text
stringlengths
8
4.13M
use std::option; use std::vec; use {MAX_QOS}; use error::Result; use mqtt3::{SubscribeTopic, TopicPath, PacketIdentifier, QoS}; #[derive(Debug, Clone)] pub struct Subscription { pub pid: PacketIdentifier, pub topic_path: TopicPath, pub qos: QoS } impl Subscription { pub fn to_subscribe_topic(&self) -> SubscribeTopic { SubscribeTopic { topic_path: self.topic_path.path(), qos: self.qos } } } pub trait ToSubTopics { type Iter: Iterator<Item=SubscribeTopic>; fn to_subscribe_topics(&self) -> Result<Self::Iter>; } impl ToSubTopics for SubscribeTopic { type Iter = option::IntoIter<SubscribeTopic>; fn to_subscribe_topics(&self) -> Result<Self::Iter> { Ok(Some(self.clone()).into_iter()) } } impl ToSubTopics for Vec<SubscribeTopic> { type Iter = vec::IntoIter<SubscribeTopic>; fn to_subscribe_topics(&self) -> Result<Self::Iter> { Ok(self.clone().into_iter()) //FIXME: } } impl<'a> ToSubTopics for &'a str { type Iter = option::IntoIter<SubscribeTopic>; fn to_subscribe_topics(&self) -> Result<Self::Iter> { Ok(Some(SubscribeTopic { topic_path: self.to_string(), qos: MAX_QOS }).into_iter()) } } impl ToSubTopics for (String, QoS) { type Iter = option::IntoIter<SubscribeTopic>; fn to_subscribe_topics(&self) -> Result<Self::Iter> { let (ref topic_path, qos): (String, QoS) = *self; Ok(Some(SubscribeTopic { topic_path: topic_path.clone(), qos: qos }).into_iter()) } } pub trait ToUnSubTopics { type Iter: Iterator<Item=String>; fn to_unsubscribe_topics(&self) -> Result<Self::Iter>; } impl ToUnSubTopics for Vec<String> { type Iter = vec::IntoIter<String>; fn to_unsubscribe_topics(&self) -> Result<Self::Iter> { Ok(self.clone().into_iter()) } } impl<'a> ToUnSubTopics for &'a str { type Iter = option::IntoIter<String>; fn to_unsubscribe_topics(&self) -> Result<Self::Iter> { Ok(Some(self.to_string()).into_iter()) } }
use crate::device::Device; use failure::Error; pub trait Visuals { fn setup(&mut self) -> Result<(), Error>; fn done(&mut self, device: &mut Device) -> Result<(), Error>; /// Returns `false` if the debugger should continue running. /// `true` will cause the debugger to exit. fn draw(&mut self, _: &mut Device) -> Result<bool, Error>; } pub struct NoopVisuals; impl Visuals for NoopVisuals { fn setup(&mut self) -> Result<(), Error> { Ok(()) } fn done(&mut self, _: &mut Device) -> Result<(), Error> { Ok(()) } fn draw(&mut self, _: &mut Device) -> Result<bool, Error> { Ok(false) } }
use super::decode; use serde::{Deserialize, Serialize}; use rmps::Deserializer; use rmps::decode::Error; use std::io::Read; /// Transform List /// /// Instructions on how to transform coordinates for an array /// of chains to create (biological) assemblies. /// The translational component is given in **Å**. #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Transform { /// Pointers into chain data fields pub chain_index_list: Vec<i32>, /// 4x4 transformation matrix pub matrix: Vec<f32>, } /// Bio Assembly #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BioAssembly { /// Array of transform objects pub transform_list: Vec<Transform>, /// Name of the biological assembly pub name: String, } /// Unique molecular entities within the structure. /// /// Each entry in [`chain_index_list`](#structfield.chain_index_list) /// represents an instance of that entity in the structure. /// /// The entries of [`chain_index_list`](#structfield.chain_index_list) are /// indices into the [`Mmtf.chain_id_list`](struct.Mmtf.html#structfield.chain_id_list) and /// [`Mmtf.chain_name_list`](struct.Mmtf.html#structfield.chain_name_list) fields. /// The sequence string contains the full construct, not just /// the resolved residues. Its characters are referenced by the /// entries of the [`Mmtf.sequence_index_list`](struct.Mmtf.html#structfield.sequence_index_list) field. /// Further, characters follow the IUPAC single letter code for protein /// or *DNA/RNA* residues, otherwise the character 'X'. #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Entity { /// Pointers into chain data fields pub chain_index_list: Vec<i32>, ///Description of the entity pub description: String, /// Name of the entity type /// /// *Note*: This field will be renamed to `type` by serde #[serde(rename = "type")] pub _type: String, /// Sequence of the full construct in one-letter-code pub sequence: String, } /// Group data /// /// The fields in the following sections hold group-related data. /// The `mmCIF` format allows for so-called micro-heterogeneity on /// the group-level. For groups (residues) with micro-heterogeneity /// there are two or more entries given that have the same sequence /// index, group id (and insertion code) but are of a different group /// type. The defining property is their identical sequence index. #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GroupType { /// `Vec` of formal charges pub formal_charge_list: Vec<i32>, /// `Vec` of atom names, 0 to 5 character `Strings` pub atom_name_list: Vec<String>, /// `Vec` of elements, 0 to 3 character `Strings` /// /// *Note*: This field is `Optional` pub element_list: Option<Vec<String>>, /// `Vec` of bonded atom indices pub bond_atom_list: Vec<i32>, /// `Vec` of bond orders as Integers between 1 and 4 pub bond_order_list: Vec<i32>, /// The name of the group, 0 to 5 characters pub group_name: String, /// The single letter code, 1 character pub single_letter_code: String, /// The chemical component type pub chem_comp_type: String, } /// MMTF Fields #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Mmtf { /// The version number of the specification the file adheres to. pub mmtf_version: String, /// The name and version of the software used to produce the file. /// For development versions it can be useful to also include the /// checksum of the commit. The main purpose of this field is to /// identify the software that has written a file, for instance /// because it has format errors. pub mmtf_producer: String, /// Array of six values defining the unit cell. The first three /// entries are the length of the sides *a*, *b*, and *c* in **Å**. /// The last three angles are the *alpha*, *beta*, and *gamma* angles in **degree**. pub unit_cell: Option<Vec<f64>>, /// The [Hermann-Mauguin](https://en.wikipedia.org/wiki/Hermann–Mauguin_notation) /// space-group symbol. pub space_group: Option<String>, /// An ID for the structure, for example the PDB ID if applicable. /// If not in conflict with the format of the ID, it must be given /// in uppercase. pub structure_id: Option<String>, /// A short description of the structural data included in the file. pub title: Option<String>, /// A date that relates to the deposition of the structure in a /// database, e.g. the wwPDB archive. /// Type: String with the format YYYY-MM-DD pub deposition_date: Option<String>, /// A date that relates to the release of the structure in a /// database, e.g. the wwPDB archive. /// /// *Type*: `String` with the format `YYYY-MM-DD` pub release_date: Option<String>, /// Array of arrays representing *4x4* transformation matrices that /// are stored linearly in row major order. Thus, the translational /// component comprises the 4th, 8th, and 12th element. /// The transformation matrices describe noncrystallographic symmetry /// operations needed to create all molecules in the unit cell. pub ncs_operator_list: Option<Vec<[f32; 16]>>, /// `Vec` of [BioAssembly](BioAssembly) objects. pub bio_assembly_list: Option<Vec<BioAssembly>>, /// `Vec` of unique molecular entities within the structure. pub entity_list: Option<Vec<Entity>>, /// The array of experimental methods employed for structure determination. pub experimental_methods: Option<Vec<String>>, /// The experimental resolution in Angstrom. If not applicable the field must be omitted. pub resolution: Option<f64>, /// The R-free value. If not applicable the field must be omitted. pub r_free: Option<f32>, /// The R-work value. If not applicable the field must be omitted. pub r_work: Option<f64>, /// The overall number of bonds. This number must reflect both the /// bonds given in [`bond_atom_list`](#structfield.bond_atom_list) /// and the bonds given in the [`GroupType.bond_atom_list`](GroupType) /// entries in [`group_list`](#structfield.group_list) pub num_bonds: i32, /// The overall number of atoms in the structure. This also includes /// atoms at alternate locations ([alt_loc_list](#structfield.alt_loc_list)). pub num_atoms: i32, /// The overall number of groups in the structure. This also includes extra /// groups due to micro-heterogeneity. pub num_groups: i32, /// The overall number of chains in the structure. pub num_chains: i32, /// The overall number of models in the structure. pub num_models: i32, /// `Vec` of [`GroupType`](GroupType) objects. pub group_list: Vec<GroupType>, /// Pairs of values represent indices of covalently bonded atoms. /// The indices point to the Atom data arrays. Only covalent bonds may be given. #[serde(deserialize_with = "decode::as_decoder")] pub bond_atom_list: Vec<i32>, /// Array of bond orders for bonds in [`bond_atom_list`](#structfield.bond_atom_list). /// /// *Note*: Must be values between 1 and 4, defining **single**, /// **double**, **triple**, and **quadruple** bonds. #[serde(deserialize_with = "decode::as_decoder")] pub bond_order_list: Option<Vec<i8>>, /// Array of *x* atom coordinates, in **Å**. One entry for each atom and coordinate. #[serde(deserialize_with = "decode::as_decoder")] pub x_coord_list: Vec<f32>, /// Array of *y* atom coordinates, in **Å**. One entry for each atom and coordinate. #[serde(deserialize_with = "decode::as_decoder")] pub y_coord_list: Vec<f32>, /// Array of *z* atom coordinates, in **Å**. One entry for each atom and coordinate. #[serde(deserialize_with = "decode::as_decoder")] pub z_coord_list: Vec<f32>, /// Array of atom B-factors in in **Å^2**. One entry for each atom. #[serde(deserialize_with = "decode::as_decoder")] pub b_factor_list: Option<Vec<f32>>, /// `Vec` of atom serial numbers. One entry for each atom. #[serde(deserialize_with = "decode::as_decoder")] pub atom_id_list: Option<Vec<i32>>, /// `Vec` of alternate location labels, one for each atom. /// The lack of an alternate location label must be denoted by a 0 byte. #[serde(deserialize_with = "decode::as_decoder")] pub alt_loc_list: Option<Vec<char>>, /// `Vec` of atom occupancies, one for each atom. #[serde(deserialize_with = "decode::as_decoder")] pub occupancy_list: Option<Vec<f32>>, /// `Vec` of group (residue) numbers. One entry for each group/residue. #[serde(deserialize_with = "decode::as_decoder")] pub group_id_list: Vec<i32>, /// `Vec` of pointers to [`GroupType`](GroupType) entries /// in [`group_list`](#structfield.group_list) by their keys. /// One entry for each residue, thus the number of residues /// is equal to the length of this field. #[serde(deserialize_with = "decode::as_decoder")] pub group_type_list: Vec<i32>, /// Array of secondary structure assignments coded according /// to the following table, which shows the eight different /// types of secondary structure the /// [DSSP](https://dx.doi.org/10.1002%2Fbip.360221211) /// algorithm distinguishes. If the field is included there /// must be an entry for each group (residue) either in all /// models or only in the first model. /// /// | Code | Name | /// |------|--------------| /// | 0 | pi helix | /// | 1 | bend | /// | 2 | alpha helix | /// | 3 | extended | /// | 4 | 3-10 helix | /// | 5 | bridge | /// | 6 | turn | /// | 7 | coil | /// | -1 | undefined | #[serde(deserialize_with = "decode::as_decoder")] pub sec_struct_list: Option<Vec<i8>>, /// Array of insertion codes, one for each group (residue). /// The lack of an insertion code must be denoted by a 0 byte. #[serde(deserialize_with = "decode::as_decoder")] pub ins_code_list: Option<Vec<char>>, /// Array of indices that point into the [`sequence`](struct.Entity.html#structfield.sequence) /// property of an [`Entity`](Entity) object in the [`entity_list`](#structfield.entity_list) field that /// is associated with the chain the group belongs to (i.e. the index of the chain is /// included in the [`chain_index_list`](struct.Entity.html#structfield.chain_index_list) of the `entity`). /// There is one entry for each group (residue). It must be set to -1 when a group entry has no associated entity /// (and thus no sequence), for example water molecules. #[serde(deserialize_with = "decode::as_decoder")] pub sequence_index_list: Option<Vec<i32>>, /// `Vec` of chain IDs, for storing data from `mmCIF` files. /// This field should contain the value from `the label_asym_id` `mmCIF` data item /// and the [`chain_name_list`](#structfield.chain_name_list) the `auth_asym_id` /// `mmCIF` data item. /// /// In PDB files there is only a single name/identifier for chains that corresponds /// to the `auth_asym_id` item. When there is only a single chain identifier available /// it must be stored in the `chain_id_list` field. #[serde(deserialize_with = "decode::as_decoder")] pub chain_id_list: Vec<String>, /// `Vec` of chain names. This field allows to specify an additional set of labels/names /// for chains. /// /// For example, it can be used to store both, the `label_asym_id` /// (in [`chain_id_list`](#structfield.chain_id_list)) and the `auth_asym_id` /// (in [`chain_name_list`](#structfield.chain_name_list)) from mmCIF files. #[serde(deserialize_with = "decode::as_decoder")] pub chain_name_list: Option<Vec<String>>, /// `Vec` of the number of groups (aka residues) in each chain. /// The number of chains is thus equal to the length of the /// `groups_per_chain` field. /// In conjunction with [`chains_per_model`](#structfield.chains_per_model), /// the array allows looping over all chains pub groups_per_chain: Vec<i32>, /// The number of models in a structure is equal to the length of the /// `chains_per_model` field. /// The `chains_per_model` field also defines which chains belong to each model. pub chains_per_model: Vec<i32>, } impl Mmtf { /// Deserialize a `MMTF` from given file /// /// # Examples /// /// ``` /// # use std::path::Path; /// # use std::env; /// use std::fs::File; /// use mmtf::Mmtf; /// /// # let file_path = Path::new(&env::current_dir().unwrap()) /// # .join("tests") /// # .join("data") /// # .join("173D.mmtf"); /// # let display = file_path.display(); /// let mmtf_file = File::open(&file_path).unwrap(); /// let mmtf = Mmtf::from(&mmtf_file).unwrap(); /// /// assert_eq!("1.0.0", mmtf.mmtf_version); /// ``` pub fn from<R: Read>(r: R) -> Result<Self, Error> { let mut de = Deserializer::new(r); let mmtf: Mmtf = Deserialize::deserialize(&mut de)?; Ok(mmtf) } }
//use std::io::{stdio}; use std::io; use std::thread; use std::rand; fn start_getting_weather() { let mut loop_counter = 0; let delay = 3000; loop { loop_counter += 1; println!("counter: {}", loop_counter); thread::spawn(move || test_fn()); //main_weather_getter(); thread::sleep_ms(delay); } } fn test_fn() { for i in 1..5 { thread::spawn(move || { let x: u32 = randTime(); thread::sleep_ms(x); println!("{}", i); }); } } fn test_print(x: i32) { println!("called! {}", x) } fn randTime() -> i32 { let n: i32 = (rand::random() % 100i64) + 1i64; return n } fn main() { thread::spawn(move || start_getting_weather()); // Prevent main from exiting early let mut stdin = io::stdin(); let input = &mut String::new(); // loop { // input.clear(); // stdin.read_line(input); // println!("{}", input); // } // prevent main from exiting input.clear(); stdin.read_line(input); println!("{}", input); }
use crate::prelude::*; use std::os::raw::c_void; #[repr(C)] #[derive(Debug)] pub struct VkDisplayPresentInfoKHR { pub sType: VkStructureType, pub pNext: *const c_void, pub srcRect: VkRect2D, pub dstRect: VkRect2D, pub persistent: VkBool32, }
// 5 lines of code that converts your JSON string into NBT format. // // This piece of code performs the transcode through `serde_transcode` crate. // It prints NBT transcript for human readbility using `Serializer::transcript`; // if you want NBT bytes, consider using `Serializer::binary` instead. // // Due to the loss of number accuracy in JSON, this program only support limited // input data type from JSON, for example objects and strings. However, if we do // contrarily from NBT to JSON, full transcode support is possible as the former // does record all the data types for numbers. fn main() { use std::io; let str_input = r#"{"nick":"luojia65","school":{"name":"hust","985":true}}"#; let mut deserializer = serde_json::Deserializer::from_str(str_input); let mut serializer = coruscant_nbt::Serializer::transcript(io::stdout(), "person"); serde_transcode::transcode(&mut deserializer, &mut serializer).expect("serde transcode"); }
use std::sync::Arc; use async_graphql_parser::types::ExecutableDocument; use async_graphql_value::Variables; use futures_util::{stream::BoxStream, TryFutureExt}; use opentelemetry::{ trace::{FutureExt, SpanKind, TraceContextExt, Tracer}, Context as OpenTelemetryContext, Key, }; use crate::{ extensions::{ Extension, ExtensionContext, ExtensionFactory, NextExecute, NextParseQuery, NextRequest, NextResolve, NextSubscribe, NextValidation, ResolveInfo, }, Response, ServerError, ServerResult, ValidationResult, Value, }; const KEY_SOURCE: Key = Key::from_static_str("graphql.source"); const KEY_VARIABLES: Key = Key::from_static_str("graphql.variables"); const KEY_PARENT_TYPE: Key = Key::from_static_str("graphql.parentType"); const KEY_RETURN_TYPE: Key = Key::from_static_str("graphql.returnType"); const KEY_ERROR: Key = Key::from_static_str("graphql.error"); const KEY_COMPLEXITY: Key = Key::from_static_str("graphql.complexity"); const KEY_DEPTH: Key = Key::from_static_str("graphql.depth"); /// OpenTelemetry extension #[cfg_attr(docsrs, doc(cfg(feature = "opentelemetry")))] pub struct OpenTelemetry<T> { tracer: Arc<T>, } impl<T> OpenTelemetry<T> { /// Use `tracer` to create an OpenTelemetry extension. pub fn new(tracer: T) -> OpenTelemetry<T> where T: Tracer + Send + Sync + 'static, <T as Tracer>::Span: Sync + Send, { Self { tracer: Arc::new(tracer), } } } impl<T> ExtensionFactory for OpenTelemetry<T> where T: Tracer + Send + Sync + 'static, <T as Tracer>::Span: Sync + Send, { fn create(&self) -> Arc<dyn Extension> { Arc::new(OpenTelemetryExtension { tracer: self.tracer.clone(), }) } } struct OpenTelemetryExtension<T> { tracer: Arc<T>, } #[async_trait::async_trait] impl<T> Extension for OpenTelemetryExtension<T> where T: Tracer + Send + Sync + 'static, <T as Tracer>::Span: Sync + Send, { async fn request(&self, ctx: &ExtensionContext<'_>, next: NextRequest<'_>) -> Response { next.run(ctx) .with_context(OpenTelemetryContext::current_with_span( self.tracer .span_builder("request") .with_kind(SpanKind::Server) .start(&*self.tracer), )) .await } fn subscribe<'s>( &self, ctx: &ExtensionContext<'_>, stream: BoxStream<'s, Response>, next: NextSubscribe<'_>, ) -> BoxStream<'s, Response> { Box::pin( next.run(ctx, stream) .with_context(OpenTelemetryContext::current_with_span( self.tracer .span_builder("subscribe") .with_kind(SpanKind::Server) .start(&*self.tracer), )), ) } async fn parse_query( &self, ctx: &ExtensionContext<'_>, query: &str, variables: &Variables, next: NextParseQuery<'_>, ) -> ServerResult<ExecutableDocument> { let attributes = vec![ KEY_SOURCE.string(query.to_string()), KEY_VARIABLES.string(serde_json::to_string(variables).unwrap()), ]; let span = self .tracer .span_builder("parse") .with_kind(SpanKind::Server) .with_attributes(attributes) .start(&*self.tracer); async move { let res = next.run(ctx, query, variables).await; if let Ok(doc) = &res { OpenTelemetryContext::current() .span() .set_attribute(KEY_SOURCE.string(ctx.stringify_execute_doc(doc, variables))); } res } .with_context(OpenTelemetryContext::current_with_span(span)) .await } async fn validation( &self, ctx: &ExtensionContext<'_>, next: NextValidation<'_>, ) -> Result<ValidationResult, Vec<ServerError>> { let span = self .tracer .span_builder("validation") .with_kind(SpanKind::Server) .start(&*self.tracer); next.run(ctx) .with_context(OpenTelemetryContext::current_with_span(span)) .map_ok(|res| { let current_cx = OpenTelemetryContext::current(); let span = current_cx.span(); span.set_attribute(KEY_COMPLEXITY.i64(res.complexity as i64)); span.set_attribute(KEY_DEPTH.i64(res.depth as i64)); res }) .await } async fn execute( &self, ctx: &ExtensionContext<'_>, operation_name: Option<&str>, next: NextExecute<'_>, ) -> Response { let span = self .tracer .span_builder("execute") .with_kind(SpanKind::Server) .start(&*self.tracer); next.run(ctx, operation_name) .with_context(OpenTelemetryContext::current_with_span(span)) .await } async fn resolve( &self, ctx: &ExtensionContext<'_>, info: ResolveInfo<'_>, next: NextResolve<'_>, ) -> ServerResult<Option<Value>> { let span = if !info.is_for_introspection { let attributes = vec![ KEY_PARENT_TYPE.string(info.parent_type.to_string()), KEY_RETURN_TYPE.string(info.return_type.to_string()), ]; Some( self.tracer .span_builder(info.path_node.to_string()) .with_kind(SpanKind::Server) .with_attributes(attributes) .start(&*self.tracer), ) } else { None }; let fut = next.run(ctx, info).inspect_err(|err| { let current_cx = OpenTelemetryContext::current(); current_cx .span() .add_event("error".to_string(), vec![KEY_ERROR.string(err.to_string())]); }); match span { Some(span) => { fut.with_context(OpenTelemetryContext::current_with_span(span)) .await } None => fut.await, } } }
use tide_tracing::TraceMiddleware; use { tide::{Error, Response, Result, StatusCode}, tracing::Level, }; #[async_std::main] async fn main() -> tide::Result<()> { let subscriber = tracing_subscriber::fmt() .with_max_level(Level::TRACE) .finish(); tracing::subscriber::set_global_default(subscriber).expect("no global subscriber has been set"); let mut app = tide::Server::new(); app.with(TraceMiddleware::new()); app.at("/working_endpoint") .get(|_| async { Ok(Response::new(StatusCode::Ok)) }); app.at("/client_error") .get(|_| async { Ok(Response::new(StatusCode::NotFound)) }); app.at("/internal_error").get(|_| async { Result::<Response>::Err(Error::from_str( StatusCode::ServiceUnavailable, "This message will be displayed", )) }); app.listen("localhost:8081").await?; Ok(()) }
use crate::common::types::{PointVertex, Real, TspResult}; use crate::common::utils::{dist, read_lines, to_points}; use spade::rtree::RTree; use typenum::U2; pub fn solve_for_file(filename: &str) -> TspResult { let file_contents: Vec<Vec<Real>> = read_lines(filename); let points: Vec<PointVertex<Real, U2>> = to_points(file_contents); let home_vertex = points[0].clone(); // The first point should be the home vertex. let mut rtree = RTree::bulk_load(points); // Iterate over all the vertices in the graph, starting from the first vertex. let mut result = 0f64; let mut prev = home_vertex.clone(); rtree.remove(&prev); // Continue computing the distance while there are still vertices to visit. while rtree.size() != 0 { // Get the nearest neighbors to the last vertex we visited. let mut nns = rtree.nearest_neighbors(&prev); // Sort by vertex ID and get the head of the sorted list. nns.sort(); let nn = nns.iter().nth(0).unwrap(); // Compute the Euclidean distance from the last vertex we visited to the next one. result += dist(prev.point, nn.point); // Mark the next vertex as the current/last one, and remove it from the set of // vertices to visit. prev = (*nn).clone(); rtree.remove(&prev); } // Lastly, compute the distance from the last visited vertex back to the starting point. result = result + dist(prev.point, home_vertex.point); // Round down and cast the result to an integer. result.floor() as TspResult } pub fn solve() { let result = solve_for_file("resources/week3/tsp.txt"); println!("{}", result); }
//https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/ use std::cmp::min; impl Solution { pub fn count_good_rectangles(rectangles: Vec<Vec<i32>>) -> i32 { let mut max_square_count = 0; let mut max_square_size = 0; let mut tmp_square = 0; for i in 0..rectangles.len() { tmp_square = min(rectangles[i][0], rectangles[i][1]); if tmp_square > max_square_size { max_square_size = tmp_square; max_square_count = 1; } else if tmp_square == max_square_size { max_square_count += 1; } } max_square_count } }
// Maybe implement a pallette struct #[derive(Default)] pub struct Color { r: u8, g: u8, b: u8, } #[derive(Default)] pub struct Pallete { colors: [Color; 16], }
//! An actor system where each server exposes a rewritable single-copy register. Servers do not //! provide consensus. use stateright::actor::register::{RegisterActor, RegisterMsg, RegisterMsg::*}; use stateright::actor::{Actor, ActorModel, Id, Network, Out}; use stateright::report::WriteReporter; use stateright::semantics::register::Register; use stateright::semantics::LinearizabilityTester; use stateright::{Checker, Expectation, Model}; use std::borrow::Cow; type RequestId = u64; type Value = char; #[derive(Clone)] struct SingleCopyActor; impl Actor for SingleCopyActor { type Msg = RegisterMsg<RequestId, Value, ()>; type State = Value; type Timer = (); fn on_start(&self, _id: Id, _o: &mut Out<Self>) -> Self::State { Value::default() } fn on_msg( &self, _id: Id, state: &mut Cow<Self::State>, src: Id, msg: Self::Msg, o: &mut Out<Self>, ) { match msg { Put(req_id, value) => { *state.to_mut() = value; o.send(src, PutOk(req_id)); } Get(req_id) => { o.send(src, GetOk(req_id, **state)); } _ => {} } } } #[derive(Clone)] struct SingleCopyModelCfg { client_count: usize, server_count: usize, network: Network<<SingleCopyActor as Actor>::Msg>, } impl SingleCopyModelCfg { fn into_model( self, ) -> ActorModel<RegisterActor<SingleCopyActor>, Self, LinearizabilityTester<Id, Register<Value>>> { ActorModel::new( self.clone(), LinearizabilityTester::new(Register(Value::default())), ) .actors((0..self.server_count).map(|_| RegisterActor::Server(SingleCopyActor))) .actors((0..self.client_count).map(|_| RegisterActor::Client { put_count: 1, server_count: self.server_count, })) .init_network(self.network) .property(Expectation::Always, "linearizable", |_, state| { state.history.serialized_history().is_some() }) .property(Expectation::Sometimes, "value chosen", |_, state| { for env in state.network.iter_deliverable() { if let RegisterMsg::GetOk(_req_id, value) = env.msg { if *value != Value::default() { return true; } } } false }) .record_msg_in(RegisterMsg::record_returns) .record_msg_out(RegisterMsg::record_invocations) } } #[cfg(test)] #[test] fn can_model_single_copy_register() { use stateright::actor::ActorModelAction::Deliver; // Linearizable if only one server. DFS for this one. let checker = SingleCopyModelCfg { client_count: 2, server_count: 1, network: Network::new_unordered_nonduplicating([]), } .into_model() .checker() .spawn_dfs() .join(); checker.assert_properties(); #[rustfmt::skip] checker.assert_discovery("value chosen", vec![ Deliver { src: Id::from(2), dst: Id::from(0), msg: Put(2, 'B') }, Deliver { src: Id::from(0), dst: Id::from(2), msg: PutOk(2) }, Deliver { src: Id::from(2), dst: Id::from(0), msg: Get(4) }, ]); assert_eq!(checker.unique_state_count(), 93); // Otherwise (if more than one server) then not linearizabile. BFS this time. let checker = SingleCopyModelCfg { client_count: 2, server_count: 2, network: Network::new_unordered_nonduplicating([]), } .into_model() .checker() .spawn_bfs() .join(); #[rustfmt::skip] checker.assert_discovery("linearizable", vec![ Deliver { src: Id::from(3), dst: Id::from(1), msg: Put(3, 'B') }, Deliver { src: Id::from(1), dst: Id::from(3), msg: PutOk(3) }, Deliver { src: Id::from(3), dst: Id::from(0), msg: Get(6) }, Deliver { src: Id::from(0), dst: Id::from(3), msg: GetOk(6, '\u{0}') }, ]); #[rustfmt::skip] checker.assert_discovery("value chosen", vec![ Deliver { src: Id::from(3), dst: Id::from(1), msg: Put(3, 'B') }, Deliver { src: Id::from(1), dst: Id::from(3), msg: PutOk(3) }, Deliver { src: Id::from(2), dst: Id::from(0), msg: Put(2, 'A') }, Deliver { src: Id::from(3), dst: Id::from(0), msg: Get(6) }, ]); assert_eq!(checker.unique_state_count(), 20); } fn main() -> Result<(), pico_args::Error> { use stateright::actor::spawn; use std::net::{Ipv4Addr, SocketAddrV4}; env_logger::init_from_env(env_logger::Env::default().default_filter_or("info")); // `RUST_LOG=${LEVEL}` env variable to override let mut args = pico_args::Arguments::from_env(); match args.subcommand()?.as_deref() { Some("check") => { let client_count = args.opt_free_from_str()?.unwrap_or(2); let network = args .opt_free_from_str()? .unwrap_or(Network::new_unordered_nonduplicating([])); println!( "Model checking a single-copy register with {} clients.", client_count ); SingleCopyModelCfg { client_count, server_count: 1, network, } .into_model() .checker() .threads(num_cpus::get()) .spawn_dfs() .report(&mut WriteReporter::new(&mut std::io::stdout())); } Some("explore") => { let client_count = args.opt_free_from_str()?.unwrap_or(2); let address = args .opt_free_from_str()? .unwrap_or("localhost:3000".to_string()); let network = args .opt_free_from_str()? .unwrap_or(Network::new_unordered_nonduplicating([])); println!( "Exploring state space for single-copy register with {} clients on {}.", client_count, address ); SingleCopyModelCfg { client_count, server_count: 1, network, } .into_model() .checker() .threads(num_cpus::get()) .serve(address); } Some("spawn") => { let port = 3000; println!(" A server that implements a single-copy register."); println!(" You can monitor and interact using tcpdump and netcat."); println!(" Use `tcpdump -D` if you see error `lo0: No such device exists`."); println!("Examples:"); println!("$ sudo tcpdump -i lo0 -s 0 -nnX"); println!("$ nc -u localhost {}", port); println!( "{}", serde_json::to_string(&RegisterMsg::Put::<RequestId, Value, ()>(1, 'X')).unwrap() ); println!( "{}", serde_json::to_string(&RegisterMsg::Get::<RequestId, Value, ()>(2)).unwrap() ); println!(); // WARNING: Omits `ordered_reliable_link` to keep the message // protocol simple for `nc`. spawn( serde_json::to_vec, |bytes| serde_json::from_slice(bytes), vec![( SocketAddrV4::new(Ipv4Addr::LOCALHOST, port), SingleCopyActor, )], ) .unwrap(); } _ => { println!("USAGE:"); println!(" ./single-copy-register check [CLIENT_COUNT]"); println!(" ./single-copy-register explore [CLIENT_COUNT] [ADDRESS] [NETWORK]"); println!(" ./single-copy-register spawn"); println!( "NETWORK: {}", Network::<<SingleCopyActor as Actor>::Msg>::names().join(" | ") ); } } Ok(()) }
//! Simple code generator for manual parsing //! //! ## Attributes //! //! ### Struct //! //! There are several attributes that control behaviour of parser //! Each, attached to struct's field //! //! - `starts_with = <prefix>` - Specifies string with which next parse step should start(can be stacked). Errors if prefix is missing. //! - `ends_with = <prefix>` - Specifies string with which parse step should end(can be stacked). Errors if suffix is missing. If empty, expects EOF. //! - `skip = <chars>` - Specifies to skip characters, until not meeting character outside of specified in string. //! - `skip(ws)` - Specifies to skip all white space characters. //! - `format(<format>)` - Specifies list of characters that should contain value to parse from. //! - `format(not(<format>))` - Specifies list of characters that should contain value to parse from. //! //! ##### Formats //! //! - Literal string - When string is specified as argument to `format`, it is used as set of characters. //! - `numeric` - When specified, match using `char::is_numeric()` //! - `digit(<base>)` - When specified, match using `char::is_digit(<base>)` //! - `ascii` - When specified, match using `char::is_ascii()` //! - `alphabetic` - When specified, match using `char::is_alphabetic()` //! //! ### Enum //! //! - `format = <format>` - Specifies string to match against. //! - `case` - Specifies case sensitive match. By default it is insensitive. //! - `default` - Specifies variant as taking default value. Should take only single `String` and //! there can be only one //! //! ## Usage //! //! ### Struct //! //! ```rust //! use std::str::FromStr; //! //! #[derive(banjin::Parser)] //! pub struct Data { //! #[starts_with = "prefix"] //! #[skip(ws)] //! #[starts_with = "+"] //! #[skip(ws)] //! #[format(ascii)] //! #[format(digit(10))] //! pub first: u32, //! #[skip(ws)] //! #[format(not("d"))] //! #[format("13")] //! #[ends_with = "d"] //! #[ends_with = ""] //! pub second: String, //! } //! //! fn main() { //! let data = Data::from_str("prefix + 666 13d").expect("Parse"); //! assert_eq!(data.first, 666); //! assert_eq!(data.second, "13"); //! //! let data = Data::from_str("prefix + 666 13"); //! assert!(data.is_err()); //! //! let data = Data::from_str("prefix 666 13d"); //! assert!(data.is_err()); //! //! let data = Data::from_str("prefix + 666 13dg"); //! assert!(data.is_err()); //! //! let data = Data::from_str(""); //! assert!(data.is_err()); //! } //! //! ``` //! //! ### Enum //! //! ```rust //! use std::str::FromStr; //! //! #[derive(banjin::Parser, PartialEq, Eq, Debug)] //! enum Gender { //! Male, //! #[case] //! Female, //! #[default] //! Other(String) //! } //! //! fn main() { //! let gender = Gender::from_str("male").expect("Parse"); //! assert_eq!(gender, Gender::Male); //! //! let gender = Gender::from_str("female").expect("Parse"); //! match gender { //! Gender::Other(text) => assert_eq!(text, "female"), //! _ => panic!("Unexpected!") //! } //! //! let gender = Gender::from_str("none").expect("Parse"); //! match gender { //! Gender::Other(text) => assert_eq!(text, "none"), //! _ => panic!("Unexpected!") //! } //! } //! ``` extern crate proc_macro; use proc_macro::TokenStream; #[cfg(feature = "no_std")] const FROM_STR: &'static str = "core::str::FromStr"; #[cfg(not(feature = "no_std"))] const FROM_STR: &'static str = "std::str::FromStr"; mod from_struct; mod from_enum; fn generate(ast: syn::DeriveInput) -> String { match ast.data { syn::Data::Struct(ref data) => from_struct::parse(&ast, data), syn::Data::Enum(ref data) => from_enum::parse(&ast, data), _ => panic!("derive(Parser) is available for structs only"), } } #[proc_macro_derive(Parser, attributes(skip, format, starts_with, ends_with, case, default))] pub fn parser_derive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); generate(ast).parse().expect("To parse generate") }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtGui/qfontinfo.h // dst-file: /src/gui/qfontinfo.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use std::ops::Deref; use super::super::core::qstring::*; // 771 use super::qfont::*; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QFontInfo_Class_Size() -> c_int; // proto: bool QFontInfo::rawMode(); fn C_ZNK9QFontInfo7rawModeEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: bool QFontInfo::exactMatch(); fn C_ZNK9QFontInfo10exactMatchEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: int QFontInfo::pointSize(); fn C_ZNK9QFontInfo9pointSizeEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QFontInfo::QFontInfo(const QFontInfo & ); fn C_ZN9QFontInfoC2ERKS_(arg0: *mut c_void) -> u64; // proto: QString QFontInfo::family(); fn C_ZNK9QFontInfo6familyEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QFontInfo::bold(); fn C_ZNK9QFontInfo4boldEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: qreal QFontInfo::pointSizeF(); fn C_ZNK9QFontInfo10pointSizeFEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: bool QFontInfo::fixedPitch(); fn C_ZNK9QFontInfo10fixedPitchEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: bool QFontInfo::overline(); fn C_ZNK9QFontInfo8overlineEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QFontInfo::swap(QFontInfo & other); fn C_ZN9QFontInfo4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QFontInfo::QFontInfo(const QFont & ); fn C_ZN9QFontInfoC2ERK5QFont(arg0: *mut c_void) -> u64; // proto: int QFontInfo::pixelSize(); fn C_ZNK9QFontInfo9pixelSizeEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: bool QFontInfo::strikeOut(); fn C_ZNK9QFontInfo9strikeOutEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QFontInfo::~QFontInfo(); fn C_ZN9QFontInfoD2Ev(qthis: u64 /* *mut c_void*/); // proto: bool QFontInfo::italic(); fn C_ZNK9QFontInfo6italicEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: bool QFontInfo::underline(); fn C_ZNK9QFontInfo9underlineEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QString QFontInfo::styleName(); fn C_ZNK9QFontInfo9styleNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: int QFontInfo::weight(); fn C_ZNK9QFontInfo6weightEv(qthis: u64 /* *mut c_void*/) -> c_int; } // <= ext block end // body block begin => // class sizeof(QFontInfo)=1 #[derive(Default)] pub struct QFontInfo { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QFontInfo { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QFontInfo { return QFontInfo{qclsinst: qthis, ..Default::default()}; } } // proto: bool QFontInfo::rawMode(); impl /*struct*/ QFontInfo { pub fn rawMode<RetType, T: QFontInfo_rawMode<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rawMode(self); // return 1; } } pub trait QFontInfo_rawMode<RetType> { fn rawMode(self , rsthis: & QFontInfo) -> RetType; } // proto: bool QFontInfo::rawMode(); impl<'a> /*trait*/ QFontInfo_rawMode<i8> for () { fn rawMode(self , rsthis: & QFontInfo) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo7rawModeEv()}; let mut ret = unsafe {C_ZNK9QFontInfo7rawModeEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: bool QFontInfo::exactMatch(); impl /*struct*/ QFontInfo { pub fn exactMatch<RetType, T: QFontInfo_exactMatch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.exactMatch(self); // return 1; } } pub trait QFontInfo_exactMatch<RetType> { fn exactMatch(self , rsthis: & QFontInfo) -> RetType; } // proto: bool QFontInfo::exactMatch(); impl<'a> /*trait*/ QFontInfo_exactMatch<i8> for () { fn exactMatch(self , rsthis: & QFontInfo) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo10exactMatchEv()}; let mut ret = unsafe {C_ZNK9QFontInfo10exactMatchEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: int QFontInfo::pointSize(); impl /*struct*/ QFontInfo { pub fn pointSize<RetType, T: QFontInfo_pointSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.pointSize(self); // return 1; } } pub trait QFontInfo_pointSize<RetType> { fn pointSize(self , rsthis: & QFontInfo) -> RetType; } // proto: int QFontInfo::pointSize(); impl<'a> /*trait*/ QFontInfo_pointSize<i32> for () { fn pointSize(self , rsthis: & QFontInfo) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo9pointSizeEv()}; let mut ret = unsafe {C_ZNK9QFontInfo9pointSizeEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QFontInfo::QFontInfo(const QFontInfo & ); impl /*struct*/ QFontInfo { pub fn new<T: QFontInfo_new>(value: T) -> QFontInfo { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QFontInfo_new { fn new(self) -> QFontInfo; } // proto: void QFontInfo::QFontInfo(const QFontInfo & ); impl<'a> /*trait*/ QFontInfo_new for (&'a QFontInfo) { fn new(self) -> QFontInfo { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QFontInfoC2ERKS_()}; let ctysz: c_int = unsafe{QFontInfo_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN9QFontInfoC2ERKS_(arg0)}; let rsthis = QFontInfo{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QString QFontInfo::family(); impl /*struct*/ QFontInfo { pub fn family<RetType, T: QFontInfo_family<RetType>>(& self, overload_args: T) -> RetType { return overload_args.family(self); // return 1; } } pub trait QFontInfo_family<RetType> { fn family(self , rsthis: & QFontInfo) -> RetType; } // proto: QString QFontInfo::family(); impl<'a> /*trait*/ QFontInfo_family<QString> for () { fn family(self , rsthis: & QFontInfo) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo6familyEv()}; let mut ret = unsafe {C_ZNK9QFontInfo6familyEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QFontInfo::bold(); impl /*struct*/ QFontInfo { pub fn bold<RetType, T: QFontInfo_bold<RetType>>(& self, overload_args: T) -> RetType { return overload_args.bold(self); // return 1; } } pub trait QFontInfo_bold<RetType> { fn bold(self , rsthis: & QFontInfo) -> RetType; } // proto: bool QFontInfo::bold(); impl<'a> /*trait*/ QFontInfo_bold<i8> for () { fn bold(self , rsthis: & QFontInfo) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo4boldEv()}; let mut ret = unsafe {C_ZNK9QFontInfo4boldEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: qreal QFontInfo::pointSizeF(); impl /*struct*/ QFontInfo { pub fn pointSizeF<RetType, T: QFontInfo_pointSizeF<RetType>>(& self, overload_args: T) -> RetType { return overload_args.pointSizeF(self); // return 1; } } pub trait QFontInfo_pointSizeF<RetType> { fn pointSizeF(self , rsthis: & QFontInfo) -> RetType; } // proto: qreal QFontInfo::pointSizeF(); impl<'a> /*trait*/ QFontInfo_pointSizeF<f64> for () { fn pointSizeF(self , rsthis: & QFontInfo) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo10pointSizeFEv()}; let mut ret = unsafe {C_ZNK9QFontInfo10pointSizeFEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: bool QFontInfo::fixedPitch(); impl /*struct*/ QFontInfo { pub fn fixedPitch<RetType, T: QFontInfo_fixedPitch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.fixedPitch(self); // return 1; } } pub trait QFontInfo_fixedPitch<RetType> { fn fixedPitch(self , rsthis: & QFontInfo) -> RetType; } // proto: bool QFontInfo::fixedPitch(); impl<'a> /*trait*/ QFontInfo_fixedPitch<i8> for () { fn fixedPitch(self , rsthis: & QFontInfo) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo10fixedPitchEv()}; let mut ret = unsafe {C_ZNK9QFontInfo10fixedPitchEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: bool QFontInfo::overline(); impl /*struct*/ QFontInfo { pub fn overline<RetType, T: QFontInfo_overline<RetType>>(& self, overload_args: T) -> RetType { return overload_args.overline(self); // return 1; } } pub trait QFontInfo_overline<RetType> { fn overline(self , rsthis: & QFontInfo) -> RetType; } // proto: bool QFontInfo::overline(); impl<'a> /*trait*/ QFontInfo_overline<i8> for () { fn overline(self , rsthis: & QFontInfo) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo8overlineEv()}; let mut ret = unsafe {C_ZNK9QFontInfo8overlineEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QFontInfo::swap(QFontInfo & other); impl /*struct*/ QFontInfo { pub fn swap<RetType, T: QFontInfo_swap<RetType>>(& self, overload_args: T) -> RetType { return overload_args.swap(self); // return 1; } } pub trait QFontInfo_swap<RetType> { fn swap(self , rsthis: & QFontInfo) -> RetType; } // proto: void QFontInfo::swap(QFontInfo & other); impl<'a> /*trait*/ QFontInfo_swap<()> for (&'a QFontInfo) { fn swap(self , rsthis: & QFontInfo) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QFontInfo4swapERS_()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QFontInfo4swapERS_(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QFontInfo::QFontInfo(const QFont & ); impl<'a> /*trait*/ QFontInfo_new for (&'a QFont) { fn new(self) -> QFontInfo { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QFontInfoC2ERK5QFont()}; let ctysz: c_int = unsafe{QFontInfo_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN9QFontInfoC2ERK5QFont(arg0)}; let rsthis = QFontInfo{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: int QFontInfo::pixelSize(); impl /*struct*/ QFontInfo { pub fn pixelSize<RetType, T: QFontInfo_pixelSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.pixelSize(self); // return 1; } } pub trait QFontInfo_pixelSize<RetType> { fn pixelSize(self , rsthis: & QFontInfo) -> RetType; } // proto: int QFontInfo::pixelSize(); impl<'a> /*trait*/ QFontInfo_pixelSize<i32> for () { fn pixelSize(self , rsthis: & QFontInfo) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo9pixelSizeEv()}; let mut ret = unsafe {C_ZNK9QFontInfo9pixelSizeEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: bool QFontInfo::strikeOut(); impl /*struct*/ QFontInfo { pub fn strikeOut<RetType, T: QFontInfo_strikeOut<RetType>>(& self, overload_args: T) -> RetType { return overload_args.strikeOut(self); // return 1; } } pub trait QFontInfo_strikeOut<RetType> { fn strikeOut(self , rsthis: & QFontInfo) -> RetType; } // proto: bool QFontInfo::strikeOut(); impl<'a> /*trait*/ QFontInfo_strikeOut<i8> for () { fn strikeOut(self , rsthis: & QFontInfo) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo9strikeOutEv()}; let mut ret = unsafe {C_ZNK9QFontInfo9strikeOutEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QFontInfo::~QFontInfo(); impl /*struct*/ QFontInfo { pub fn free<RetType, T: QFontInfo_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QFontInfo_free<RetType> { fn free(self , rsthis: & QFontInfo) -> RetType; } // proto: void QFontInfo::~QFontInfo(); impl<'a> /*trait*/ QFontInfo_free<()> for () { fn free(self , rsthis: & QFontInfo) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QFontInfoD2Ev()}; unsafe {C_ZN9QFontInfoD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: bool QFontInfo::italic(); impl /*struct*/ QFontInfo { pub fn italic<RetType, T: QFontInfo_italic<RetType>>(& self, overload_args: T) -> RetType { return overload_args.italic(self); // return 1; } } pub trait QFontInfo_italic<RetType> { fn italic(self , rsthis: & QFontInfo) -> RetType; } // proto: bool QFontInfo::italic(); impl<'a> /*trait*/ QFontInfo_italic<i8> for () { fn italic(self , rsthis: & QFontInfo) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo6italicEv()}; let mut ret = unsafe {C_ZNK9QFontInfo6italicEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: bool QFontInfo::underline(); impl /*struct*/ QFontInfo { pub fn underline<RetType, T: QFontInfo_underline<RetType>>(& self, overload_args: T) -> RetType { return overload_args.underline(self); // return 1; } } pub trait QFontInfo_underline<RetType> { fn underline(self , rsthis: & QFontInfo) -> RetType; } // proto: bool QFontInfo::underline(); impl<'a> /*trait*/ QFontInfo_underline<i8> for () { fn underline(self , rsthis: & QFontInfo) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo9underlineEv()}; let mut ret = unsafe {C_ZNK9QFontInfo9underlineEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QString QFontInfo::styleName(); impl /*struct*/ QFontInfo { pub fn styleName<RetType, T: QFontInfo_styleName<RetType>>(& self, overload_args: T) -> RetType { return overload_args.styleName(self); // return 1; } } pub trait QFontInfo_styleName<RetType> { fn styleName(self , rsthis: & QFontInfo) -> RetType; } // proto: QString QFontInfo::styleName(); impl<'a> /*trait*/ QFontInfo_styleName<QString> for () { fn styleName(self , rsthis: & QFontInfo) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo9styleNameEv()}; let mut ret = unsafe {C_ZNK9QFontInfo9styleNameEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QFontInfo::weight(); impl /*struct*/ QFontInfo { pub fn weight<RetType, T: QFontInfo_weight<RetType>>(& self, overload_args: T) -> RetType { return overload_args.weight(self); // return 1; } } pub trait QFontInfo_weight<RetType> { fn weight(self , rsthis: & QFontInfo) -> RetType; } // proto: int QFontInfo::weight(); impl<'a> /*trait*/ QFontInfo_weight<i32> for () { fn weight(self , rsthis: & QFontInfo) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QFontInfo6weightEv()}; let mut ret = unsafe {C_ZNK9QFontInfo6weightEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // <= body block end
use bigneon_db::dev::TestProject; use bigneon_db::models::{ TicketPricing, TicketPricingEditableAttributes, TicketType, TicketTypeEditableAttributes, }; use bigneon_db::utils::errors::ErrorCode::ValidationError; use chrono::NaiveDate; use diesel::result::Error; use diesel::Connection; #[test] fn create() { let project = TestProject::new(); let conn = project.get_connection(); let event = project.create_event().finish(); let wallet_id = event.issuer_wallet(conn).unwrap().id; let sd = NaiveDate::from_ymd(2016, 7, 8).and_hms(4, 10, 11); let ed = NaiveDate::from_ymd(2016, 7, 9).and_hms(4, 10, 11); let ticket_type = event .add_ticket_type("VIP".to_string(), 100, sd, ed, wallet_id, None, conn) .unwrap(); assert_eq!(ticket_type.event_id, event.id); assert_eq!(ticket_type.name, "VIP".to_string()) } #[test] fn create_large_amount() { let project = TestProject::new(); let conn = project.get_connection(); let event = project.create_event().finish(); let wallet_id = event.issuer_wallet(conn).unwrap().id; let sd = NaiveDate::from_ymd(2016, 7, 8).and_hms(4, 10, 11); let ed = NaiveDate::from_ymd(2016, 7, 9).and_hms(4, 10, 11); let ticket_type = event .add_ticket_type("VIP".to_string(), 100_000, sd, ed, wallet_id, None, conn) .unwrap(); assert_eq!(ticket_type.event_id, event.id); assert_eq!(ticket_type.name, "VIP".to_string()) } #[test] fn validate_record() { let project = TestProject::new(); let event = project.create_event().with_tickets().finish(); let ticket_type = &event.ticket_types(project.get_connection()).unwrap()[0]; let start_date1 = NaiveDate::from_ymd(2016, 7, 6).and_hms(4, 10, 11); let end_date1 = NaiveDate::from_ymd(2016, 7, 10).and_hms(4, 10, 11); let start_date2 = NaiveDate::from_ymd(2016, 7, 7).and_hms(4, 10, 11); let end_date2 = NaiveDate::from_ymd(2016, 7, 11).and_hms(4, 10, 11); TicketPricing::create( ticket_type.id, "Early Bird".to_string(), start_date1, end_date1, 100, ).commit(project.get_connection()) .unwrap(); let ticket_pricing = TicketPricing::create( ticket_type.id, "Regular".to_string(), start_date2, end_date2, 100, ).commit(project.get_connection()) .unwrap(); let mut ticket_pricing_parameters: TicketPricingEditableAttributes = Default::default(); // Overlapping period project .get_connection() .transaction::<(), Error, _>(|| { let validation_results = ticket_type.validate_record(project.get_connection()); assert!(validation_results.is_err()); let error = validation_results.unwrap_err(); match &error.error_code { ValidationError { errors } => { assert!(errors.contains_key("ticket_pricing")); assert_eq!(errors["ticket_pricing"].len(), 2); assert_eq!( errors["ticket_pricing"][0].code, "ticket_pricing_overlapping_periods" ); } _ => panic!("Expected validation error"), } Err(Error::RollbackTransaction) }).unwrap_err(); // Period adjusted to not overlap (after existing record) project .get_connection() .transaction::<(), Error, _>(|| { ticket_pricing_parameters.start_date = Some(end_date1); ticket_pricing_parameters.end_date = Some(NaiveDate::from_ymd(2016, 7, 15).and_hms(4, 10, 11)); let result = ticket_pricing.update(ticket_pricing_parameters.clone(), project.get_connection()); assert!(result.is_ok()); let validation_results = ticket_type.validate_record(project.get_connection()); assert!(validation_results.is_ok()); Err(Error::RollbackTransaction) }).unwrap_err(); // Period adjusted to not overlap (prior to existing record) ticket_pricing_parameters.start_date = Some(NaiveDate::from_ymd(2016, 7, 4).and_hms(4, 10, 11)); ticket_pricing_parameters.end_date = Some(start_date1); let result = ticket_pricing.update(ticket_pricing_parameters.clone(), project.get_connection()); assert!(result.is_ok()); let validation_results = ticket_type.validate_record(project.get_connection()); assert!(validation_results.is_ok()); } #[test] pub fn remaining_ticket_count() { let project = TestProject::new(); let connection = project.get_connection(); let event = project.create_event().with_ticket_pricing().finish(); let ticket_type = event.ticket_types(connection).unwrap().remove(0); let order = project.create_order().for_event(&event).finish(); assert_eq!(90, ticket_type.remaining_ticket_count(connection).unwrap()); order.add_tickets(ticket_type.id, 10, connection).unwrap(); assert_eq!(80, ticket_type.remaining_ticket_count(connection).unwrap()); let order_item = order.items(connection).unwrap().remove(0); assert!( order .remove_tickets(order_item.ticket_pricing_id.unwrap(), Some(4), connection) .is_ok() ); assert_eq!(84, ticket_type.remaining_ticket_count(connection).unwrap()); } #[test] fn update() { let db = TestProject::new(); let connection = db.get_connection(); let event = db.create_event().with_tickets().finish(); let ticket_type = &event.ticket_types(connection).unwrap()[0]; //Change editable parameter and submit ticket type update request let update_name = String::from("updated_event_name"); let update_start_date = NaiveDate::from_ymd(2018, 4, 23).and_hms(5, 14, 18); let update_end_date = NaiveDate::from_ymd(2018, 6, 1).and_hms(8, 5, 34); let update_parameters = TicketTypeEditableAttributes { name: Some(update_name.clone()), start_date: Some(update_start_date), end_date: Some(update_end_date), ..Default::default() }; let updated_ticket_type = ticket_type.update(update_parameters, connection).unwrap(); assert_eq!(updated_ticket_type.id, ticket_type.id); assert_eq!(updated_ticket_type.name, update_name); assert_eq!(updated_ticket_type.start_date, update_start_date); assert_eq!(updated_ticket_type.end_date, update_end_date); } #[test] fn find() { let db = TestProject::new(); let event = db.create_event().with_tickets().finish(); let ticket_type = &event.ticket_types(&db.get_connection()).unwrap()[0]; let found_ticket_type = TicketType::find(ticket_type.id, &db.get_connection()).unwrap(); assert_eq!(&found_ticket_type, ticket_type); }
use std::collections::BTreeMap; use crate::{FieldId, IndexedPos}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct PositionMap { pos_to_field: Vec<FieldId>, field_to_pos: BTreeMap<FieldId, IndexedPos>, } impl PositionMap { /// insert `id` at the specified `position` updating the other position if a shift is caused by /// the operation. If `id` is already present in the position map, it is moved to the requested /// `position`, potentially causing shifts. pub fn insert(&mut self, id: FieldId, position: IndexedPos) -> IndexedPos { let mut upos = position.0 as usize; let mut must_rebuild_map = false; if let Some(old_pos) = self.field_to_pos.get(&id) { let uold_pos = old_pos.0 as usize; self.pos_to_field.remove(uold_pos); must_rebuild_map = true; } if upos < self.pos_to_field.len() { self.pos_to_field.insert(upos, id); must_rebuild_map = true; } else { upos = self.pos_to_field.len(); self.pos_to_field.push(id); } // we only need to update all the positions if there have been a shift a some point. In // most cases we only did a push, so we don't need to rebuild the `field_to_pos` map. if must_rebuild_map { self.field_to_pos.clear(); self.field_to_pos.extend( self.pos_to_field .iter() .enumerate() .map(|(p, f)| (*f, IndexedPos(p as u16))), ); } else { self.field_to_pos.insert(id, IndexedPos(upos as u16)); } IndexedPos(upos as u16) } /// Pushes `id` in last position pub fn push(&mut self, id: FieldId) -> IndexedPos { let pos = self.len(); self.insert(id, IndexedPos(pos as u16)) } pub fn len(&self) -> usize { self.pos_to_field.len() } pub fn field_to_pos(&self, id: FieldId) -> Option<IndexedPos> { self.field_to_pos.get(&id).cloned() } pub fn pos_to_field(&self, pos: IndexedPos) -> Option<FieldId> { let pos = pos.0 as usize; self.pos_to_field.get(pos).cloned() } pub fn field_pos(&self) -> impl Iterator<Item = (FieldId, IndexedPos)> + '_ { self.pos_to_field .iter() .enumerate() .map(|(i, f)| (*f, IndexedPos(i as u16))) } } #[cfg(test)] mod test { use super::*; #[test] fn test_default() { assert_eq!( format!("{:?}", PositionMap::default()), r##"PositionMap { pos_to_field: [], field_to_pos: {} }"## ); } #[test] fn test_insert() { let mut map = PositionMap::default(); // changing position removes from old position map.insert(0.into(), 0.into()); map.insert(1.into(), 1.into()); assert_eq!( format!("{:?}", map), r##"PositionMap { pos_to_field: [FieldId(0), FieldId(1)], field_to_pos: {FieldId(0): IndexedPos(0), FieldId(1): IndexedPos(1)} }"## ); map.insert(0.into(), 1.into()); assert_eq!( format!("{:?}", map), r##"PositionMap { pos_to_field: [FieldId(1), FieldId(0)], field_to_pos: {FieldId(0): IndexedPos(1), FieldId(1): IndexedPos(0)} }"## ); map.insert(2.into(), 1.into()); assert_eq!( format!("{:?}", map), r##"PositionMap { pos_to_field: [FieldId(1), FieldId(2), FieldId(0)], field_to_pos: {FieldId(0): IndexedPos(2), FieldId(1): IndexedPos(0), FieldId(2): IndexedPos(1)} }"## ); } #[test] fn test_push() { let mut map = PositionMap::default(); map.push(0.into()); map.push(2.into()); assert_eq!(map.len(), 2); assert_eq!( format!("{:?}", map), r##"PositionMap { pos_to_field: [FieldId(0), FieldId(2)], field_to_pos: {FieldId(0): IndexedPos(0), FieldId(2): IndexedPos(1)} }"## ); } #[test] fn test_field_to_pos() { let mut map = PositionMap::default(); map.push(0.into()); map.push(2.into()); assert_eq!(map.field_to_pos(2.into()), Some(1.into())); assert_eq!(map.field_to_pos(0.into()), Some(0.into())); assert_eq!(map.field_to_pos(4.into()), None); } #[test] fn test_pos_to_field() { let mut map = PositionMap::default(); map.push(0.into()); map.push(2.into()); map.push(3.into()); map.push(4.into()); assert_eq!( format!("{:?}", map), r##"PositionMap { pos_to_field: [FieldId(0), FieldId(2), FieldId(3), FieldId(4)], field_to_pos: {FieldId(0): IndexedPos(0), FieldId(2): IndexedPos(1), FieldId(3): IndexedPos(2), FieldId(4): IndexedPos(3)} }"## ); assert_eq!(map.pos_to_field(0.into()), Some(0.into())); assert_eq!(map.pos_to_field(1.into()), Some(2.into())); assert_eq!(map.pos_to_field(2.into()), Some(3.into())); assert_eq!(map.pos_to_field(3.into()), Some(4.into())); assert_eq!(map.pos_to_field(4.into()), None); } #[test] fn test_field_pos() { let mut map = PositionMap::default(); map.push(0.into()); map.push(2.into()); let mut iter = map.field_pos(); assert_eq!(iter.next(), Some((0.into(), 0.into()))); assert_eq!(iter.next(), Some((2.into(), 1.into()))); assert_eq!(iter.next(), None); } }
#[doc = "Reader of register MMCCTRL"] pub type R = crate::R<u32, super::MMCCTRL>; #[doc = "Writer for register MMCCTRL"] pub type W = crate::W<u32, super::MMCCTRL>; #[doc = "Register MMCCTRL `reset()`'s with value 0"] impl crate::ResetValue for super::MMCCTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CNTRST`"] pub type CNTRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CNTRST`"] pub struct CNTRST_W<'a> { w: &'a mut W, } impl<'a> CNTRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `CNTSTPRO`"] pub type CNTSTPRO_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CNTSTPRO`"] pub struct CNTSTPRO_W<'a> { w: &'a mut W, } impl<'a> CNTSTPRO_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `RSTONRD`"] pub type RSTONRD_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RSTONRD`"] pub struct RSTONRD_W<'a> { w: &'a mut W, } impl<'a> RSTONRD_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `CNTFREEZ`"] pub type CNTFREEZ_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CNTFREEZ`"] pub struct CNTFREEZ_W<'a> { w: &'a mut W, } impl<'a> CNTFREEZ_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `CNTPRST`"] pub type CNTPRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CNTPRST`"] pub struct CNTPRST_W<'a> { w: &'a mut W, } impl<'a> CNTPRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `CNTPRSTLVL`"] pub type CNTPRSTLVL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CNTPRSTLVL`"] pub struct CNTPRSTLVL_W<'a> { w: &'a mut W, } impl<'a> CNTPRSTLVL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `UCDBC`"] pub type UCDBC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UCDBC`"] pub struct UCDBC_W<'a> { w: &'a mut W, } impl<'a> UCDBC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } impl R { #[doc = "Bit 0 - Counters Reset"] #[inline(always)] pub fn cntrst(&self) -> CNTRST_R { CNTRST_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Counters Stop Rollover"] #[inline(always)] pub fn cntstpro(&self) -> CNTSTPRO_R { CNTSTPRO_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Reset on Read"] #[inline(always)] pub fn rstonrd(&self) -> RSTONRD_R { RSTONRD_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - MMC Counter Freeze"] #[inline(always)] pub fn cntfreez(&self) -> CNTFREEZ_R { CNTFREEZ_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Counters Preset"] #[inline(always)] pub fn cntprst(&self) -> CNTPRST_R { CNTPRST_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Full/Half Preset Level Value"] #[inline(always)] pub fn cntprstlvl(&self) -> CNTPRSTLVL_R { CNTPRSTLVL_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 8 - Update MMC Counters for Dropped Broadcast Frames"] #[inline(always)] pub fn ucdbc(&self) -> UCDBC_R { UCDBC_R::new(((self.bits >> 8) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Counters Reset"] #[inline(always)] pub fn cntrst(&mut self) -> CNTRST_W { CNTRST_W { w: self } } #[doc = "Bit 1 - Counters Stop Rollover"] #[inline(always)] pub fn cntstpro(&mut self) -> CNTSTPRO_W { CNTSTPRO_W { w: self } } #[doc = "Bit 2 - Reset on Read"] #[inline(always)] pub fn rstonrd(&mut self) -> RSTONRD_W { RSTONRD_W { w: self } } #[doc = "Bit 3 - MMC Counter Freeze"] #[inline(always)] pub fn cntfreez(&mut self) -> CNTFREEZ_W { CNTFREEZ_W { w: self } } #[doc = "Bit 4 - Counters Preset"] #[inline(always)] pub fn cntprst(&mut self) -> CNTPRST_W { CNTPRST_W { w: self } } #[doc = "Bit 5 - Full/Half Preset Level Value"] #[inline(always)] pub fn cntprstlvl(&mut self) -> CNTPRSTLVL_W { CNTPRSTLVL_W { w: self } } #[doc = "Bit 8 - Update MMC Counters for Dropped Broadcast Frames"] #[inline(always)] pub fn ucdbc(&mut self) -> UCDBC_W { UCDBC_W { w: self } } }
use iron::Handler; use handler::WebHandler; use router::Router; pub struct WebRouter { routes: Vec<Box<WebHandler>>, } impl WebRouter { pub fn new() -> Self { WebRouter { routes: Vec::new() } } pub fn add_route(&mut self, handler: Box<WebHandler>) { self.routes.push(handler); } pub fn to_iron_router(&self) -> Router { let mut router = Router::new(); for handler in &self.routes { let () = handler.handle(); // router.get(handler.endpoint(), handler.handle(), handler.name()); } router } }
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; // Test for performance regressions in the *head* revision since the *latest* release. // // ``` // cargo update // cargo bench -- --save-baseline main // critcmp main -g '\w+/(.*)' // ``` criterion_main!(benches); criterion_group!(benches, regression); fn regression(c: &mut Criterion) { bench_type(c, |_| fastrand::u8(..)); bench_type(c, |_| fastrand::u16(..)); bench_type(c, |_| fastrand::u32(..)); bench_type(c, |_| fastrand::u64(..)); bench_type(c, |_| fastrand::u128(..)); bench_type(c, |_| fastrand::i8(..)); bench_type(c, |_| fastrand::i16(..)); bench_type(c, |_| fastrand::i32(..)); bench_type(c, |_| fastrand::i64(..)); bench_type(c, |_| fastrand::i128(..)); bench_f32(c, |_| fastrand::f32()); bench_f64(c, |_| fastrand::f64()); bench_type(c, |_| fastrand::bool()); bench_type(c, |_| fastrand::char('\u{0}'..'\u{10FFFF}')); } fn bench_type<T>(c: &mut Criterion, gen: fn(usize) -> T) where T: Clone + Ord + radsort::Key + radsort_latest::Key + radsort_main::Key, { let gen = |size| { fastrand::seed(0); (0..size).map(gen).collect() }; bench_function(c, gen, "head", radsort::sort); bench_function(c, gen, "main", radsort_main::sort); bench_function(c, gen, "latest", radsort_latest::sort); bench_function(c, gen, "std stable", std_stable); bench_function(c, gen, "std unstable", std_unstable); } fn bench_f32(c: &mut Criterion, gen: fn(usize) -> f32) { let gen = |size| { fastrand::seed(0); (0..size).map(gen).collect() }; bench_function(c, gen, "head", radsort::sort); bench_function(c, gen, "main", radsort_main::sort); bench_function(c, gen, "latest", radsort_latest::sort); bench_function(c, gen, "std stable", std_stable_f32); bench_function(c, gen, "std unstable", std_unstable_f32); } fn bench_f64(c: &mut Criterion, gen: fn(usize) -> f64) { let gen = |size| { fastrand::seed(0); (0..size).map(gen).collect() }; bench_function(c, gen, "head", radsort::sort); bench_function(c, gen, "main", radsort_main::sort); bench_function(c, gen, "latest", radsort_latest::sort); bench_function(c, gen, "std stable", std_stable_f64); bench_function(c, gen, "std unstable", std_unstable_f64); } fn std_stable<T: Ord>(slice: &mut [T]) { slice.sort(); } fn std_stable_f32(slice: &mut [f32]) { slice.sort_by(|a, b| a.total_cmp(b)); } fn std_stable_f64(slice: &mut [f64]) { slice.sort_by(|a, b| a.total_cmp(b)); } fn std_unstable<T: Ord>(slice: &mut [T]) { slice.sort_unstable(); } fn std_unstable_f32(slice: &mut [f32]) { slice.sort_unstable_by(|a, b| a.total_cmp(b)); } fn std_unstable_f64(slice: &mut [f64]) { slice.sort_unstable_by(|a, b| a.total_cmp(b)); } fn bench_function<T: Clone>( c: &mut Criterion, gen: impl Fn(usize) -> Vec<T>, name: &'static str, sort: impl Fn(&mut [T]), ) { let mut group = c.benchmark_group(name); let t_name = std::any::type_name::<T>(); for size in 0..=4 { let elems = 25 * 10_u64.pow(size); group.throughput(Throughput::Elements(elems)); group.bench_with_input(BenchmarkId::new(t_name, elems), &elems, |b, &elems| { let input = gen(elems as usize); b.iter_batched_ref( || input.clone(), |data| { sort(data); }, criterion::BatchSize::LargeInput, ); }); } group.finish(); }
use super::{challenge::Challenge, user_performance_data::UserPerformanceData}; #[derive(Debug)] pub struct ChallengePerformanceData { pub chat_id: i64, pub challenge: Challenge, pub user_performance: Vec<UserPerformanceData>, }
use std::io::{BufReader, BufRead}; use std::fs::File; pub fn solve() -> String { let f = BufReader::new(File::open("resources/day_two.txt").unwrap()); let checksum :u32 = f.lines() .map(|line| line.unwrap()) .map(|line| line_checksum(line)) .sum(); return checksum.to_string() } fn line_checksum(line: String) -> u32 { let numbers :Vec<u32> = line.split_whitespace() .map(|s| s.parse::<u32>().unwrap()) .collect(); let min = numbers.iter().min().unwrap(); let max = numbers.iter().max().unwrap(); return max - min } pub fn solve_two() -> String { let f = BufReader::new(File::open("resources/day_two.txt").unwrap()); let checksum :u32 = f.lines() .map(|line| line.unwrap()) .map(|line| line_checksum_two(line)) .sum(); return checksum.to_string() } fn line_checksum_two(line: String) -> u32 { let numbers :Vec<u32> = line.split_whitespace() .map(|s| s.parse::<u32>().unwrap()) .collect(); for number in numbers.iter() { for digit in numbers.iter() { if number != digit { if number % digit == 0 { println!("{} / {} = {}", number, digit, number / digit); return number / digit } } } } panic!("oh no") }
use structopt::StructOpt; #[derive(StructOpt)] pub struct CmdOpts { /// Output JSON #[structopt(short, long)] pub json: bool, /// Don't show headers (ignored for JSON output) #[structopt(short = "H", long)] pub no_headers: bool, #[structopt(subcommand)] pub cmd: Command, } #[derive(StructOpt)] pub enum Command { /// Scan for Miflora Devices Scan { /// How long should we listen for Mifloras #[structopt(short, long = "duration", default_value = "10")] duration_sec: u8, }, /// Read realtime data from Miflora device Read { addr: String }, /// Make Miflora device blink Blink { addr: String }, /// Read historical data from Miflora device History { addr: String, /// Read from record number (defaults to first record) #[structopt(short, long)] from: Option<u16>, /// Read until record number (defaults to last record) #[structopt(short, long)] to: Option<u16>, /// Number of records to batch together, before reconnecting #[structopt(short, long)] page: Option<u16>, /// Clear after successful reading (only if you read everything) #[structopt(short, long)] clear: bool, }, /// Read number of historical records from Miflora Device HistoryCount { addr: String }, /// Clear historical data from Miflora device HistoryClear { addr: String }, }
use super::bus::Busable; use arrayvec::ArrayVec; use num_enum::IntoPrimitive; use crate::gui; pub struct Ppu { background_palette: ArrayVec<Color, 4>, obj_palette0: ArrayVec<Color, 4>, obj_palette1: ArrayVec<Color, 4>, scx: u8, scy: u8, wx: u8, // real_WX - 7 wy: u8, ly: u8, lyc: u8, enabled: bool, win_enabled: bool, sprite_enabled: bool, bg_win_priority: bool, obj_size: ObjSize, win_map_select: WindowMapSelect, win_bg_data: WindowBGTileData, bg_map_select: BgMapSelect, int_vblank: bool, int_hblank: bool, int_lyc: bool, int_oam: bool, current_mode: Mode, vram: [u8; 0x2000], oam: [u8; 0xA0], wait: usize, texture: Vec<[Color; gui::WIDTH]>, } pub enum PpuInterrupt { None, VBlank, Stat, } impl Ppu { pub fn new() -> Self { Ppu { background_palette: (0..4) .map(|idx| bw_palette(idx as u8, idx, PaletteType::Background)) .collect::<ArrayVec<Color, 4>>(), obj_palette0: (0..4) .map(|idx| bw_palette(idx as u8, idx, PaletteType::Sprite)) .collect::<ArrayVec<Color, 4>>(), obj_palette1: (0..4) .map(|idx| bw_palette(idx as u8, idx, PaletteType::Sprite)) .collect::<ArrayVec<Color, 4>>(), scx: 0, scy: 0, wx: 0, wy: 0, ly: 0, lyc: 0, enabled: true, win_enabled: false, sprite_enabled: false, bg_win_priority: true, obj_size: ObjSize::Small, win_map_select: WindowMapSelect::High, win_bg_data: WindowBGTileData::Low, bg_map_select: BgMapSelect::Low, int_vblank: false, int_hblank: false, int_lyc: false, int_oam: false, current_mode: Mode::OamScan, vram: [0; 0x2000], oam: [0; 0xA0], wait: 0, texture: vec![[Color::new(0, 0, 0, PaletteType::Background); gui::WIDTH]; gui::HEIGHT], } } pub fn get_bgp(&self) -> u8 { self.background_palette .iter() .enumerate() .fold(0, |acc, (i, color)| (acc | color.palette_index << (2 * i))) } pub fn set_bgp(&mut self, new_palette: u8) { for (i, col) in self.background_palette.iter_mut().enumerate() { *col = bw_palette( (new_palette & (0x3 << (2 * i))) >> (2 * i), i as u8, PaletteType::Background, ); } } pub fn get_obp0(&self) -> u8 { self.obj_palette0 .iter() .enumerate() .fold(0, |acc, (i, color)| (acc | color.palette_index << (2 * i))) } pub fn set_obp0(&mut self, new_palette: u8) { for (i, col) in self.obj_palette0.iter_mut().enumerate() { *col = bw_palette( (new_palette & (0x3 << (2 * i))) >> (2 * i), i as u8, PaletteType::Sprite, ); } } pub fn get_obp1(&self) -> u8 { self.obj_palette1 .iter() .enumerate() .fold(0, |acc, (i, color)| (acc | color.palette_index << (2 * i))) } pub fn set_obp1(&mut self, new_palette: u8) { for (i, col) in self.obj_palette1.iter_mut().enumerate() { *col = bw_palette( (new_palette & (0x3 << (2 * i))) >> (2 * i), i as u8, PaletteType::Sprite, ); } } pub fn get_wx(&self) -> u8 { self.wx } pub fn set_wx(&mut self, val: u8) { self.wx = val; } pub fn get_wy(&self) -> u8 { self.wy } pub fn set_wy(&mut self, val: u8) { self.wy = val; } pub fn get_scy(&self) -> u8 { self.scy } pub fn set_scy(&mut self, val: u8) { self.scy = val; } pub fn get_scx(&self) -> u8 { self.scx } pub fn set_scx(&mut self, val: u8) { self.scx = val; } pub fn get_ly(&self) -> u8 { self.ly } pub fn set_ly(&self, _val: u8) { panic!("LY is not writable"); } pub fn get_lyc(&self) -> u8 { self.lyc } pub fn set_lyc(&mut self, val: u8) { self.lyc = val; } pub fn get_lcdc(&self) -> u8 { (if self.enabled { 0x80 } else { 0 }) | (if let WindowMapSelect::High = self.win_map_select { 0x40 } else { 0 }) | (if self.win_enabled { 0x20 } else { 0 }) | (if let WindowBGTileData::High = self.win_bg_data { 0x10 } else { 0 }) | (if let BgMapSelect::High = self.bg_map_select { 0x08 } else { 0 }) | (if let ObjSize::Big = self.obj_size { 0x04 } else { 0 }) | (if self.sprite_enabled { 0x02 } else { 0 }) | (if self.bg_win_priority { 0x01 } else { 0 }) } pub fn set_lcdc(&mut self, val: u8) { self.enabled = if val & 0x80 != 0 { if !self.enabled { self.ly = 0; self.current_mode = Mode::OamScan; } true } else { false }; self.win_map_select = match val & 0x40 { 0 => WindowMapSelect::Low, _ => WindowMapSelect::High, }; self.win_enabled = val & 0x20 != 0; self.win_bg_data = match val & 0x10 { 0 => WindowBGTileData::Low, _ => WindowBGTileData::High, }; self.bg_map_select = match val & 0x08 { 0 => BgMapSelect::Low, _ => BgMapSelect::High, }; self.obj_size = match val & 0x04 { 0 => ObjSize::Small, _ => ObjSize::Big, }; self.sprite_enabled = val & 0x02 != 0; self.bg_win_priority = val & 0x01 != 0; } pub fn get_lcds(&self) -> u8 { let mode: u8 = self.current_mode.into(); (self.int_lyc as u8) << 6 | (self.int_oam as u8) << 5 | (self.int_vblank as u8) << 4 | (self.int_hblank as u8) << 3 | if self.lyc == self.ly { 0x04 } else { 0 } | mode } pub fn set_lcds(&mut self, val: u8) { self.int_lyc = val & 0x40 != 0; self.int_oam = val & 0x20 != 0; self.int_vblank = val & 0x10 != 0; self.int_hblank = val & 0x08 != 0; } pub fn tick(&mut self) -> PpuInterrupt { if !self.enabled { return PpuInterrupt::None; } if self.wait != 0 { self.wait -= 1; return PpuInterrupt::None; } let mut res = PpuInterrupt::None; match self.current_mode { Mode::OamScan => { self.wait = 180; self.current_mode = Mode::Rendering; } Mode::Rendering => { self.render_line(); self.wait = 196; self.current_mode = Mode::HBlank; if self.int_hblank { res = PpuInterrupt::Stat; } } Mode::HBlank => { self.ly += 1; if self.ly == self.lyc && self.int_lyc { res = PpuInterrupt::Stat; } if self.ly >= 144 { self.wait = 456; self.current_mode = Mode::VBlank; res = PpuInterrupt::VBlank; } else { self.wait = 80; self.current_mode = Mode::OamScan; if self.int_oam { res = PpuInterrupt::Stat; } } } Mode::VBlank => { if self.ly < 154 { self.wait = 456; self.ly += 1; } else { self.ly = 0; self.wait = 80; self.current_mode = Mode::OamScan; if self.int_oam || self.ly == self.lyc { res = PpuInterrupt::Stat; } } } } res } fn render_line(&mut self) { if self.bg_win_priority { self.render_background(); if self.win_enabled { self.render_window(); } } if self.sprite_enabled { self.render_sprites(); } } fn render_background(&mut self) { let get_tile = if let WindowBGTileData::Low = self.win_bg_data { Ppu::get_tile_line_signed } else { Ppu::get_tile_line_unsigned }; let y = u8::wrapping_add(self.ly, self.scy); let mut x = 0; while x < gui::WIDTH { let rel_x = (x + self.scx as usize) % 256; let tile_index = self.vram[self.bg_map_select as usize + y as usize / 8 * 32 + rel_x / 8]; let tile_data = get_tile(self, tile_index, y as usize); let offset_x = rel_x % 8; for tile_x in offset_x..8 { match self.texture[self.ly as usize].get_mut(x + tile_x - offset_x) { Some(pixel) => { *pixel = self.background_palette[tile_data[tile_x as usize] as usize] } _ => { return; } } } x += 8 - offset_x; } } fn render_window(&mut self) { let get_tile = if let WindowBGTileData::Low = self.win_bg_data { Ppu::get_tile_line_signed } else { Ppu::get_tile_line_unsigned }; let y = match u8::checked_sub(self.ly, self.wy) { Some(result) => result, _ => return, }; let mut x = (self.wx as usize).saturating_sub(7); while x < gui::WIDTH { let rel_x = x + 7 - self.wx as usize; let tile_index = self.vram[self.win_map_select as usize + y as usize / 8 * 32 + rel_x / 8]; let tile_data = get_tile(self, tile_index, y as usize); for tile_x in 0..8 { match self.texture[self.ly as usize].get_mut(x + tile_x) { Some(pixel) => { *pixel = self.background_palette[tile_data[tile_x as usize] as usize] } _ => { return; } } } x += 8; } } fn render_sprites(&mut self) { let mut oam_data = self.get_sprites_on_line(); oam_data.sort_by_key(|sprite| sprite.x as i16); for sprite in oam_data.iter() { let tile = self.get_sprite_tile_line(sprite); let palette = if sprite.palette { self.obj_palette1.clone() } else { self.obj_palette0.clone() }; if !sprite.x_flip { for tile_x in 0..8 { let x = match sprite.x.saturating_add(tile_x).checked_sub(8) { Some(x) => x, None => continue, }; if let Some(pixel) = self.texture[self.ly as usize].get_mut(x as usize) { if matches!(pixel.palette_type, PaletteType::Background) { if !sprite.behind_bg || pixel.palette_index == 0 { let color = palette[tile[tile_x as usize] as usize]; if color.palette_index != 0 { *pixel = color; } } else { pixel.palette_type = PaletteType::Sprite; // don't change color, but then low-prio sprite can't be over this pixel } } } // do not break, because of the left screen border } } else { for tile_x in 0..8 { let x = match (sprite.x + tile_x).checked_sub(8) { Some(x) => x, None => continue, }; if let Some(pixel) = self.texture[self.ly as usize].get_mut(x as usize) { if matches!(pixel.palette_type, PaletteType::Background) { if !sprite.behind_bg || pixel.palette_index == 0 { let color = palette[tile[7 - tile_x as usize] as usize]; if color.palette_index != 0 { *pixel = color; } } else { pixel.palette_type = PaletteType::Sprite; // don't change color, but then low-prio sprite can't be over this pixel } } } // do not break, because of the left screen border } } } } fn get_sprites_on_line(&self) -> Vec<SpriteOam> { let mut res = Vec::new(); let height = match self.obj_size { ObjSize::Small => 8, ObjSize::Big => 16, }; let y_sec = self.ly + 16; for i in (0..0xa0).step_by(4) { let data = &self.oam[i..i + 4]; let y_sprite = data[0]; if y_sprite <= y_sec && y_sec < y_sprite + height { let flags = data[3]; res.push(SpriteOam { y: data[0], x: data[1], tile: data[2], behind_bg: flags & 0x80 != 0, y_flip: flags & 0x40 != 0, x_flip: flags & 0x20 != 0, palette: flags & 0x10 != 0, }); if res.len() >= 10 { return res; } } } res } fn get_tile_line_signed(&self, nb: u8, y: usize) -> [u8; 8] { let addr = (0x1000 + nb as i8 as isize * 16) + y as isize % 8 * 2; let l = self.vram[addr as usize]; let h = self.vram[addr as usize + 1]; let mut res = [0u8; 8]; for (i, x) in res.iter_mut().enumerate() { *x = ((h >> (7 - i) & 1u8) << 1) | ((l >> (7 - i)) & 1u8); } res } fn get_tile_line_unsigned(&self, nb: u8, y: usize) -> [u8; 8] { let addr = nb as usize * 16 + y % 8 * 2; let l = self.vram[addr]; let h = self.vram[addr + 1]; let mut res = [0u8; 8]; for (i, x) in res.iter_mut().enumerate() { *x = (((h >> (7 - i)) & 1u8) << 1) | ((l >> (7 - i)) & 1u8); } res } fn get_sprite_tile_line(&self, sprite: &SpriteOam) -> [u8; 8] { let mut y_offset = self.ly + 16 - sprite.y; if sprite.y_flip { let sprite_height = match self.obj_size { ObjSize::Small => 8, ObjSize::Big => 16, }; y_offset = sprite_height - 1 - y_offset; } let addr = match y_offset { y if y < 8 => { if let ObjSize::Big = self.obj_size { (sprite.tile & 0xfe) as usize * 16 + y as usize * 2 } else { sprite.tile as usize * 16 + y as usize * 2 } } y if y >= 8 => (sprite.tile | 1) as usize * 16 + y as usize % 8 * 2, // necessarily ObjSize::Big _ => panic!("Unexpected y offset"), }; let l = self.vram[addr]; let h = self.vram[addr + 1]; let mut res = [0u8; 8]; for (i, x) in res.iter_mut().enumerate() { *x = ((h >> (7 - i) & 1u8) << 1) | ((l >> (7 - i)) & 1u8); } res } pub fn render(&self, target: &mut [u8; gui::SIZE]) { let mut index = 0; for y in 0..gui::HEIGHT { for x in 0..gui::WIDTH { unsafe { let color = self.texture.get_unchecked(y).get_unchecked(x); *target.get_unchecked_mut(index) = color.r; *target.get_unchecked_mut(index + 1) = color.g; *target.get_unchecked_mut(index + 2) = color.b; index += 3; } } } } } impl Busable for Ppu { fn read(&self, addr: u16) -> u8 { if addr < 0xA000 { self.vram[(addr - 0x8000) as usize] } else if addr < 0xfea0 { self.oam[(addr - 0xfe00) as usize] } else { panic!("Illegal VRam read : {:#x}", addr) } } fn write(&mut self, addr: u16, val: u8) { if addr < 0xA000 { self.vram[(addr - 0x8000) as usize] = val; } else if addr < 0xfea0 { self.oam[(addr - 0xfe00) as usize] = val; } else { panic!("Illegal VRam write : {:#x}", addr) } } } #[derive(Clone, Copy, IntoPrimitive)] #[repr(u16)] enum WindowMapSelect { Low = 0x1800, High = 0x1C00, } #[derive(Clone, Copy, IntoPrimitive)] #[repr(u16)] enum WindowBGTileData { Low = 0x1000, High = 0x0000, } #[derive(Clone, Copy, IntoPrimitive)] #[repr(u16)] enum BgMapSelect { Low = 0x1800, High = 0x1C00, } enum ObjSize { Small, Big, } #[derive(Clone, Copy, IntoPrimitive)] #[repr(u8)] enum Mode { HBlank = 0, VBlank = 1, OamScan = 2, Rendering = 3, } struct SpriteOam { x: u8, y: u8, tile: u8, behind_bg: bool, y_flip: bool, x_flip: bool, palette: bool, } #[derive(Clone, Copy)] enum PaletteType { Background, Sprite, } #[derive(Clone, Copy)] struct Color { r: u8, g: u8, b: u8, palette_index: u8, palette_type: PaletteType, } impl Color { fn new(r: u8, g: u8, b: u8, palette_type: PaletteType) -> Self { Color { r, g, b, palette_index: 0, palette_type, } } fn from_palette(r: u8, g: u8, b: u8, index: u8, palette_type: PaletteType) -> Self { Color { r, g, b, palette_index: index, palette_type, } } } fn bw_palette(entry: u8, index: u8, ptype: PaletteType) -> Color { match entry { 3 => Color::from_palette(0, 0, 0, index, ptype), 2 => Color::from_palette(50, 50, 50, index, ptype), 1 => Color::from_palette(100, 100, 100, index, ptype), 0 => Color::from_palette(150, 150, 150, index, ptype), x => panic!("Unknown BW color : {}", x), } }
use std::fmt; #[derive(Debug, PartialEq)] pub enum Token { Eof, Illegal, Identifier(String), Int(i64), Plus, Increment, Minus, Decrement, Assign, Asterisk, Slash, Exclamation, Equal, NotEqual, LessThan, LessThanAndEqual, MoreThan, MoreThanAndEqual, Semicolon, Comma, LeftParanthesis, RightParanthesis, LeftBrace, RightBrace, LeftBracket, RightBracket, Fn, Let, Extern, True, False, If, Else, Or, Return, And, } impl Default for Token { fn default() -> Token { Token::Illegal } } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::Plus => write!(f, "+"), Token::Minus => write!(f, "-"), Token::Slash => write!(f, "/"), Token::Asterisk => write!(f, "*"), Token::Equal => write!(f, "=="), Token::NotEqual => write!(f, "!="), Token::MoreThanAndEqual => write!(f, ">="), Token::MoreThan => write!(f, ">"), Token::LessThanAndEqual => write!(f, "<="), Token::LessThan => write!(f, "<"), Token::Assign => write!(f, "="), Token::Comma => write!(f, ","), Token::Semicolon => write!(f, ";"), Token::LeftParanthesis => write!(f, "("), Token::RightParanthesis => write!(f, ")"), Token::LeftBrace => write!(f, "{{"), Token::RightBrace => write!(f, "}}"), Token::LeftBracket => write!(f, "["), Token::RightBracket => write!(f, "]"), Token::Exclamation => write!(f, "!"), Token::Increment => write!(f, "++"), Token::Decrement => write!(f, "--"), _ => write!(f, "{:?}", self) } } } pub fn get_identifier(idnt: &str) -> Token { match idnt { "fn" => Token::Fn, "let" => Token::Let, "true" => Token::True, "false" => Token::False, "if" => Token::If, "else" => Token::Else, "and" => Token::And, "or" => Token::Or, "return" => Token::Return, _ => Token::Identifier(idnt.to_string()), } }
use tera; use actix_web::http::{ContentEncoding, Method, NormalizePath, StatusCode}; use actix_web::{fs, pred, App, HttpRequest, HttpResponse}; #[cfg(debug_assertions)] use actix_web::middleware::{Middleware, Started}; #[cfg(debug_assertions)] use actix_web::{middleware, Result}; use std::cell::RefCell; pub struct AppState { template: RefCell<tera::Tera>, } #[cfg(debug_assertions)] struct TemplateReload; #[cfg(debug_assertions)] impl Middleware<AppState> for TemplateReload { fn start(&self, req: &mut HttpRequest<AppState>) -> Result<Started> { req.state().template.borrow_mut().full_reload().unwrap(); Ok(Started::Done) } } fn index(req: HttpRequest<AppState>) -> HttpResponse { let template = req.state().template.borrow(); let mut context = tera::Context::new(); context.add("vat_rate", &0.20); let result = template.render("admin/login.html", &context).unwrap(); HttpResponse::Ok() .content_encoding(ContentEncoding::Gzip) .content_type("text/html; charset=utf-8") .body(result) } fn p404(req: HttpRequest<AppState>) -> HttpResponse { let template = req.state().template.borrow(); let context = tera::Context::new(); let result = template.render("404.html", &context).unwrap(); HttpResponse::build(StatusCode::NOT_FOUND) .content_encoding(ContentEncoding::Gzip) .content_type("text/html") .body(result) } pub fn create_app() -> App<AppState> { let app = App::with_state(AppState {template: RefCell::new(compile_templates!("./src/templates/**/*"))}); #[cfg(debug_assertions)] let app = app.middleware(middleware::Logger::default()); #[cfg(debug_assertions)] let app = app.middleware(TemplateReload); app.resource("/", |r| r.f(index)) .resource("/{test}/", |r| r.f(index)) .handler( "/static", fs::StaticFiles::new("./src/static/build").show_files_listing(), ) .default_resource(|r| { r.method(Method::GET).f(p404); r.route() .filter(pred::Not(pred::Get())) .f(|_req| HttpResponse::MethodNotAllowed()); r.h(NormalizePath::default()); }) }
use std::collections::HashMap; pub fn part_1(input: &Vec<String>) -> usize { let nr_map = get_counts_per_bit_position(input); let number_length = input[0].len(); let total_numbers = input.len(); let mut gamma_rate = String::new(); for index in 0..number_length { let nr_positive_bits = nr_map.get(&index).unwrap(); if nr_positive_bits * 2 > total_numbers { gamma_rate.push('1'); } else { gamma_rate.push('0'); } } let gamma_rate = usize::from_str_radix(gamma_rate.as_str(), 2).unwrap(); let max_value = (1 << number_length) - 1; let epsilon_rate = max_value - gamma_rate; gamma_rate * epsilon_rate } pub fn part_2(input: &Vec<String>) -> usize { let number_length = input[0].len(); let life_support_rating = get_winning_number(input, number_length, true); let co2_rating = get_winning_number(input, number_length, false); (life_support_rating * co2_rating) as usize } fn get_winning_number(input: &Vec<String>, number_length: usize, most_common: bool) -> isize { let mut input = input.clone(); for index in 0..number_length { input = filter_input(&input, index, most_common); if &input.len() < &2 { break; } } let winning_nr = input.get(0).unwrap(); let winning_nr = isize::from_str_radix(winning_nr, 2).unwrap(); winning_nr } fn filter_input(input: &Vec<String>, bit: usize, most_common: bool) -> Vec<String> { let nr_map = get_counts_per_bit_position(input); let bits = &input.len(); if most_common && (nr_map.get(&bit).unwrap() * 2) >= *bits { filter_on_value(input, bit, '1') } else if most_common { filter_on_value(input, bit, '0') } else if (nr_map.get(&bit).unwrap() * 2) < *bits { filter_on_value(input, bit, '1') } else { filter_on_value(input, bit, '0') } } fn get_counts_per_bit_position(input: &Vec<String>) -> HashMap<usize, usize> { let mut nr_map: HashMap<usize, usize> = HashMap::new(); for line in input { for (index, char) in line.chars().enumerate() { if char == '1' { let counter = nr_map.entry(index).or_insert(0); *counter += 1; } else { nr_map.entry(index).or_insert(0); } } } nr_map } fn filter_on_value(input: &Vec<String>, bit: usize, value : char) -> Vec<String> { input .iter() .filter(|line| line.chars().nth(bit).unwrap() == value) .map(|str| str.clone()) .collect() } #[cfg(test)] mod tests { use crate::day3::{part_1, part_2}; use crate::reader::parse_lines_to_vec; #[test] fn test_example_part1() { let input: Vec<String> = parse_lines_to_vec("./resources/inputs/day3-example.txt").unwrap(); assert_eq!(198, part_1(&input)); } #[test] fn test_example_part2() { let input: Vec<String> = parse_lines_to_vec("./resources/inputs/day3-example.txt").unwrap(); assert_eq!(230, part_2(&input)); } #[test] fn test_input_part1() { let input: Vec<String> = parse_lines_to_vec("./resources/inputs/day3-input.txt").unwrap(); assert_eq!(1307354, part_1(&input)); } #[test] fn test_input_part2() { let input: Vec<String> = parse_lines_to_vec("./resources/inputs/day3-input.txt").unwrap(); assert_eq!(482500, part_2(&input)); } }
use piston_window::{ Button, Key, MouseButton }; pub struct InputManager; impl InputManager { pub fn new() -> InputManager { InputManager } pub fn get_operation(&self, button: Button) -> Operation { match button { Button::Keyboard(key) => match key { Key::A => { Operation::Move(Direction::Left) }, Key::D => { Operation::Move(Direction::Right) }, Key::W => { Operation::Move(Direction::Up) }, Key::S => { Operation::Move(Direction::Down) }, Key::LShift => { Operation::FixCamera }, _ => {Operation::None}, }, Button::Mouse(button) => match button { _ => {Operation::None}, }, _ => {Operation::None}, } } } pub enum Direction { Left, Right, Up, Down, } pub enum Operation { Move(Direction), Cursor(f64, f64), FixCamera, None, }
use crate::event::{Event, EventState}; use crate::parser::parse_line; use std::error::Error; use std::io::{BufRead, BufReader, Lines, Read}; use std::iter::Enumerate; pub struct Consumer<T> where T: Read, { response: Enumerate<Lines<BufReader<T>>> } impl<'a, T> Consumer<T> where T: Read, { pub fn new(response: T) -> Self { Consumer { response: BufReader::new(response).lines().enumerate() } } } impl<T> Iterator for Consumer<T> where T: Read, { type Item = Result<Event, Box<dyn Error>>; fn next(&mut self) -> Option<Result<Event, Box<dyn Error>>> { let mut event = Event::new(); for (_num, line_res) in self.response.by_ref() { let line = line_res.unwrap(); match parse_line(&line, &mut event) { EventState::Pending => {} EventState::Ready => { return Some(Ok(event)); } } } Some(Ok(event)) } }
//! This module contains minimal stable dummy implementations of NonZero and //! Shared, such that the same code can be used between the nightly and stable //! versions of rust-gc. use std::marker::PhantomData; /// See `::std::ptr::Shared` pub struct Shared<T: ?Sized> { p: *mut T, _pd: PhantomData<T>, } impl<T: ?Sized> Shared<T> { pub unsafe fn new_unchecked(p: *mut T) -> Self { Shared { p: p, _pd: PhantomData, } } pub fn as_ptr(&self) -> *mut T { self.p } } impl<T: ?Sized> Clone for Shared<T> { fn clone(&self) -> Self { *self } } impl<T: ?Sized> Copy for Shared<T> {}
extern crate gtk; use gtk::prelude::*; use std::cell::Cell; use std::rc::Rc; use std::ops::Deref; use gtk::{Orientation, Window, WindowType}; fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK. Do you have libgtk 3.10+?"); return; } let window = Window::new(WindowType::Toplevel); window.set_title("Iron Tomato"); window.set_border_width(15); window.connect_delete_event(|_, _| { gtk::main_quit(); // Let the default handler destroy the window. Inhibit(false) }); let label = gtk::Label::new_with_mnemonic(Some("25:00")); let run_button = gtk::Button::new_with_label("Start Tomato"); let reset_button = gtk::Button::new_with_label("Reset"); let main_box = gtk::Box::new(Orientation::Vertical, 30); main_box.add(&label); main_box.add(&run_button); main_box.add(&reset_button); window.add(&main_box); let total_seconds = Rc::new(Cell::new(1500)); let is_timer_running = Rc::new(Cell::new(false)); // connect_clicked() takes a Fn() closure, so interior mutability saves the day :( { let better_catch_it = is_timer_running.clone(); run_button.connect_clicked(move |butt| { let timer_state = better_catch_it.deref(); if timer_state.get() == false { timer_state.set(true); butt.set_label("Pause Tomato"); } else { timer_state.set(false); butt.set_label("Resume Tomato"); } }); } { let seconds_remaining = total_seconds.clone(); reset_button.connect_clicked(move |_| { seconds_remaining.deref().set(1500); }); } gtk::timeout_add(1000, move || { let mut seconds_remaining = total_seconds.deref().get(); // If the timer is running, decrement one second per second if is_timer_running.deref().get() { if seconds_remaining > 0 { seconds_remaining -= 1; } } // Update the total seconds remaining + clock time label total_seconds.deref().set(seconds_remaining); label.set_label(get_time_string(seconds_remaining).as_str()); gtk::Continue(true) }); window.show_all(); gtk::main(); } fn get_time_string(seconds: u32) -> String { let timer_mins = seconds / 60; let timer_seconds = seconds % 60; format!("{:02}:{:02}", timer_mins, timer_seconds) }
fn main() { yew::start_app::<event_bus::Model>(); }
struct Package<'a> { colour: &'a str, shape: &'a str } trait PackageSpecification { fn is_satisfied(&self, package: &Package) -> bool; } struct PackageColourSpecification<'a> { expected_colour: &'a str } impl PackageSpecification for PackageColourSpecification<'_> { fn is_satisfied(&self, package: &Package) -> bool { package.colour == self.expected_colour } } struct PackageShapeSpecification<'a> { expected_shape: &'a str } impl PackageSpecification for PackageShapeSpecification<'_> { fn is_satisfied(&self, package: &Package) -> bool { package.shape == self.expected_shape } } struct AndPackageSpecification<'a> { left: &'a dyn PackageSpecification, right: &'a dyn PackageSpecification } impl PackageSpecification for AndPackageSpecification<'_> { fn is_satisfied(&self, package: &Package) -> bool { self.left.is_satisfied(package) && self.right.is_satisfied(package) } } #[test] fn should_be_possible_to_create_specification_for_red_oval_package() { let red_oval_package = Package { colour: "red", shape: "oval" }; let red_square_package = Package { colour: "red", shape: "square" }; let green_oval_package = Package { colour: "green", shape: "oval" }; let red_oval_package_specification = AndPackageSpecification { left: &PackageColourSpecification { expected_colour: "red" }, right: &PackageShapeSpecification { expected_shape: "oval" } }; assert_eq!( red_oval_package_specification.is_satisfied(&red_oval_package), true, ); assert_eq!( red_oval_package_specification.is_satisfied(&red_square_package), false, ); assert_eq!( red_oval_package_specification.is_satisfied(&green_oval_package), false, ); }
use std::collections::HashSet; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::WindowCanvas; pub struct Pellet { rect: Box<Rect>, window_width: i32, window_height: i32, w: u32, h: u32, eaten: bool, } impl Pellet { pub fn new( window_width: i32, window_height: i32, w: u32, h: u32, occupied_tiles: &[Rect], ) -> Self { Pellet { rect: Pellet::random_spawn_location(window_width, window_height, w, h, occupied_tiles), window_width, window_height, w, h, eaten: false, } } pub fn draw(&self, renderer: &mut WindowCanvas) -> Result<(), String> { renderer.set_draw_color(Color::RGBA(255, 255, 255, 0)); renderer.fill_rect(*self.rect)?; renderer.draw_rect(*self.rect) } pub fn current_location(&self) -> Rect { *self.rect } pub fn respawn(&mut self, occupied_tiles: &[Rect]) { self.rect = Pellet::random_spawn_location( self.window_width, self.window_height, self.w, self.h, occupied_tiles, ); self.eaten = false; } fn random_spawn_location( window_width: i32, window_height: i32, w: u32, h: u32, occupied_tiles: &[Rect], ) -> Box<Rect> { // The reason we do the following below is, so that we do not spawn the pellet inside the snake tiles. let length = ((window_width / w as i32) * (window_height / h as i32)) as usize; let mut set = HashSet::with_capacity(length); for tile in occupied_tiles { set.insert(*tile); } let mut available_tiles = Vec::with_capacity(length); let mut x = 0; let mut y = 0; for _ in 0..length { let rect = Rect::new(x, y, w, h); if !set.contains(&rect) { available_tiles.push(rect); } x = x + w as i32; if x > window_width - w as i32 { y = y + h as i32; x = 0; } } let random_index: usize = rand::random(); Box::new(available_tiles[random_index % available_tiles.len()]) } }
use arrow::buffer::{BooleanBuffer, Buffer}; use std::ops::Range; /// An arrow-compatible mutable bitset implementation /// /// Note: This currently operates on individual bytes at a time /// it could be optimised to instead operate on usize blocks #[derive(Debug, Default, Clone)] pub struct BitSet { /// The underlying data /// /// Data is stored in the least significant bit of a byte first buffer: Vec<u8>, /// The length of this mask in bits len: usize, } impl BitSet { /// Creates a new BitSet pub fn new() -> Self { Self::default() } /// Creates a new BitSet with `count` unset bits. pub fn with_size(count: usize) -> Self { let mut bitset = Self::default(); bitset.append_unset(count); bitset } /// Reserve space for `count` further bits pub fn reserve(&mut self, count: usize) { let new_buf_len = (self.len + count + 7) >> 3; self.buffer.reserve(new_buf_len); } /// Appends `count` unset bits pub fn append_unset(&mut self, count: usize) { self.len += count; let new_buf_len = (self.len + 7) >> 3; self.buffer.resize(new_buf_len, 0); } /// Appends `count` set bits pub fn append_set(&mut self, count: usize) { let new_len = self.len + count; let new_buf_len = (new_len + 7) >> 3; let skew = self.len & 7; if skew != 0 { *self.buffer.last_mut().unwrap() |= 0xFF << skew; } self.buffer.resize(new_buf_len, 0xFF); let rem = new_len & 7; if rem != 0 { *self.buffer.last_mut().unwrap() &= (1 << rem) - 1; } self.len = new_len; } /// Truncates the bitset to the provided length pub fn truncate(&mut self, len: usize) { let new_buf_len = (len + 7) >> 3; self.buffer.truncate(new_buf_len); let overrun = len & 7; if overrun > 0 { *self.buffer.last_mut().unwrap() &= (1 << overrun) - 1; } self.len = len; } /// Extends this [`BitSet`] by the context of `other` pub fn extend_from(&mut self, other: &BitSet) { self.append_bits(other.len, &other.buffer) } /// Extends this [`BitSet`] by `range` elements in `other` pub fn extend_from_range(&mut self, other: &BitSet, range: Range<usize>) { let count = range.end - range.start; if count == 0 { return; } let start_byte = range.start >> 3; let end_byte = (range.end + 7) >> 3; let skew = range.start & 7; // `append_bits` requires the provided `to_set` to be byte aligned, therefore // if the range being copied is not byte aligned we must first append // the leading bits to reach a byte boundary if skew == 0 { // No skew can simply append bytes directly self.append_bits(count, &other.buffer[start_byte..end_byte]) } else if start_byte + 1 == end_byte { // Append bits from single byte self.append_bits(count, &[other.buffer[start_byte] >> skew]) } else { // Append trailing bits from first byte to reach byte boundary, then append // bits from the remaining byte-aligned mask let offset = 8 - skew; self.append_bits(offset, &[other.buffer[start_byte] >> skew]); self.append_bits(count - offset, &other.buffer[(start_byte + 1)..end_byte]); } } /// Appends `count` boolean values from the slice of packed bits pub fn append_bits(&mut self, count: usize, to_set: &[u8]) { assert_eq!((count + 7) >> 3, to_set.len()); let new_len = self.len + count; let new_buf_len = (new_len + 7) >> 3; self.buffer.reserve(new_buf_len - self.buffer.len()); let whole_bytes = count >> 3; let overrun = count & 7; let skew = self.len & 7; if skew == 0 { self.buffer.extend_from_slice(&to_set[..whole_bytes]); if overrun > 0 { let masked = to_set[whole_bytes] & ((1 << overrun) - 1); self.buffer.push(masked) } self.len = new_len; debug_assert_eq!(self.buffer.len(), new_buf_len); return; } for to_set_byte in &to_set[..whole_bytes] { let low = *to_set_byte << skew; let high = *to_set_byte >> (8 - skew); *self.buffer.last_mut().unwrap() |= low; self.buffer.push(high); } if overrun > 0 { let masked = to_set[whole_bytes] & ((1 << overrun) - 1); let low = masked << skew; *self.buffer.last_mut().unwrap() |= low; if overrun > 8 - skew { let high = masked >> (8 - skew); self.buffer.push(high) } } self.len = new_len; debug_assert_eq!(self.buffer.len(), new_buf_len); } /// Sets a given bit pub fn set(&mut self, idx: usize) { assert!(idx <= self.len); let byte_idx = idx >> 3; let bit_idx = idx & 7; self.buffer[byte_idx] |= 1 << bit_idx; } /// Returns if the given index is set pub fn get(&self, idx: usize) -> bool { assert!(idx <= self.len); let byte_idx = idx >> 3; let bit_idx = idx & 7; (self.buffer[byte_idx] >> bit_idx) & 1 != 0 } /// Converts this BitSet to a buffer compatible with arrows boolean encoding pub fn to_arrow(&self) -> BooleanBuffer { let offset = 0; BooleanBuffer::new(Buffer::from(&self.buffer), offset, self.len) } /// Returns the number of values stored in the bitset pub fn len(&self) -> usize { self.len } /// Returns if this bitset is empty pub fn is_empty(&self) -> bool { self.len == 0 } /// Returns the number of bytes used by this bitset pub fn byte_len(&self) -> usize { self.buffer.len() } /// Return the raw packed bytes used by this bitset pub fn bytes(&self) -> &[u8] { &self.buffer } /// Return `true` if all bits in the [`BitSet`] are currently set. pub fn is_all_set(&self) -> bool { // An empty bitmap has no set bits. if self.len == 0 { return false; } // Check all the bytes in the bitmap that have all their bits considered // part of the bit set. let full_blocks = (self.len / 8).saturating_sub(1); if !self.buffer.iter().take(full_blocks).all(|&v| v == u8::MAX) { return false; } // Check the last byte of the bitmap that may only be partially part of // the bit set, and therefore need masking to check only the relevant // bits. let mask = match self.len % 8 { 1..=8 => !(0xFF << (self.len % 8)), // LSB mask 0 => 0xFF, _ => unreachable!(), }; *self.buffer.last().unwrap() == mask } /// Return `true` if all bits in the [`BitSet`] are currently unset. pub fn is_all_unset(&self) -> bool { self.buffer.iter().all(|&v| v == 0) } } /// Returns an iterator over set bit positions in increasing order pub fn iter_set_positions(bytes: &[u8]) -> impl Iterator<Item = usize> + '_ { iter_set_positions_with_offset(bytes, 0) } /// Returns an iterator over set bit positions in increasing order starting /// at the provided bit offset pub fn iter_set_positions_with_offset( bytes: &[u8], offset: usize, ) -> impl Iterator<Item = usize> + '_ { let mut byte_idx = offset >> 3; let mut in_progress = bytes.get(byte_idx).cloned().unwrap_or(0); let skew = offset & 7; in_progress &= 0xFF << skew; std::iter::from_fn(move || loop { if in_progress != 0 { let bit_pos = in_progress.trailing_zeros(); in_progress ^= 1 << bit_pos; return Some((byte_idx << 3) + (bit_pos as usize)); } byte_idx += 1; in_progress = *bytes.get(byte_idx)?; }) } #[cfg(test)] mod tests { use super::*; use arrow::array::BooleanBufferBuilder; use rand::prelude::*; use rand::rngs::OsRng; /// Computes a compacted representation of a given bool array fn compact_bools(bools: &[bool]) -> Vec<u8> { bools .chunks(8) .map(|x| { let mut collect = 0_u8; for (idx, set) in x.iter().enumerate() { if *set { collect |= 1 << idx } } collect }) .collect() } fn iter_set_bools(bools: &[bool]) -> impl Iterator<Item = usize> + '_ { bools.iter().enumerate().filter_map(|(x, y)| y.then(|| x)) } #[test] fn test_compact_bools() { let bools = &[ false, false, true, true, false, false, true, false, true, false, ]; let collected = compact_bools(bools); let indexes: Vec<_> = iter_set_bools(bools).collect(); assert_eq!(collected.as_slice(), &[0b01001100, 0b00000001]); assert_eq!(indexes.as_slice(), &[2, 3, 6, 8]) } #[test] fn test_bit_mask() { let mut mask = BitSet::new(); mask.append_bits(8, &[0b11111111]); let d1 = mask.buffer.clone(); mask.append_bits(3, &[0b01010010]); let d2 = mask.buffer.clone(); mask.append_bits(5, &[0b00010100]); let d3 = mask.buffer.clone(); mask.append_bits(2, &[0b11110010]); let d4 = mask.buffer.clone(); mask.append_bits(15, &[0b11011010, 0b01010101]); let d5 = mask.buffer.clone(); assert_eq!(d1.as_slice(), &[0b11111111]); assert_eq!(d2.as_slice(), &[0b11111111, 0b00000010]); assert_eq!(d3.as_slice(), &[0b11111111, 0b10100010]); assert_eq!(d4.as_slice(), &[0b11111111, 0b10100010, 0b00000010]); assert_eq!( d5.as_slice(), &[0b11111111, 0b10100010, 0b01101010, 0b01010111, 0b00000001] ); assert!(mask.get(0)); assert!(!mask.get(8)); assert!(mask.get(9)); assert!(mask.get(19)); } fn make_rng() -> StdRng { let seed = OsRng.next_u64(); println!("Seed: {seed}"); StdRng::seed_from_u64(seed) } #[test] fn test_bit_mask_all_set() { let mut mask = BitSet::new(); let mut all_bools = vec![]; let mut rng = make_rng(); for _ in 0..100 { let mask_length = (rng.next_u32() % 50) as usize; let bools: Vec<_> = std::iter::repeat(true).take(mask_length).collect(); let collected = compact_bools(&bools); mask.append_bits(mask_length, &collected); all_bools.extend_from_slice(&bools); } let collected = compact_bools(&all_bools); assert_eq!(mask.buffer, collected); let expected_indexes: Vec<_> = iter_set_bools(&all_bools).collect(); let actual_indexes: Vec<_> = iter_set_positions(&mask.buffer).collect(); assert_eq!(expected_indexes, actual_indexes); } #[test] fn test_bit_mask_fuzz() { let mut mask = BitSet::new(); let mut all_bools = vec![]; let mut rng = make_rng(); for _ in 0..100 { let mask_length = (rng.next_u32() % 50) as usize; let bools: Vec<_> = std::iter::from_fn(|| Some(rng.next_u32() & 1 == 0)) .take(mask_length) .collect(); let collected = compact_bools(&bools); mask.append_bits(mask_length, &collected); all_bools.extend_from_slice(&bools); } let collected = compact_bools(&all_bools); assert_eq!(mask.buffer, collected); let expected_indexes: Vec<_> = iter_set_bools(&all_bools).collect(); let actual_indexes: Vec<_> = iter_set_positions(&mask.buffer).collect(); assert_eq!(expected_indexes, actual_indexes); if !all_bools.is_empty() { for _ in 0..10 { let offset = rng.next_u32() as usize % all_bools.len(); let expected_indexes: Vec<_> = iter_set_bools(&all_bools[offset..]) .map(|x| x + offset) .collect(); let actual_indexes: Vec<_> = iter_set_positions_with_offset(&mask.buffer, offset).collect(); assert_eq!(expected_indexes, actual_indexes); } } for index in actual_indexes { assert!(mask.get(index)); } } #[test] fn test_append_fuzz() { let mut mask = BitSet::new(); let mut all_bools = vec![]; let mut rng = make_rng(); for _ in 0..100 { let len = (rng.next_u32() % 32) as usize; let set = rng.next_u32() & 1 == 0; match set { true => mask.append_set(len), false => mask.append_unset(len), } all_bools.extend(std::iter::repeat(set).take(len)); let collected = compact_bools(&all_bools); assert_eq!(mask.buffer, collected); } } #[test] fn test_truncate_fuzz() { let mut mask = BitSet::new(); let mut all_bools = vec![]; let mut rng = make_rng(); for _ in 0..100 { let mask_length = (rng.next_u32() % 32) as usize; let bools: Vec<_> = std::iter::from_fn(|| Some(rng.next_u32() & 1 == 0)) .take(mask_length) .collect(); let collected = compact_bools(&bools); mask.append_bits(mask_length, &collected); all_bools.extend_from_slice(&bools); if !all_bools.is_empty() { let truncate = rng.next_u32() as usize % all_bools.len(); mask.truncate(truncate); all_bools.truncate(truncate); } let collected = compact_bools(&all_bools); assert_eq!(mask.buffer, collected); } } #[test] fn test_extend_range_fuzz() { let mut rng = make_rng(); let src_len = 32; let src_bools: Vec<_> = std::iter::from_fn(|| Some(rng.next_u32() & 1 == 0)) .take(src_len) .collect(); let mut src_mask = BitSet::new(); src_mask.append_bits(src_len, &compact_bools(&src_bools)); let mut dst_bools = Vec::new(); let mut dst_mask = BitSet::new(); for _ in 0..100 { let a = rng.next_u32() as usize % src_len; let b = rng.next_u32() as usize % src_len; let start = a.min(b); let end = a.max(b); dst_bools.extend_from_slice(&src_bools[start..end]); dst_mask.extend_from_range(&src_mask, start..end); let collected = compact_bools(&dst_bools); assert_eq!(dst_mask.buffer, collected); } } #[test] fn test_arrow_compat() { let bools = &[ false, false, true, true, false, false, true, false, true, false, false, true, ]; let mut builder = BooleanBufferBuilder::new(bools.len()); builder.append_slice(bools); let buffer = builder.finish(); let collected = compact_bools(bools); let mut mask = BitSet::new(); mask.append_bits(bools.len(), &collected); let mask_buffer = mask.to_arrow(); assert_eq!(collected.as_slice(), buffer.values()); assert_eq!(buffer.values(), mask_buffer.into_inner().as_slice()); } #[test] #[should_panic = "idx <= self.len"] fn test_bitset_set_get_out_of_bounds() { let mut v = BitSet::with_size(4); // The bitset is of length 4, which is backed by a single byte with 8 // bits of storage capacity. // // Accessing bits past the 4 the bitset "contains" should not succeed. v.get(5); v.set(5); } #[test] fn test_all_set_unset() { for i in 1..100 { let mut v = BitSet::new(); v.append_set(i); assert!(v.is_all_set()); assert!(!v.is_all_unset()); } } #[test] fn test_all_set_unset_multi_byte() { let mut v = BitSet::new(); // Bitmap is composed of entirely set bits. v.append_set(100); assert!(v.is_all_set()); assert!(!v.is_all_unset()); // Now the bitmap is neither composed of entirely set, nor entirely // unset bits. v.append_unset(1); assert!(!v.is_all_set()); assert!(!v.is_all_unset()); let mut v = BitSet::new(); // Bitmap is composed of entirely unset bits. v.append_unset(100); assert!(!v.is_all_set()); assert!(v.is_all_unset()); // And once again, it is neither all set, nor all unset. v.append_set(1); assert!(!v.is_all_set()); assert!(!v.is_all_unset()); } #[test] fn test_all_set_unset_single_byte() { let mut v = BitSet::new(); // Bitmap is composed of entirely set bits. v.append_set(2); assert!(v.is_all_set()); assert!(!v.is_all_unset()); // Now the bitmap is neither composed of entirely set, nor entirely // unset bits. v.append_unset(1); assert!(!v.is_all_set()); assert!(!v.is_all_unset()); let mut v = BitSet::new(); // Bitmap is composed of entirely unset bits. v.append_unset(2); assert!(!v.is_all_set()); assert!(v.is_all_unset()); // And once again, it is neither all set, nor all unset. v.append_set(1); assert!(!v.is_all_set()); assert!(!v.is_all_unset()); } #[test] fn test_all_set_unset_empty() { let v = BitSet::new(); assert!(!v.is_all_set()); assert!(v.is_all_unset()); } }
#![crate_name = "rspark"] pub mod rspark { use std::error::Error; use std::fmt; /// The Unicode representation of the graph ticks. const TICKS: [char; 8] = [ '\u{2581}', '\u{2582}', '\u{2583}', '\u{2584}', '\u{2585}', '\u{2586}', '\u{2587}', '\u{2588}', ]; /// Renders a graph for the given numeric vector. /// /// # Arguments /// /// * `v` - The numeric vector to render a graph. /// /// # Examples /// /// ``` /// let v = vec![2, 250, 670, 890, 2, 430, 11, 908, 123, 57]; /// let res = rspark::rspark::render(&v).unwrap(); /// assert_eq!("▁▂▆▇▁▄▁█▁▁", res); /// ``` pub fn render(v: &Vec<i32>) -> Result<String, RenderError> { let mut s = String::new(); render_to(v, &mut s) .map(|ok_val| ok_val.to_string()) .map_err(|err_val| err_val) } /// Renders a graph and appends it to the given string. /// /// # Arguments /// /// * `v` - The numeric vector to render a graph. /// * `s` - The mutable String pointer to append the graph. /// /// # Examples /// /// ``` /// let v = vec![2, 250, 670, 890, 2, 430, 11, 908, 123, 57]; /// let mut s = String::from(">"); /// let res = rspark::rspark::render_to(&v, &mut s).unwrap(); /// assert_eq!(">▁▂▆▇▁▄▁█▁▁", res); /// ``` pub fn render_to<'a>(v: &Vec<i32>, s: &'a mut String) -> Result<&'a str, RenderError> { if v.len() < 2 { return Err(RenderError::InvalidVectorParameter); } let max = v.iter().max().unwrap(); let min = v.iter().min().unwrap(); let scale = (max - min) as f32 / 7.; for e in v.iter() { let i = (e - min) / scale as i32; (*s).push_str(&TICKS[i as usize].to_string()); } Ok(&s[..]) } #[derive(Debug)] pub enum RenderError { /// The invalid vector parameter error. InvalidVectorParameter, } impl fmt::Display for RenderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RenderError::InvalidVectorParameter => f.write_str("InvalidVectorParameter"), } } } impl Error for RenderError { fn description(&self) -> &str { match *self { RenderError::InvalidVectorParameter => "Invalid vector parameter", } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_render() { let v = vec![2, 250, 670, 890, 2, 430, 11, 908, 123, 57]; let res = rspark::render(&v).unwrap(); println!("{}", res); assert_eq!("▁▂▆▇▁▄▁█▁▁", res); } #[test] fn test_render_to() { let v = vec![2, 250, 670, 890, 2, 430, 11, 908, 123, 57]; let mut s = String::from(">"); let res = rspark::render_to(&v, &mut s).unwrap(); println!("{}", res); assert_eq!(">▁▂▆▇▁▄▁█▁▁", res); } #[test] fn test_render_err() { let v = vec![2]; let res = rspark::render(&v); match res { Ok(_) => panic!("Error expected."), _ => (), } } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! A futures-rs executor design specifically for Fuchsia OS. #![deny(missing_docs)] // Set the system allocator for anything using this crate extern crate fuchsia_system_alloc; /// A future which can be used by multiple threads at once. pub mod atomic_future; mod channel; pub use self::channel::{Channel, RecvMsg}; mod on_signals; pub use self::on_signals::OnSignals; mod rwhandle; pub use self::rwhandle::RWHandle; mod socket; pub use self::socket::Socket; mod timer; pub use self::timer::{Interval, OnTimeout, TimeoutExt, Timer}; mod executor; pub use self::executor::{ spawn, spawn_local, DurationExt, EHandle, Executor, PacketReceiver, ReceiverRegistration, Time, WaitState, }; mod fifo; pub use self::fifo::{Fifo, FifoEntry, FifoReadable, FifoWritable, ReadEntry, WriteEntry}; pub mod net; // Re-export pin_mut as its used by the async proc macros pub use pin_utils::pin_mut; pub use fuchsia_async_macro::{run, run_singlethreaded, run_until_stalled}; // TODO(cramertj) remove once async/awaitification has occurred pub mod temp; // Reexport futures for use in macros; #[doc(hidden)] pub mod futures { pub use futures::*; }
mod port_bind; mod start; mod stop; pub use port_bind::ProcessPortBindLog; pub use start::ProcessStart; pub use stop::ProcessStop;
::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn LdapGetLastError ( ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn LdapMapErrorToWin32 ( ldaperror : LDAP_RETCODE ) -> super::super::Foundation:: WIN32_ERROR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn LdapUTF8ToUnicode ( lpsrcstr : :: windows_sys::core::PCSTR , cchsrc : i32 , lpdeststr : :: windows_sys::core::PWSTR , cchdest : i32 ) -> i32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn LdapUnicodeToUTF8 ( lpsrcstr : :: windows_sys::core::PCWSTR , cchsrc : i32 , lpdeststr : :: windows_sys::core::PSTR , cchdest : i32 ) -> i32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_alloc_t ( options : i32 ) -> *mut BerElement ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_bvdup ( pberval : *mut LDAP_BERVAL ) -> *mut LDAP_BERVAL ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_bvecfree ( pberval : *mut *mut LDAP_BERVAL ) -> ( ) ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_bvfree ( bv : *mut LDAP_BERVAL ) -> ( ) ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ber_first_element ( pberelement : *mut BerElement , plen : *mut u32 , ppopaque : *mut *mut super::super::Foundation:: CHAR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_flatten ( pberelement : *mut BerElement , pberval : *mut *mut LDAP_BERVAL ) -> i32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_free ( pberelement : *mut BerElement , fbuf : i32 ) -> ( ) ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_init ( pberval : *mut LDAP_BERVAL ) -> *mut BerElement ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_next_element ( pberelement : *mut BerElement , plen : *mut u32 , opaque : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_peek_tag ( pberelement : *mut BerElement , plen : *mut u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_printf ( pberelement : *mut BerElement , fmt : :: windows_sys::core::PCSTR ) -> i32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_scanf ( pberelement : *mut BerElement , fmt : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ber_skip_tag ( pberelement : *mut BerElement , plen : *mut u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn cldap_open ( hostname : :: windows_sys::core::PCSTR , portnumber : u32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn cldap_openA ( hostname : :: windows_sys::core::PCSTR , portnumber : u32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn cldap_openW ( hostname : :: windows_sys::core::PCWSTR , portnumber : u32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_abandon ( ld : *mut LDAP , msgid : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_add ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attrs : *mut *mut LDAPModA ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_addA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attrs : *mut *mut LDAPModA ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_addW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , attrs : *mut *mut LDAPModW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_add_ext ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attrs : *mut *mut LDAPModA , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_add_extA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attrs : *mut *mut LDAPModA , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_add_extW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , attrs : *mut *mut LDAPModW , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_add_ext_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attrs : *mut *mut LDAPModA , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_add_ext_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attrs : *mut *mut LDAPModA , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_add_ext_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , attrs : *mut *mut LDAPModW , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_add_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attrs : *mut *mut LDAPModA ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_add_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attrs : *mut *mut LDAPModA ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_add_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , attrs : *mut *mut LDAPModW ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_bind ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , cred : :: windows_sys::core::PCSTR , method : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_bindA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , cred : :: windows_sys::core::PCSTR , method : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_bindW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , cred : :: windows_sys::core::PCWSTR , method : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_bind_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , cred : :: windows_sys::core::PCSTR , method : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_bind_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , cred : :: windows_sys::core::PCSTR , method : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_bind_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , cred : :: windows_sys::core::PCWSTR , method : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_check_filterA ( ld : *mut LDAP , searchfilter : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_check_filterW ( ld : *mut LDAP , searchfilter : :: windows_sys::core::PCWSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_cleanup ( hinstance : super::super::Foundation:: HANDLE ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_close_extended_op ( ld : *mut LDAP , messagenumber : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_compare ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attr : :: windows_sys::core::PCSTR , value : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_compareA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attr : :: windows_sys::core::PCSTR , value : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_compareW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , attr : :: windows_sys::core::PCWSTR , value : :: windows_sys::core::PCWSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_compare_ext ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attr : :: windows_sys::core::PCSTR , value : :: windows_sys::core::PCSTR , data : *mut LDAP_BERVAL , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_compare_extA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attr : :: windows_sys::core::PCSTR , value : :: windows_sys::core::PCSTR , data : *const LDAP_BERVAL , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_compare_extW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , attr : :: windows_sys::core::PCWSTR , value : :: windows_sys::core::PCWSTR , data : *const LDAP_BERVAL , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_compare_ext_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attr : :: windows_sys::core::PCSTR , value : :: windows_sys::core::PCSTR , data : *mut LDAP_BERVAL , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_compare_ext_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attr : :: windows_sys::core::PCSTR , value : :: windows_sys::core::PCSTR , data : *const LDAP_BERVAL , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_compare_ext_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , attr : :: windows_sys::core::PCWSTR , value : :: windows_sys::core::PCWSTR , data : *const LDAP_BERVAL , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_compare_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attr : :: windows_sys::core::PCSTR , value : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_compare_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , attr : :: windows_sys::core::PCSTR , value : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_compare_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , attr : :: windows_sys::core::PCWSTR , value : :: windows_sys::core::PCWSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_conn_from_msg ( primaryconn : *mut LDAP , res : *mut LDAPMessage ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_connect ( ld : *mut LDAP , timeout : *mut LDAP_TIMEVAL ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_control_free ( control : *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_control_freeA ( controls : *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_control_freeW ( control : *mut LDAPControlW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_controls_free ( controls : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_controls_freeA ( controls : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_controls_freeW ( control : *mut *mut LDAPControlW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_count_entries ( ld : *mut LDAP , res : *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_count_references ( ld : *mut LDAP , res : *mut LDAPMessage ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_count_values ( vals : *const :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_count_valuesA ( vals : *const :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_count_valuesW ( vals : *const :: windows_sys::core::PCWSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_count_values_len ( vals : *mut *mut LDAP_BERVAL ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_create_page_control ( externalhandle : *mut LDAP , pagesize : u32 , cookie : *mut LDAP_BERVAL , iscritical : u8 , control : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_create_page_controlA ( externalhandle : *mut LDAP , pagesize : u32 , cookie : *mut LDAP_BERVAL , iscritical : u8 , control : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_create_page_controlW ( externalhandle : *mut LDAP , pagesize : u32 , cookie : *mut LDAP_BERVAL , iscritical : u8 , control : *mut *mut LDAPControlW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_create_sort_control ( externalhandle : *mut LDAP , sortkeys : *mut *mut LDAPSortKeyA , iscritical : u8 , control : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_create_sort_controlA ( externalhandle : *mut LDAP , sortkeys : *mut *mut LDAPSortKeyA , iscritical : u8 , control : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_create_sort_controlW ( externalhandle : *mut LDAP , sortkeys : *mut *mut LDAPSortKeyW , iscritical : u8 , control : *mut *mut LDAPControlW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_create_vlv_controlA ( externalhandle : *mut LDAP , vlvinfo : *mut LDAPVLVInfo , iscritical : u8 , control : *mut *mut LDAPControlA ) -> i32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_create_vlv_controlW ( externalhandle : *mut LDAP , vlvinfo : *mut LDAPVLVInfo , iscritical : u8 , control : *mut *mut LDAPControlW ) -> i32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_delete ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_deleteA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_deleteW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_delete_ext ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_delete_extA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_delete_extW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_delete_ext_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_delete_ext_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_delete_ext_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_delete_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_delete_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_delete_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_dn2ufn ( dn : :: windows_sys::core::PCSTR ) -> :: windows_sys::core::PSTR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_dn2ufnA ( dn : :: windows_sys::core::PCSTR ) -> :: windows_sys::core::PSTR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_dn2ufnW ( dn : :: windows_sys::core::PCWSTR ) -> :: windows_sys::core::PWSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_encode_sort_controlA ( externalhandle : *mut LDAP , sortkeys : *mut *mut LDAPSortKeyA , control : *mut LDAPControlA , criticality : super::super::Foundation:: BOOLEAN ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_encode_sort_controlW ( externalhandle : *mut LDAP , sortkeys : *mut *mut LDAPSortKeyW , control : *mut LDAPControlW , criticality : super::super::Foundation:: BOOLEAN ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_err2string ( err : u32 ) -> :: windows_sys::core::PSTR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_err2stringA ( err : u32 ) -> :: windows_sys::core::PSTR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_err2stringW ( err : u32 ) -> :: windows_sys::core::PWSTR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_escape_filter_element ( sourcefilterelement : :: windows_sys::core::PCSTR , sourcelength : u32 , destfilterelement : :: windows_sys::core::PSTR , destlength : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_escape_filter_elementA ( sourcefilterelement : :: windows_sys::core::PCSTR , sourcelength : u32 , destfilterelement : :: windows_sys::core::PSTR , destlength : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_escape_filter_elementW ( sourcefilterelement : :: windows_sys::core::PCSTR , sourcelength : u32 , destfilterelement : :: windows_sys::core::PWSTR , destlength : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_explode_dn ( dn : :: windows_sys::core::PCSTR , notypes : u32 ) -> *mut :: windows_sys::core::PSTR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_explode_dnA ( dn : :: windows_sys::core::PCSTR , notypes : u32 ) -> *mut :: windows_sys::core::PSTR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_explode_dnW ( dn : :: windows_sys::core::PCWSTR , notypes : u32 ) -> *mut :: windows_sys::core::PWSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_extended_operation ( ld : *mut LDAP , oid : :: windows_sys::core::PCSTR , data : *mut LDAP_BERVAL , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_extended_operationA ( ld : *mut LDAP , oid : :: windows_sys::core::PCSTR , data : *mut LDAP_BERVAL , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_extended_operationW ( ld : *mut LDAP , oid : :: windows_sys::core::PCWSTR , data : *mut LDAP_BERVAL , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_extended_operation_sA ( externalhandle : *mut LDAP , oid : :: windows_sys::core::PCSTR , data : *mut LDAP_BERVAL , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , returnedoid : *mut :: windows_sys::core::PSTR , returneddata : *mut *mut LDAP_BERVAL ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_extended_operation_sW ( externalhandle : *mut LDAP , oid : :: windows_sys::core::PCWSTR , data : *mut LDAP_BERVAL , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW , returnedoid : *mut :: windows_sys::core::PWSTR , returneddata : *mut *mut LDAP_BERVAL ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_first_attribute ( ld : *mut LDAP , entry : *mut LDAPMessage , ptr : *mut *mut BerElement ) -> :: windows_sys::core::PSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_first_attributeA ( ld : *mut LDAP , entry : *mut LDAPMessage , ptr : *mut *mut BerElement ) -> :: windows_sys::core::PSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_first_attributeW ( ld : *mut LDAP , entry : *mut LDAPMessage , ptr : *mut *mut BerElement ) -> :: windows_sys::core::PWSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_first_entry ( ld : *mut LDAP , res : *mut LDAPMessage ) -> *mut LDAPMessage ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_first_reference ( ld : *mut LDAP , res : *mut LDAPMessage ) -> *mut LDAPMessage ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_free_controls ( controls : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_free_controlsA ( controls : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_free_controlsW ( controls : *mut *mut LDAPControlW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_dn ( ld : *mut LDAP , entry : *mut LDAPMessage ) -> :: windows_sys::core::PSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_dnA ( ld : *mut LDAP , entry : *mut LDAPMessage ) -> :: windows_sys::core::PSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_dnW ( ld : *mut LDAP , entry : *mut LDAPMessage ) -> :: windows_sys::core::PWSTR ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_get_next_page ( externalhandle : *mut LDAP , searchhandle : *mut LDAPSearch , pagesize : u32 , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_next_page_s ( externalhandle : *mut LDAP , searchhandle : *mut LDAPSearch , timeout : *mut LDAP_TIMEVAL , pagesize : u32 , totalcount : *mut u32 , results : *mut *mut LDAPMessage ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_get_option ( ld : *mut LDAP , option : i32 , outvalue : *mut ::core::ffi::c_void ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_get_optionW ( ld : *mut LDAP , option : i32 , outvalue : *mut ::core::ffi::c_void ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_paged_count ( externalhandle : *mut LDAP , searchblock : *mut LDAPSearch , totalcount : *mut u32 , results : *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_values ( ld : *mut LDAP , entry : *mut LDAPMessage , attr : :: windows_sys::core::PCSTR ) -> *mut :: windows_sys::core::PSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_valuesA ( ld : *mut LDAP , entry : *mut LDAPMessage , attr : :: windows_sys::core::PCSTR ) -> *mut :: windows_sys::core::PSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_valuesW ( ld : *mut LDAP , entry : *mut LDAPMessage , attr : :: windows_sys::core::PCWSTR ) -> *mut :: windows_sys::core::PWSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_values_len ( externalhandle : *mut LDAP , message : *mut LDAPMessage , attr : :: windows_sys::core::PCSTR ) -> *mut *mut LDAP_BERVAL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_values_lenA ( externalhandle : *mut LDAP , message : *mut LDAPMessage , attr : :: windows_sys::core::PCSTR ) -> *mut *mut LDAP_BERVAL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_get_values_lenW ( externalhandle : *mut LDAP , message : *mut LDAPMessage , attr : :: windows_sys::core::PCWSTR ) -> *mut *mut LDAP_BERVAL ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_init ( hostname : :: windows_sys::core::PCSTR , portnumber : u32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_initA ( hostname : :: windows_sys::core::PCSTR , portnumber : u32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_initW ( hostname : :: windows_sys::core::PCWSTR , portnumber : u32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_memfree ( block : :: windows_sys::core::PCSTR ) -> ( ) ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_memfreeA ( block : :: windows_sys::core::PCSTR ) -> ( ) ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_memfreeW ( block : :: windows_sys::core::PCWSTR ) -> ( ) ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modify ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , mods : *mut *mut LDAPModA ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modifyA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , mods : *mut *mut LDAPModA ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modifyW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , mods : *mut *mut LDAPModW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_modify_ext ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , mods : *mut *mut LDAPModA , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_modify_extA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , mods : *mut *mut LDAPModA , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_modify_extW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , mods : *mut *mut LDAPModW , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_modify_ext_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , mods : *mut *mut LDAPModA , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_modify_ext_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , mods : *mut *mut LDAPModA , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_modify_ext_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , mods : *mut *mut LDAPModW , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modify_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , mods : *mut *mut LDAPModA ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modify_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , mods : *mut *mut LDAPModA ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modify_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , mods : *mut *mut LDAPModW ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , newdistinguishedname : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn2 ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , newdistinguishedname : :: windows_sys::core::PCSTR , deleteoldrdn : i32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn2A ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , newdistinguishedname : :: windows_sys::core::PCSTR , deleteoldrdn : i32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn2W ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCWSTR , newdistinguishedname : :: windows_sys::core::PCWSTR , deleteoldrdn : i32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn2_s ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , newdistinguishedname : :: windows_sys::core::PCSTR , deleteoldrdn : i32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn2_sA ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , newdistinguishedname : :: windows_sys::core::PCSTR , deleteoldrdn : i32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn2_sW ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCWSTR , newdistinguishedname : :: windows_sys::core::PCWSTR , deleteoldrdn : i32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdnA ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , newdistinguishedname : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdnW ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCWSTR , newdistinguishedname : :: windows_sys::core::PCWSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn_s ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , newdistinguishedname : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn_sA ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , newdistinguishedname : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_modrdn_sW ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCWSTR , newdistinguishedname : :: windows_sys::core::PCWSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_msgfree ( res : *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_next_attribute ( ld : *mut LDAP , entry : *mut LDAPMessage , ptr : *mut BerElement ) -> :: windows_sys::core::PSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_next_attributeA ( ld : *mut LDAP , entry : *mut LDAPMessage , ptr : *mut BerElement ) -> :: windows_sys::core::PSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_next_attributeW ( ld : *mut LDAP , entry : *mut LDAPMessage , ptr : *mut BerElement ) -> :: windows_sys::core::PWSTR ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_next_entry ( ld : *mut LDAP , entry : *mut LDAPMessage ) -> *mut LDAPMessage ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_next_reference ( ld : *mut LDAP , entry : *mut LDAPMessage ) -> *mut LDAPMessage ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_open ( hostname : :: windows_sys::core::PCSTR , portnumber : u32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_openA ( hostname : :: windows_sys::core::PCSTR , portnumber : u32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_openW ( hostname : :: windows_sys::core::PCWSTR , portnumber : u32 ) -> *mut LDAP ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_extended_resultA ( connection : *mut LDAP , resultmessage : *mut LDAPMessage , resultoid : *mut :: windows_sys::core::PSTR , resultdata : *mut *mut LDAP_BERVAL , freeit : super::super::Foundation:: BOOLEAN ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_extended_resultW ( connection : *mut LDAP , resultmessage : *mut LDAPMessage , resultoid : *mut :: windows_sys::core::PWSTR , resultdata : *mut *mut LDAP_BERVAL , freeit : super::super::Foundation:: BOOLEAN ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_page_control ( externalhandle : *mut LDAP , servercontrols : *mut *mut LDAPControlA , totalcount : *mut u32 , cookie : *mut *mut LDAP_BERVAL ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_page_controlA ( externalhandle : *mut LDAP , servercontrols : *mut *mut LDAPControlA , totalcount : *mut u32 , cookie : *mut *mut LDAP_BERVAL ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_page_controlW ( externalhandle : *mut LDAP , servercontrols : *mut *mut LDAPControlW , totalcount : *mut u32 , cookie : *mut *mut LDAP_BERVAL ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_reference ( connection : *mut LDAP , resultmessage : *mut LDAPMessage , referrals : *mut *mut :: windows_sys::core::PSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_referenceA ( connection : *mut LDAP , resultmessage : *mut LDAPMessage , referrals : *mut *mut :: windows_sys::core::PSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_referenceW ( connection : *mut LDAP , resultmessage : *mut LDAPMessage , referrals : *mut *mut :: windows_sys::core::PWSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_result ( connection : *mut LDAP , resultmessage : *mut LDAPMessage , returncode : *mut u32 , matcheddns : *mut :: windows_sys::core::PSTR , errormessage : *mut :: windows_sys::core::PSTR , referrals : *mut *mut :: windows_sys::core::PSTR , servercontrols : *mut *mut *mut LDAPControlA , freeit : super::super::Foundation:: BOOLEAN ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_resultA ( connection : *mut LDAP , resultmessage : *mut LDAPMessage , returncode : *mut u32 , matcheddns : *mut :: windows_sys::core::PSTR , errormessage : *mut :: windows_sys::core::PSTR , referrals : *mut *mut *mut i8 , servercontrols : *mut *mut *mut LDAPControlA , freeit : super::super::Foundation:: BOOLEAN ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_resultW ( connection : *mut LDAP , resultmessage : *mut LDAPMessage , returncode : *mut u32 , matcheddns : *mut :: windows_sys::core::PWSTR , errormessage : *mut :: windows_sys::core::PWSTR , referrals : *mut *mut *mut u16 , servercontrols : *mut *mut *mut LDAPControlW , freeit : super::super::Foundation:: BOOLEAN ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_sort_control ( externalhandle : *mut LDAP , control : *mut *mut LDAPControlA , result : *mut u32 , attribute : *mut :: windows_sys::core::PSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_sort_controlA ( externalhandle : *mut LDAP , control : *mut *mut LDAPControlA , result : *mut u32 , attribute : *mut :: windows_sys::core::PSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_sort_controlW ( externalhandle : *mut LDAP , control : *mut *mut LDAPControlW , result : *mut u32 , attribute : *mut :: windows_sys::core::PWSTR ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_vlv_controlA ( externalhandle : *mut LDAP , control : *mut *mut LDAPControlA , targetpos : *mut u32 , listcount : *mut u32 , context : *mut *mut LDAP_BERVAL , errcode : *mut i32 ) -> i32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_parse_vlv_controlW ( externalhandle : *mut LDAP , control : *mut *mut LDAPControlW , targetpos : *mut u32 , listcount : *mut u32 , context : *mut *mut LDAP_BERVAL , errcode : *mut i32 ) -> i32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_perror ( ld : *mut LDAP , msg : :: windows_sys::core::PCSTR ) -> ( ) ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_rename_ext ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , newrdn : :: windows_sys::core::PCSTR , newparent : :: windows_sys::core::PCSTR , deleteoldrdn : i32 , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_rename_extA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , newrdn : :: windows_sys::core::PCSTR , newparent : :: windows_sys::core::PCSTR , deleteoldrdn : i32 , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_rename_extW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , newrdn : :: windows_sys::core::PCWSTR , newparent : :: windows_sys::core::PCWSTR , deleteoldrdn : i32 , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_rename_ext_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , newrdn : :: windows_sys::core::PCSTR , newparent : :: windows_sys::core::PCSTR , deleteoldrdn : i32 , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_rename_ext_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , newrdn : :: windows_sys::core::PCSTR , newparent : :: windows_sys::core::PCSTR , deleteoldrdn : i32 , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_rename_ext_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , newrdn : :: windows_sys::core::PCWSTR , newparent : :: windows_sys::core::PCWSTR , deleteoldrdn : i32 , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_result ( ld : *mut LDAP , msgid : u32 , all : u32 , timeout : *const LDAP_TIMEVAL , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_result2error ( ld : *mut LDAP , res : *mut LDAPMessage , freeit : u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_sasl_bindA ( externalhandle : *mut LDAP , distname : :: windows_sys::core::PCSTR , authmechanism : :: windows_sys::core::PCSTR , cred : *const LDAP_BERVAL , serverctrls : *mut *mut LDAPControlA , clientctrls : *mut *mut LDAPControlA , messagenumber : *mut i32 ) -> i32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_sasl_bindW ( externalhandle : *mut LDAP , distname : :: windows_sys::core::PCWSTR , authmechanism : :: windows_sys::core::PCWSTR , cred : *const LDAP_BERVAL , serverctrls : *mut *mut LDAPControlW , clientctrls : *mut *mut LDAPControlW , messagenumber : *mut i32 ) -> i32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_sasl_bind_sA ( externalhandle : *mut LDAP , distname : :: windows_sys::core::PCSTR , authmechanism : :: windows_sys::core::PCSTR , cred : *const LDAP_BERVAL , serverctrls : *mut *mut LDAPControlA , clientctrls : *mut *mut LDAPControlA , serverdata : *mut *mut LDAP_BERVAL ) -> i32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_sasl_bind_sW ( externalhandle : *mut LDAP , distname : :: windows_sys::core::PCWSTR , authmechanism : :: windows_sys::core::PCWSTR , cred : *const LDAP_BERVAL , serverctrls : *mut *mut LDAPControlW , clientctrls : *mut *mut LDAPControlW , serverdata : *mut *mut LDAP_BERVAL ) -> i32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_search ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_searchA ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_searchW ( ld : *mut LDAP , base : :: windows_sys::core::PCWSTR , scope : u32 , filter : :: windows_sys::core::PCWSTR , attrs : *const *const u16 , attrsonly : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_search_abandon_page ( externalhandle : *mut LDAP , searchblock : *mut LDAPSearch ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_ext ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 , servercontrols : *const *const LDAPControlA , clientcontrols : *const *const LDAPControlA , timelimit : u32 , sizelimit : u32 , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_extA ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 , servercontrols : *const *const LDAPControlA , clientcontrols : *const *const LDAPControlA , timelimit : u32 , sizelimit : u32 , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_extW ( ld : *mut LDAP , base : :: windows_sys::core::PCWSTR , scope : u32 , filter : :: windows_sys::core::PCWSTR , attrs : *const *const u16 , attrsonly : u32 , servercontrols : *const *const LDAPControlW , clientcontrols : *const *const LDAPControlW , timelimit : u32 , sizelimit : u32 , messagenumber : *mut u32 ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_ext_s ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 , servercontrols : *const *const LDAPControlA , clientcontrols : *const *const LDAPControlA , timeout : *mut LDAP_TIMEVAL , sizelimit : u32 , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_ext_sA ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 , servercontrols : *const *const LDAPControlA , clientcontrols : *const *const LDAPControlA , timeout : *mut LDAP_TIMEVAL , sizelimit : u32 , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_ext_sW ( ld : *mut LDAP , base : :: windows_sys::core::PCWSTR , scope : u32 , filter : :: windows_sys::core::PCWSTR , attrs : *const *const u16 , attrsonly : u32 , servercontrols : *const *const LDAPControlW , clientcontrols : *const *const LDAPControlW , timeout : *mut LDAP_TIMEVAL , sizelimit : u32 , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_init_page ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , scopeofsearch : u32 , searchfilter : :: windows_sys::core::PCSTR , attributelist : *mut *mut i8 , attributesonly : u32 , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , pagetimelimit : u32 , totalsizelimit : u32 , sortkeys : *mut *mut LDAPSortKeyA ) -> *mut LDAPSearch ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_init_pageA ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCSTR , scopeofsearch : u32 , searchfilter : :: windows_sys::core::PCSTR , attributelist : *const *const i8 , attributesonly : u32 , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA , pagetimelimit : u32 , totalsizelimit : u32 , sortkeys : *mut *mut LDAPSortKeyA ) -> *mut LDAPSearch ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_init_pageW ( externalhandle : *mut LDAP , distinguishedname : :: windows_sys::core::PCWSTR , scopeofsearch : u32 , searchfilter : :: windows_sys::core::PCWSTR , attributelist : *const *const u16 , attributesonly : u32 , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW , pagetimelimit : u32 , totalsizelimit : u32 , sortkeys : *mut *mut LDAPSortKeyW ) -> *mut LDAPSearch ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_s ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_sA ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_sW ( ld : *mut LDAP , base : :: windows_sys::core::PCWSTR , scope : u32 , filter : :: windows_sys::core::PCWSTR , attrs : *const *const u16 , attrsonly : u32 , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_st ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 , timeout : *mut LDAP_TIMEVAL , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_stA ( ld : *mut LDAP , base : :: windows_sys::core::PCSTR , scope : u32 , filter : :: windows_sys::core::PCSTR , attrs : *const *const i8 , attrsonly : u32 , timeout : *mut LDAP_TIMEVAL , res : *mut *mut LDAPMessage ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_search_stW ( ld : *mut LDAP , base : :: windows_sys::core::PCWSTR , scope : u32 , filter : :: windows_sys::core::PCWSTR , attrs : *const *const u16 , attrsonly : u32 , timeout : *mut LDAP_TIMEVAL , res : *mut *mut LDAPMessage ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_set_dbg_flags ( newflags : u32 ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_set_dbg_routine ( debugprintroutine : DBGPRINT ) -> ( ) ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_set_option ( ld : *mut LDAP , option : i32 , invalue : *const ::core::ffi::c_void ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_set_optionW ( ld : *mut LDAP , option : i32 , invalue : *const ::core::ffi::c_void ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_simple_bind ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , passwd : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_simple_bindA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , passwd : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_simple_bindW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , passwd : :: windows_sys::core::PCWSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_simple_bind_s ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , passwd : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_simple_bind_sA ( ld : *mut LDAP , dn : :: windows_sys::core::PCSTR , passwd : :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_simple_bind_sW ( ld : *mut LDAP , dn : :: windows_sys::core::PCWSTR , passwd : :: windows_sys::core::PCWSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_sslinit ( hostname : :: windows_sys::core::PCSTR , portnumber : u32 , secure : i32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_sslinitA ( hostname : :: windows_sys::core::PCSTR , portnumber : u32 , secure : i32 ) -> *mut LDAP ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_sslinitW ( hostname : :: windows_sys::core::PCWSTR , portnumber : u32 , secure : i32 ) -> *mut LDAP ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_start_tls_sA ( externalhandle : *mut LDAP , serverreturnvalue : *mut u32 , result : *mut *mut LDAPMessage , servercontrols : *mut *mut LDAPControlA , clientcontrols : *mut *mut LDAPControlA ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_start_tls_sW ( externalhandle : *mut LDAP , serverreturnvalue : *mut u32 , result : *mut *mut LDAPMessage , servercontrols : *mut *mut LDAPControlW , clientcontrols : *mut *mut LDAPControlW ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_startup ( version : *mut LDAP_VERSION_INFO , instance : *mut super::super::Foundation:: HANDLE ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ldap_stop_tls_s ( externalhandle : *mut LDAP ) -> super::super::Foundation:: BOOLEAN ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_ufn2dn ( ufn : :: windows_sys::core::PCSTR , pdn : *mut :: windows_sys::core::PSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_ufn2dnA ( ufn : :: windows_sys::core::PCSTR , pdn : *mut :: windows_sys::core::PSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_ufn2dnW ( ufn : :: windows_sys::core::PCWSTR , pdn : *mut :: windows_sys::core::PWSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_unbind ( ld : *mut LDAP ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_unbind_s ( ld : *mut LDAP ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_value_free ( vals : *const :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_value_freeA ( vals : *const :: windows_sys::core::PCSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_value_freeW ( vals : *const :: windows_sys::core::PCWSTR ) -> u32 ); ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn ldap_value_free_len ( vals : *mut *mut LDAP_BERVAL ) -> u32 ); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LAPI_MAJOR_VER1: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LAPI_MINOR_VER1: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LBER_DEFAULT: i32 = -1i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LBER_ERROR: i32 = -1i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LBER_TRANSLATE_STRINGS: u32 = 4u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LBER_USE_DER: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LBER_USE_INDEFINITE_LEN: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_ABANDON_CMD: i32 = 80i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_ADD_CMD: i32 = 104i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_API_FEATURE_VIRTUAL_LIST_VIEW: u32 = 1001u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_API_INFO_VERSION: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_API_VERSION: u32 = 2004u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_AUTH_OTHERKIND: i32 = 134i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_AUTH_SASL: i32 = 131i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_AUTH_SIMPLE: i32 = 128i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_BIND_CMD: i32 = 96i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_ADAM_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1851"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_ADAM_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1851"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_LDAP_INTEG_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1791"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_LDAP_INTEG_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1791"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.800"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.800"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_PARTIAL_SECRETS_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1920"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_PARTIAL_SECRETS_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1920"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_V51_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1670"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_V51_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1670"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_V60_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1935"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_V60_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1935"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_V61_OID: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1935"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_V61_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1935"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_V61_R2_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2080"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_V61_R2_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2080"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_W8_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2237"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CAP_ACTIVE_DIRECTORY_W8_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2237"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CHASE_EXTERNAL_REFERRALS: u32 = 64u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CHASE_SUBORDINATE_REFERRALS: u32 = 32u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_COMPARE_CMD: i32 = 110i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONTROL_REFERRALS: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.616"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONTROL_REFERRALS_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.616"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONTROL_VLVREQUEST: ::windows_sys::core::PCSTR = ::windows_sys::s!("2.16.840.1.113730.3.4.9"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONTROL_VLVREQUEST_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("2.16.840.1.113730.3.4.9"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONTROL_VLVRESPONSE: ::windows_sys::core::PCSTR = ::windows_sys::s!("2.16.840.1.113730.3.4.10"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONTROL_VLVRESPONSE_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("2.16.840.1.113730.3.4.10"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DELETE_CMD: i32 = 74i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DEREF_ALWAYS: u32 = 3u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DEREF_FINDING: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DEREF_NEVER: u32 = 0u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DEREF_SEARCHING: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DIRSYNC_ANCESTORS_FIRST_ORDER: u32 = 2048u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DIRSYNC_INCREMENTAL_VALUES: u32 = 2147483648u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DIRSYNC_OBJECT_SECURITY: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DIRSYNC_PUBLIC_DATA_ONLY: u32 = 8192u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DIRSYNC_ROPAS_DATA_ONLY: u32 = 1073741824u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_EXTENDED_CMD: i32 = 119i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FEATURE_INFO_VERSION: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_AND: u32 = 160u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_APPROX: u32 = 168u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_EQUALITY: u32 = 163u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_EXTENSIBLE: u32 = 169u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_GE: u32 = 165u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_LE: u32 = 166u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_NOT: u32 = 162u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_OR: u32 = 161u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_PRESENT: u32 = 135u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_SUBSTRINGS: u32 = 164u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_GC_PORT: u32 = 3268u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_INVALID_CMD: u32 = 255u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_INVALID_RES: u32 = 255u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MATCHING_RULE_BIT_AND: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.803"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MATCHING_RULE_BIT_AND_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.803"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MATCHING_RULE_BIT_OR: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.804"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MATCHING_RULE_BIT_OR_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.804"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MATCHING_RULE_DN_BINARY_COMPLEX: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2253"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MATCHING_RULE_DN_BINARY_COMPLEX_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2253"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MATCHING_RULE_TRANSITIVE_EVALUATION: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1941"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MATCHING_RULE_TRANSITIVE_EVALUATION_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1941"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MODIFY_CMD: i32 = 102i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MODRDN_CMD: i32 = 108i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MOD_ADD: u32 = 0u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MOD_BVALUES: u32 = 128u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MOD_DELETE: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MOD_REPLACE: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MSG_ALL: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MSG_ONE: u32 = 0u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MSG_RECEIVED: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NO_LIMIT: u32 = 0u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_ABANDON_REPL: ::windows_sys::core::PCSTR = ::windows_sys::s!("abandonReplication"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_ABANDON_REPL_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("abandonReplication"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_BECOME_DOM_MASTER: ::windows_sys::core::PCSTR = ::windows_sys::s!("becomeDomainMaster"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_BECOME_DOM_MASTER_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("becomeDomainMaster"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_BECOME_PDC: ::windows_sys::core::PCSTR = ::windows_sys::s!("becomePdc"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_BECOME_PDC_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("becomePdc"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_BECOME_RID_MASTER: ::windows_sys::core::PCSTR = ::windows_sys::s!("becomeRidMaster"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_BECOME_RID_MASTER_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("becomeRidMaster"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_BECOME_SCHEMA_MASTER: ::windows_sys::core::PCSTR = ::windows_sys::s!("becomeSchemaMaster"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_BECOME_SCHEMA_MASTER_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("becomeSchemaMaster"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_CONFIG_NAMING_CONTEXT: ::windows_sys::core::PCSTR = ::windows_sys::s!("configurationNamingContext"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_CONFIG_NAMING_CONTEXT_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("configurationNamingContext"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_CURRENT_TIME: ::windows_sys::core::PCSTR = ::windows_sys::s!("currentTime"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_CURRENT_TIME_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("currentTime"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_DEFAULT_NAMING_CONTEXT: ::windows_sys::core::PCSTR = ::windows_sys::s!("defaultNamingContext"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_DEFAULT_NAMING_CONTEXT_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("defaultNamingContext"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_DNS_HOST_NAME: ::windows_sys::core::PCSTR = ::windows_sys::s!("dnsHostName"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_DNS_HOST_NAME_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("dnsHostName"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_DO_GARBAGE_COLLECTION: ::windows_sys::core::PCSTR = ::windows_sys::s!("doGarbageCollection"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_DO_GARBAGE_COLLECTION_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("doGarbageCollection"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_DS_SERVICE_NAME: ::windows_sys::core::PCSTR = ::windows_sys::s!("dsServiceName"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_DS_SERVICE_NAME_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("dsServiceName"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_FIXUP_INHERITANCE: ::windows_sys::core::PCSTR = ::windows_sys::s!("fixupInheritance"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_FIXUP_INHERITANCE_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("fixupInheritance"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_HIGHEST_COMMITTED_USN: ::windows_sys::core::PCSTR = ::windows_sys::s!("highestCommitedUSN"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_HIGHEST_COMMITTED_USN_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("highestCommitedUSN"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_INVALIDATE_RID_POOL: ::windows_sys::core::PCSTR = ::windows_sys::s!("invalidateRidPool"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_INVALIDATE_RID_POOL_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("invalidateRidPool"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_LDAP_SERVICE_NAME: ::windows_sys::core::PCSTR = ::windows_sys::s!("ldapServiceName"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_LDAP_SERVICE_NAME_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("ldapServiceName"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_NAMING_CONTEXTS: ::windows_sys::core::PCSTR = ::windows_sys::s!("namingContexts"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_NAMING_CONTEXTS_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("namingContexts"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_RECALC_HIERARCHY: ::windows_sys::core::PCSTR = ::windows_sys::s!("recalcHierarchy"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_RECALC_HIERARCHY_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("recalcHierarchy"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_ROOT_DOMAIN_NAMING_CONTEXT: ::windows_sys::core::PCSTR = ::windows_sys::s!("rootDomainNamingContext"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_ROOT_DOMAIN_NAMING_CONTEXT_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("rootDomainNamingContext"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SCHEMA_NAMING_CONTEXT: ::windows_sys::core::PCSTR = ::windows_sys::s!("schemaNamingContext"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SCHEMA_NAMING_CONTEXT_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("schemaNamingContext"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SCHEMA_UPDATE_NOW: ::windows_sys::core::PCSTR = ::windows_sys::s!("schemaUpdateNow"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SCHEMA_UPDATE_NOW_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("schemaUpdateNow"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SERVER_NAME: ::windows_sys::core::PCSTR = ::windows_sys::s!("serverName"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SERVER_NAME_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("serverName"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUBSCHEMA_SUBENTRY: ::windows_sys::core::PCSTR = ::windows_sys::s!("subschemaSubentry"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUBSCHEMA_SUBENTRY_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("subschemaSubentry"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_CAPABILITIES: ::windows_sys::core::PCSTR = ::windows_sys::s!("supportedCapabilities"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_CAPABILITIES_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("supportedCapabilities"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_CONTROL: ::windows_sys::core::PCSTR = ::windows_sys::s!("supportedControl"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_CONTROL_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("supportedControl"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_LDAP_POLICIES: ::windows_sys::core::PCSTR = ::windows_sys::s!("supportedLDAPPolicies"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_LDAP_POLICIES_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("supportedLDAPPolicies"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_LDAP_VERSION: ::windows_sys::core::PCSTR = ::windows_sys::s!("supportedLDAPVersion"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_LDAP_VERSION_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("supportedLDAPVersion"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_SASL_MECHANISM: ::windows_sys::core::PCSTR = ::windows_sys::s!("supportedSASLMechanisms"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPATT_SUPPORTED_SASL_MECHANISM_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("supportedSASLMechanisms"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_API_FEATURE_INFO: u32 = 21u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_API_INFO: u32 = 0u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_AREC_EXCLUSIVE: u32 = 152u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_AUTO_RECONNECT: u32 = 145u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_CACHE_ENABLE: u32 = 15u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_CACHE_FN_PTRS: u32 = 13u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_CACHE_STRATEGY: u32 = 14u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_CHASE_REFERRALS: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_CLIENT_CERTIFICATE: u32 = 128u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_DEREF: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_DESC: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_DNS: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_DNSDOMAIN_NAME: u32 = 59u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_ENCRYPT: u32 = 150u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_ERROR_NUMBER: u32 = 49u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_ERROR_STRING: u32 = 50u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_FAST_CONCURRENT_BIND: u32 = 65u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_GETDSNAME_FLAGS: u32 = 61u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_HOST_NAME: u32 = 48u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_HOST_REACHABLE: u32 = 62u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_IO_FN_PTRS: u32 = 11u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_PING_KEEP_ALIVE: u32 = 54u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_PING_LIMIT: u32 = 56u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_PING_WAIT_TIME: u32 = 55u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_PROMPT_CREDENTIALS: u32 = 63u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_PROTOCOL_VERSION: u32 = 17u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_REBIND_ARG: u32 = 7u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_REBIND_FN: u32 = 6u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_REFERRALS: u32 = 8u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_REFERRAL_CALLBACK: u32 = 112u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_REFERRAL_HOP_LIMIT: u32 = 16u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_REF_DEREF_CONN_PER_MSG: u32 = 148u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_RESTART: u32 = 9u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_RETURN_REFS: u32 = 4u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_ROOTDSE_CACHE: u32 = 154u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SASL_METHOD: u32 = 151u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SCH_FLAGS: u32 = 67u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SECURITY_CONTEXT: u32 = 153u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SEND_TIMEOUT: u32 = 66u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SERVER_CERTIFICATE: u32 = 129u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SERVER_ERROR: u32 = 51u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SERVER_EXT_ERROR: u32 = 52u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SIGN: u32 = 149u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SIZELIMIT: u32 = 3u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SOCKET_BIND_ADDRESSES: u32 = 68u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SSL: u32 = 10u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SSL_INFO: u32 = 147u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_SSPI_FLAGS: u32 = 146u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_TCP_KEEPALIVE: u32 = 64u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_THREAD_FN_PTRS: u32 = 5u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_TIMELIMIT: u32 = 4u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_TLS: u32 = 10u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_TLS_INFO: u32 = 147u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPT_VERSION: u32 = 17u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_PAGED_RESULT_OID_STRING: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.319"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_PAGED_RESULT_OID_STRING_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.319"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_POLICYHINT_APPLY_FULLPWDPOLICY: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_PORT: u32 = 389u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_ADD: i32 = 105i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_ANY: i32 = -1i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_BIND: i32 = 97i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_COMPARE: i32 = 111i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_DELETE: i32 = 107i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_EXTENDED: i32 = 120i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_MODIFY: i32 = 103i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_MODRDN: i32 = 109i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_REFERRAL: i32 = 115i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_SEARCH_ENTRY: i32 = 100i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_SEARCH_RESULT: i32 = 101i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RES_SESSION: i32 = 114i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SCOPE_BASE: u32 = 0u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SCOPE_ONELEVEL: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SCOPE_SUBTREE: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SEARCH_CMD: i32 = 99i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SEARCH_HINT_INDEX_ONLY_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2207"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SEARCH_HINT_INDEX_ONLY_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2207"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SEARCH_HINT_REQUIRED_INDEX_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2306"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SEARCH_HINT_REQUIRED_INDEX_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2306"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SEARCH_HINT_SOFT_SIZE_LIMIT_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2210"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SEARCH_HINT_SOFT_SIZE_LIMIT_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2210"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_ASQ_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1504"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_ASQ_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1504"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_BATCH_REQUEST_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2212"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_BATCH_REQUEST_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2212"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_BYPASS_QUOTA_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2256"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_BYPASS_QUOTA_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2256"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.521"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.521"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DIRSYNC_EX_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2090"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DIRSYNC_EX_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2090"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DIRSYNC_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.841"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DIRSYNC_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.841"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DN_INPUT_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2026"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DN_INPUT_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2026"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DOMAIN_SCOPE_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1339"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DOMAIN_SCOPE_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1339"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_EXPECTED_ENTRY_COUNT_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2211"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_EXPECTED_ENTRY_COUNT_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2211"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_EXTENDED_DN_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.529"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_EXTENDED_DN_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.529"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_FAST_BIND_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1781"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_FAST_BIND_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1781"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_FORCE_UPDATE_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1974"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_FORCE_UPDATE_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1974"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_GET_STATS_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.970"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_GET_STATS_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.970"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_LAZY_COMMIT_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.619"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_LAZY_COMMIT_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.619"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_LINK_TTL_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2309"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_LINK_TTL_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2309"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_NOTIFICATION_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.528"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_NOTIFICATION_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.528"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_PERMISSIVE_MODIFY_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1413"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_PERMISSIVE_MODIFY_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1413"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_POLICY_HINTS_DEPRECATED_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2066"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_POLICY_HINTS_DEPRECATED_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2066"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_POLICY_HINTS_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2239"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_POLICY_HINTS_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2239"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_QUOTA_CONTROL_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1852"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_QUOTA_CONTROL_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1852"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_RANGE_OPTION_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.802"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_RANGE_OPTION_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.802"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_RANGE_RETRIEVAL_NOERR_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1948"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_RANGE_RETRIEVAL_NOERR_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1948"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_RESP_SORT_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.474"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_RESP_SORT_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.474"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SD_FLAGS_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.801"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SD_FLAGS_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.801"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SEARCH_HINTS_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2206"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SEARCH_HINTS_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2206"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SEARCH_OPTIONS_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1340"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SEARCH_OPTIONS_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1340"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SET_OWNER_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2255"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SET_OWNER_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2255"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SHOW_DEACTIVATED_LINK_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2065"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SHOW_DEACTIVATED_LINK_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2065"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SHOW_DELETED_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.417"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SHOW_DELETED_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.417"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SHOW_RECYCLED_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2064"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SHOW_RECYCLED_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2064"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SHUTDOWN_NOTIFY_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1907"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SHUTDOWN_NOTIFY_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1907"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SORT_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.473"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_SORT_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.473"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_TREE_DELETE_EX_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2204"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_TREE_DELETE_EX_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2204"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_TREE_DELETE_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.805"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_TREE_DELETE_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.805"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_UPDATE_STATS_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2205"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_UPDATE_STATS_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2205"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_VERIFY_NAME_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.1338"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_VERIFY_NAME_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.1338"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_WHO_AM_I_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.3.6.1.4.1.4203.1.11.3"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_WHO_AM_I_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.3.6.1.4.1.4203.1.11.3"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SESSION_CMD: i32 = 113i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SSL_GC_PORT: u32 = 3269u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SSL_PORT: u32 = 636u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_START_TLS_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.3.6.1.4.1.1466.20037"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_START_TLS_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.3.6.1.4.1.1466.20037"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SUBSTRING_ANY: i32 = 129i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SUBSTRING_FINAL: i32 = 130i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SUBSTRING_INITIAL: i32 = 128i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_TTL_EXTENDED_OP_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.3.6.1.4.1.1466.101.119.1"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_TTL_EXTENDED_OP_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.3.6.1.4.1.1466.101.119.1"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UNBIND_CMD: i32 = 66i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UNICODE: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UPDATE_STATS_INVOCATIONID_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2209"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UPDATE_STATS_INVOCATIONID_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2209"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UPDATE_STATS_USN_OID: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.2.840.113556.1.4.2208"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UPDATE_STATS_USN_OID_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("1.2.840.113556.1.4.2208"); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VENDOR_NAME: ::windows_sys::core::PCSTR = ::windows_sys::s!("Microsoft Corporation."); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VENDOR_NAME_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("Microsoft Corporation."); #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VENDOR_VERSION: u32 = 510u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VERSION: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VERSION1: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VERSION2: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VERSION3: u32 = 3u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VERSION_MAX: u32 = 3u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VERSION_MIN: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VLVINFO_VERSION: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const SERVER_SEARCH_FLAG_DOMAIN_SCOPE: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const SERVER_SEARCH_FLAG_PHANTOM_ROOT: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub type LDAP_RETCODE = i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SUCCESS: LDAP_RETCODE = 0i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OPERATIONS_ERROR: LDAP_RETCODE = 1i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_PROTOCOL_ERROR: LDAP_RETCODE = 2i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_TIMELIMIT_EXCEEDED: LDAP_RETCODE = 3i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SIZELIMIT_EXCEEDED: LDAP_RETCODE = 4i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_COMPARE_FALSE: LDAP_RETCODE = 5i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_COMPARE_TRUE: LDAP_RETCODE = 6i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_AUTH_METHOD_NOT_SUPPORTED: LDAP_RETCODE = 7i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_STRONG_AUTH_REQUIRED: LDAP_RETCODE = 8i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_REFERRAL_V2: LDAP_RETCODE = 9i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_PARTIAL_RESULTS: LDAP_RETCODE = 9i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_REFERRAL: LDAP_RETCODE = 10i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_ADMIN_LIMIT_EXCEEDED: LDAP_RETCODE = 11i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UNAVAILABLE_CRIT_EXTENSION: LDAP_RETCODE = 12i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONFIDENTIALITY_REQUIRED: LDAP_RETCODE = 13i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SASL_BIND_IN_PROGRESS: LDAP_RETCODE = 14i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NO_SUCH_ATTRIBUTE: LDAP_RETCODE = 16i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UNDEFINED_TYPE: LDAP_RETCODE = 17i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_INAPPROPRIATE_MATCHING: LDAP_RETCODE = 18i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONSTRAINT_VIOLATION: LDAP_RETCODE = 19i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_ATTRIBUTE_OR_VALUE_EXISTS: LDAP_RETCODE = 20i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_INVALID_SYNTAX: LDAP_RETCODE = 21i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NO_SUCH_OBJECT: LDAP_RETCODE = 32i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_ALIAS_PROBLEM: LDAP_RETCODE = 33i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_INVALID_DN_SYNTAX: LDAP_RETCODE = 34i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_IS_LEAF: LDAP_RETCODE = 35i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_ALIAS_DEREF_PROBLEM: LDAP_RETCODE = 36i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_INAPPROPRIATE_AUTH: LDAP_RETCODE = 48i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_INVALID_CREDENTIALS: LDAP_RETCODE = 49i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_INSUFFICIENT_RIGHTS: LDAP_RETCODE = 50i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_BUSY: LDAP_RETCODE = 51i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UNAVAILABLE: LDAP_RETCODE = 52i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_UNWILLING_TO_PERFORM: LDAP_RETCODE = 53i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_LOOP_DETECT: LDAP_RETCODE = 54i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SORT_CONTROL_MISSING: LDAP_RETCODE = 60i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OFFSET_RANGE_ERROR: LDAP_RETCODE = 61i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NAMING_VIOLATION: LDAP_RETCODE = 64i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OBJECT_CLASS_VIOLATION: LDAP_RETCODE = 65i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NOT_ALLOWED_ON_NONLEAF: LDAP_RETCODE = 66i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NOT_ALLOWED_ON_RDN: LDAP_RETCODE = 67i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_ALREADY_EXISTS: LDAP_RETCODE = 68i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NO_OBJECT_CLASS_MODS: LDAP_RETCODE = 69i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_RESULTS_TOO_LARGE: LDAP_RETCODE = 70i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_AFFECTS_MULTIPLE_DSAS: LDAP_RETCODE = 71i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_VIRTUAL_LIST_VIEW_ERROR: LDAP_RETCODE = 76i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_OTHER: LDAP_RETCODE = 80i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_SERVER_DOWN: LDAP_RETCODE = 81i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_LOCAL_ERROR: LDAP_RETCODE = 82i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_ENCODING_ERROR: LDAP_RETCODE = 83i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_DECODING_ERROR: LDAP_RETCODE = 84i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_TIMEOUT: LDAP_RETCODE = 85i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_AUTH_UNKNOWN: LDAP_RETCODE = 86i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_FILTER_ERROR: LDAP_RETCODE = 87i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_USER_CANCELLED: LDAP_RETCODE = 88i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_PARAM_ERROR: LDAP_RETCODE = 89i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NO_MEMORY: LDAP_RETCODE = 90i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONNECT_ERROR: LDAP_RETCODE = 91i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NOT_SUPPORTED: LDAP_RETCODE = 92i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_NO_RESULTS_RETURNED: LDAP_RETCODE = 94i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CONTROL_NOT_FOUND: LDAP_RETCODE = 93i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_MORE_RESULTS_TO_RETURN: LDAP_RETCODE = 95i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_CLIENT_LOOP: LDAP_RETCODE = 96i32; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub const LDAP_REFERRAL_LIMIT_EXCEEDED: LDAP_RETCODE = 97i32; #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct BerElement { pub opaque: ::windows_sys::core::PSTR, } impl ::core::marker::Copy for BerElement {} impl ::core::clone::Clone for BerElement { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAP { pub ld_sb: LDAP_0, pub ld_host: ::windows_sys::core::PSTR, pub ld_version: u32, pub ld_lberoptions: u8, pub ld_deref: u32, pub ld_timelimit: u32, pub ld_sizelimit: u32, pub ld_errno: u32, pub ld_matched: ::windows_sys::core::PSTR, pub ld_error: ::windows_sys::core::PSTR, pub ld_msgid: u32, pub Reserved3: [u8; 25], pub ld_cldaptries: u32, pub ld_cldaptimeout: u32, pub ld_refhoplimit: u32, pub ld_options: u32, } impl ::core::marker::Copy for LDAP {} impl ::core::clone::Clone for LDAP { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAP_0 { pub sb_sd: usize, pub Reserved1: [u8; 41], pub sb_naddr: usize, pub Reserved2: [u8; 24], } impl ::core::marker::Copy for LDAP_0 {} impl ::core::clone::Clone for LDAP_0 { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAPAPIFeatureInfoA { pub ldapaif_info_version: i32, pub ldapaif_name: ::windows_sys::core::PSTR, pub ldapaif_version: i32, } impl ::core::marker::Copy for LDAPAPIFeatureInfoA {} impl ::core::clone::Clone for LDAPAPIFeatureInfoA { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAPAPIFeatureInfoW { pub ldapaif_info_version: i32, pub ldapaif_name: ::windows_sys::core::PWSTR, pub ldapaif_version: i32, } impl ::core::marker::Copy for LDAPAPIFeatureInfoW {} impl ::core::clone::Clone for LDAPAPIFeatureInfoW { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAPAPIInfoA { pub ldapai_info_version: i32, pub ldapai_api_version: i32, pub ldapai_protocol_version: i32, pub ldapai_extensions: *mut *mut i8, pub ldapai_vendor_name: ::windows_sys::core::PSTR, pub ldapai_vendor_version: i32, } impl ::core::marker::Copy for LDAPAPIInfoA {} impl ::core::clone::Clone for LDAPAPIInfoA { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAPAPIInfoW { pub ldapai_info_version: i32, pub ldapai_api_version: i32, pub ldapai_protocol_version: i32, pub ldapai_extensions: *mut ::windows_sys::core::PWSTR, pub ldapai_vendor_name: ::windows_sys::core::PWSTR, pub ldapai_vendor_version: i32, } impl ::core::marker::Copy for LDAPAPIInfoW {} impl ::core::clone::Clone for LDAPAPIInfoW { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct LDAPControlA { pub ldctl_oid: ::windows_sys::core::PSTR, pub ldctl_value: LDAP_BERVAL, pub ldctl_iscritical: super::super::Foundation::BOOLEAN, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for LDAPControlA {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for LDAPControlA { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct LDAPControlW { pub ldctl_oid: ::windows_sys::core::PWSTR, pub ldctl_value: LDAP_BERVAL, pub ldctl_iscritical: super::super::Foundation::BOOLEAN, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for LDAPControlW {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for LDAPControlW { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct LDAPMessage { pub lm_msgid: u32, pub lm_msgtype: u32, pub lm_ber: *mut ::core::ffi::c_void, pub lm_chain: *mut LDAPMessage, pub lm_next: *mut LDAPMessage, pub lm_time: u32, pub Connection: *mut LDAP, pub Request: *mut ::core::ffi::c_void, pub lm_returncode: u32, pub lm_referral: u16, pub lm_chased: super::super::Foundation::BOOLEAN, pub lm_eom: super::super::Foundation::BOOLEAN, pub ConnectionReferenced: super::super::Foundation::BOOLEAN, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for LDAPMessage {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for LDAPMessage { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAPModA { pub mod_op: u32, pub mod_type: ::windows_sys::core::PSTR, pub mod_vals: LDAPModA_0, } impl ::core::marker::Copy for LDAPModA {} impl ::core::clone::Clone for LDAPModA { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub union LDAPModA_0 { pub modv_strvals: *mut ::windows_sys::core::PSTR, pub modv_bvals: *mut *mut LDAP_BERVAL, } impl ::core::marker::Copy for LDAPModA_0 {} impl ::core::clone::Clone for LDAPModA_0 { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAPModW { pub mod_op: u32, pub mod_type: ::windows_sys::core::PWSTR, pub mod_vals: LDAPModW_0, } impl ::core::marker::Copy for LDAPModW {} impl ::core::clone::Clone for LDAPModW { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub union LDAPModW_0 { pub modv_strvals: *mut ::windows_sys::core::PWSTR, pub modv_bvals: *mut *mut LDAP_BERVAL, } impl ::core::marker::Copy for LDAPModW_0 {} impl ::core::clone::Clone for LDAPModW_0 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct LDAPSearch(pub u8); #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct LDAPSortKeyA { pub sk_attrtype: ::windows_sys::core::PSTR, pub sk_matchruleoid: ::windows_sys::core::PSTR, pub sk_reverseorder: super::super::Foundation::BOOLEAN, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for LDAPSortKeyA {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for LDAPSortKeyA { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct LDAPSortKeyW { pub sk_attrtype: ::windows_sys::core::PWSTR, pub sk_matchruleoid: ::windows_sys::core::PWSTR, pub sk_reverseorder: super::super::Foundation::BOOLEAN, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for LDAPSortKeyW {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for LDAPSortKeyW { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAPVLVInfo { pub ldvlv_version: i32, pub ldvlv_before_count: u32, pub ldvlv_after_count: u32, pub ldvlv_offset: u32, pub ldvlv_count: u32, pub ldvlv_attrvalue: *mut LDAP_BERVAL, pub ldvlv_context: *mut LDAP_BERVAL, pub ldvlv_extradata: *mut ::core::ffi::c_void, } impl ::core::marker::Copy for LDAPVLVInfo {} impl ::core::clone::Clone for LDAPVLVInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAP_BERVAL { pub bv_len: u32, pub bv_val: ::windows_sys::core::PSTR, } impl ::core::marker::Copy for LDAP_BERVAL {} impl ::core::clone::Clone for LDAP_BERVAL { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct LDAP_REFERRAL_CALLBACK { pub SizeOfCallbacks: u32, pub QueryForConnection: QUERYFORCONNECTION, pub NotifyRoutine: NOTIFYOFNEWCONNECTION, pub DereferenceRoutine: DEREFERENCECONNECTION, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for LDAP_REFERRAL_CALLBACK {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for LDAP_REFERRAL_CALLBACK { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAP_TIMEVAL { pub tv_sec: i32, pub tv_usec: i32, } impl ::core::marker::Copy for LDAP_TIMEVAL {} impl ::core::clone::Clone for LDAP_TIMEVAL { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub struct LDAP_VERSION_INFO { pub lv_size: u32, pub lv_major: u32, pub lv_minor: u32, } impl ::core::marker::Copy for LDAP_VERSION_INFO {} impl ::core::clone::Clone for LDAP_VERSION_INFO { fn clone(&self) -> Self { *self } } #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub type DBGPRINT = ::core::option::Option<unsafe extern "system" fn(format: ::windows_sys::core::PCSTR) -> u32>; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub type DEREFERENCECONNECTION = ::core::option::Option<unsafe extern "system" fn(primaryconnection: *mut LDAP, connectiontodereference: *mut LDAP) -> u32>; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub type NOTIFYOFNEWCONNECTION = ::core::option::Option<unsafe extern "system" fn(primaryconnection: *mut LDAP, referralfromconnection: *mut LDAP, newdn: ::windows_sys::core::PCWSTR, hostname: ::windows_sys::core::PCSTR, newconnection: *mut LDAP, portnumber: u32, secauthidentity: *mut ::core::ffi::c_void, currentuser: *mut ::core::ffi::c_void, errorcodefrombind: u32) -> super::super::Foundation::BOOLEAN>; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Authentication_Identity\"`, `\"Win32_Security_Cryptography\"`*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Authentication_Identity", feature = "Win32_Security_Cryptography"))] pub type QUERYCLIENTCERT = ::core::option::Option<unsafe extern "system" fn(connection: *mut LDAP, trusted_cas: *mut super::super::Security::Authentication::Identity::SecPkgContext_IssuerListInfoEx, ppcertificate: *mut *mut super::super::Security::Cryptography::CERT_CONTEXT) -> super::super::Foundation::BOOLEAN>; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] pub type QUERYFORCONNECTION = ::core::option::Option<unsafe extern "system" fn(primaryconnection: *mut LDAP, referralfromconnection: *mut LDAP, newdn: ::windows_sys::core::PCWSTR, hostname: ::windows_sys::core::PCSTR, portnumber: u32, secauthidentity: *mut ::core::ffi::c_void, currentusertoken: *mut ::core::ffi::c_void, connectiontouse: *mut *mut LDAP) -> u32>; #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography\"`*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography"))] pub type VERIFYSERVERCERT = ::core::option::Option<unsafe extern "system" fn(connection: *mut LDAP, pservercert: *mut *mut super::super::Security::Cryptography::CERT_CONTEXT) -> super::super::Foundation::BOOLEAN>;
use std::mem; use futures::{Future, IntoFuture, Poll}; pub(crate) trait Started: Future { fn started(&self) -> bool; } pub(crate) fn lazy<F, R>(func: F) -> Lazy<F, R> where F: FnOnce() -> R, R: IntoFuture, { Lazy { inner: Inner::Init(func), } } // FIXME: allow() required due to `impl Trait` leaking types to this lint #[allow(missing_debug_implementations)] pub(crate) struct Lazy<F, R: IntoFuture> { inner: Inner<F, R::Future> } enum Inner<F, R> { Init(F), Fut(R), Empty, } impl<F, R> Started for Lazy<F, R> where F: FnOnce() -> R, R: IntoFuture, { fn started(&self) -> bool { match self.inner { Inner::Init(_) => false, Inner::Fut(_) | Inner::Empty => true, } } } impl<F, R> Future for Lazy<F, R> where F: FnOnce() -> R, R: IntoFuture, { type Item = R::Item; type Error = R::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.inner { Inner::Fut(ref mut f) => return f.poll(), _ => (), } match mem::replace(&mut self.inner, Inner::Empty) { Inner::Init(func) => { let mut fut = func().into_future(); let ret = fut.poll(); self.inner = Inner::Fut(fut); ret }, _ => unreachable!("lazy state wrong"), } } }
use proconio::{input, marker::Bytes}; fn main() { input! { s: Bytes, n: u64, }; let mut k = 0; for i in 0..s.len() { if s[i] == b'1' { k += 1 << (s.len() - i - 1); } } if k > n { println!("-1"); return; } for i in 0..s.len() { if s[i] == b'?' { let a = 1 << (s.len() - i - 1); if k + a <= n { k += a; } } } println!("{}", k); }
#[doc = "Reader of register AHB3SMENR"] pub type R = crate::R<u32, super::AHB3SMENR>; #[doc = "Writer for register AHB3SMENR"] pub type W = crate::W<u32, super::AHB3SMENR>; #[doc = "Register AHB3SMENR `reset()`'s with value 0x0101"] impl crate::ResetValue for super::AHB3SMENR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0101 } } #[doc = "Reader of field `FMCSMEN`"] pub type FMCSMEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FMCSMEN`"] pub struct FMCSMEN_W<'a> { w: &'a mut W, } impl<'a> FMCSMEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `OSPI1SMEN`"] pub type OSPI1SMEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OSPI1SMEN`"] pub struct OSPI1SMEN_W<'a> { w: &'a mut W, } impl<'a> OSPI1SMEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } impl R { #[doc = "Bit 0 - Flexible memory controller clocks enable during Sleep and Stop modes"] #[inline(always)] pub fn fmcsmen(&self) -> FMCSMEN_R { FMCSMEN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 8 - OSPI1SMEN"] #[inline(always)] pub fn ospi1smen(&self) -> OSPI1SMEN_R { OSPI1SMEN_R::new(((self.bits >> 8) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Flexible memory controller clocks enable during Sleep and Stop modes"] #[inline(always)] pub fn fmcsmen(&mut self) -> FMCSMEN_W { FMCSMEN_W { w: self } } #[doc = "Bit 8 - OSPI1SMEN"] #[inline(always)] pub fn ospi1smen(&mut self) -> OSPI1SMEN_W { OSPI1SMEN_W { w: self } } }
use std::u8; use std::io::{Read, Write}; const DATA_SIZE: usize = 30000; /// A virtual machine to run a program. pub struct VM<I: Read, O: Write> { prog: Vec<u8>, iptr: usize, dptr: usize, data: [u8; DATA_SIZE], input: I, output: O, } /// An action to be taken by the virtual machine after an instruction enum VMAction { EOF, Error(&'static str), JumpForward, JumpBackward, Ok, } /// The result of running the machine pub enum VMResult { Error(&'static str), Ok } impl <I: Read, O: Write> VM<I, O> { /// Create a new virtual machine for a program. pub fn new(prog: Vec<u8>, input: I, output: O) -> Self { VM { prog: prog, iptr: 0, dptr: 0, data: [0; DATA_SIZE], input: input, output: output, } } /// Run the virtual machine. pub fn run(&mut self) -> VMResult { loop { match self.step() { VMAction::Ok => { self.iptr += 1; } VMAction::JumpForward => { self.iptr += 1; let mut count = 1; while count > 0 { match self.prog.get(self.iptr) { Some(byte) => { match byte.clone() as char { ']' => count -= 1, '[' => count += 1, _ => {} } } None => return VMResult::Error("No matching ]"), } self.iptr += 1; } } VMAction::JumpBackward => { let mut count = 1; while count > 0 { if self.iptr > 0 { self.iptr -= 1; } else { return VMResult::Error("No matching [") } match self.prog.get(self.iptr) { Some(byte) => { match byte.clone() as char { ']' => count += 1, '[' => count -= 1, _ => {} } } None => return VMResult::Error("No matching ["), } } self.iptr += 1; } VMAction::Error(e) => return VMResult::Error(e), VMAction::EOF => break, } } VMResult::Ok } /// Process the next instruction in the program (as defined by the /// instruction pointer), returning the next action to be taken by the VM. fn step(&mut self) -> VMAction { if self.iptr >= self.prog.len() { return VMAction::EOF; } if let Some(byte) = self.prog.get(self.iptr) { match byte.clone() as char { '>' => { if self.dptr < DATA_SIZE - 1 { self.dptr += 1; VMAction::Ok } else { VMAction::Error("Data pointer moved out of bounds") } } '<' => { if self.dptr > 0 { self.dptr -= 1; VMAction::Ok } else { VMAction::Error("Data pointer < 0") } } '+' => { if self.data[self.dptr] < u8::MAX { self.data[self.dptr] += 1; VMAction::Ok } else { VMAction::Error("Data overflow") } } '-' => { if self.data[self.dptr] > 0 { self.data[self.dptr] -= 1; VMAction::Ok } else { VMAction::Error("Data underflow") } } '.' => { let mut buf = [0; 1]; buf[0] = self.data[self.dptr]; if let Ok(_) = self.output.write(&buf) { VMAction::Ok } else { VMAction::Error("Unable to write output") } } ',' => { let mut buf = [0; 1]; if let Ok(()) = self.input.read_exact(&mut buf) { self.data[self.dptr] = buf[0]; VMAction::Ok } else { VMAction::Error("Unable to read input") } } '[' => { if self.data[self.dptr] == 0 { VMAction::JumpForward } else { VMAction::Ok } } ']' => { if self.data[self.dptr] != 0 { VMAction::JumpBackward } else { VMAction::Ok } } _ => VMAction::Ok, } } else { VMAction::Error("Invalid instruction pointer") } } }
use serde::Deserialize; use gotham_derive::{StateData, StaticResponseExtender}; #[derive(Deserialize, StateData, StaticResponseExtender)] pub struct PathExtractor { pub key: String, }
mod links; mod config; mod layers; use self::links::Links; use self::config::Config; use self::layers::Layers; pub struct Network { links: Links, layers: Layers, config: Config } impl Network { pub fn new(network_struct: &Vec<u32>, learning_rate: f32, iterations_count: u32) -> Network { let config = Config::new(learning_rate, iterations_count); let mut layers = Layers::new(); let mut links = Links::new(); for (layer_num, layer_size) in network_struct.iter().enumerate() { layers.add_empty_layer(layer_size); if layer_num != 0 { links.add_layer(layers.get_unlinked_layers()); } } Network { links, layers, config } } pub fn predict(&self, input_data_set: &Vec<f32>) -> Vec<f32> { self.layers.set_input_layer(input_data_set); for neuron_layer_num in (0..self.layers.last_layer_num()).rev() { self.links.add_layer_data(neuron_layer_num); self.layers.sigmoid_layer(neuron_layer_num); } self.layers.get_output() } pub fn train(&self, data_sets: &Vec<(Vec<f32>, Vec<f32>)>) { for _ in 0..self.config.iterations_count { for &(ref input_data_set, ref expected_data_set) in data_sets.iter() { self.predict(input_data_set); self.fix_weights(expected_data_set); } } } fn fix_weights(&self, expected_data_set: &Vec<f32>) { self.layers.set_output_layer(expected_data_set); for neuron_layer_num in 0..self.layers.last_layer_num() { self.layers.count_weight_delta(neuron_layer_num); self.links.change_weights(neuron_layer_num, self.config.learning_rate); } } }
#[derive(Clone, PartialEq, Debug)] pub enum Token<'input> { // keywords As, Library, Using, Bits, Const, Enum, Protocol, Service, Strict, Struct, Flexible, Table, Union, XUnion, Error, Reserved, Compose, Identifier(&'input str), // literals StringLiteral(String), // the u64 stores the bits of the integer, and the bool stores whether the // literal had a leading "-" sign. fidlc just lexes these as a string and // then parses and validates at the same time; for now we parse the number // while lexing since we're already working with the invidual chars. IntLiteral(u64, bool), FloatLiteral(f64), DocComment(String), True, False, // symbols LCurly, LSquare, LParen, LAngle, RCurly, RSquare, RParen, RAngle, Dot, Comma, Semi, Colon, Question, Equal, Ampersand, Arrow, Pipe, EOF, }
//! `RawDir` and `RawDirEntry`. use core::fmt; use core::mem::{align_of, MaybeUninit}; use linux_raw_sys::general::linux_dirent64; use crate::backend::fs::syscalls::getdents_uninit; use crate::fd::AsFd; use crate::ffi::CStr; use crate::fs::FileType; use crate::io; /// A directory iterator implemented with getdents. /// /// Note: This implementation does not handle growing the buffer. If this /// functionality is necessary, you'll need to drop the current iterator, /// resize the buffer, and then re-create the iterator. The iterator is /// guaranteed to continue where it left off provided the file descriptor isn't /// changed. See the example in [`RawDir::new`]. pub struct RawDir<'buf, Fd: AsFd> { fd: Fd, buf: &'buf mut [MaybeUninit<u8>], initialized: usize, offset: usize, } impl<'buf, Fd: AsFd> RawDir<'buf, Fd> { /// Create a new iterator from the given file descriptor and buffer. /// /// Note: the buffer size may be trimmed to accommodate alignment /// requirements. /// /// # Examples /// /// ## Simple but non-portable /// /// These examples are non-portable, because file systems may not have a /// maximum file name length. If you can make assumptions that bound /// this length, then these examples may suffice. /// /// Using the heap: /// /// ``` /// # use std::mem::MaybeUninit; /// # use rustix::fs::{CWD, Mode, OFlags, openat, RawDir}; /// /// let fd = openat( /// CWD, /// ".", /// OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, /// Mode::empty(), /// ) /// .unwrap(); /// /// let mut buf = Vec::with_capacity(8192); /// let mut iter = RawDir::new(fd, buf.spare_capacity_mut()); /// while let Some(entry) = iter.next() { /// let entry = entry.unwrap(); /// dbg!(&entry); /// } /// ``` /// /// Using the stack: /// /// ``` /// # use std::mem::MaybeUninit; /// # use rustix::fs::{CWD, Mode, OFlags, openat, RawDir}; /// /// let fd = openat( /// CWD, /// ".", /// OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, /// Mode::empty(), /// ) /// .unwrap(); /// /// let mut buf = [MaybeUninit::uninit(); 2048]; /// let mut iter = RawDir::new(fd, &mut buf); /// while let Some(entry) = iter.next() { /// let entry = entry.unwrap(); /// dbg!(&entry); /// } /// ``` /// /// ## Portable /// /// Heap allocated growing buffer for supporting directory entries with /// arbitrarily large file names: /// /// ```notrust /// # // The `notrust` above can be removed when we can depend on Rust 1.65. /// # use std::mem::MaybeUninit; /// # use rustix::fs::{CWD, Mode, OFlags, openat, RawDir}; /// # use rustix::io::Errno; /// /// let fd = openat( /// CWD, /// ".", /// OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, /// Mode::empty(), /// ) /// .unwrap(); /// /// let mut buf = Vec::with_capacity(8192); /// 'read: loop { /// 'resize: { /// let mut iter = RawDir::new(&fd, buf.spare_capacity_mut()); /// while let Some(entry) = iter.next() { /// let entry = match entry { /// Err(Errno::INVAL) => break 'resize, /// r => r.unwrap(), /// }; /// dbg!(&entry); /// } /// break 'read; /// } /// /// let new_capacity = buf.capacity() * 2; /// buf.reserve(new_capacity); /// } /// ``` pub fn new(fd: Fd, buf: &'buf mut [MaybeUninit<u8>]) -> Self { Self { fd, buf: { let offset = buf.as_ptr().align_offset(align_of::<linux_dirent64>()); if offset < buf.len() { &mut buf[offset..] } else { &mut [] } }, initialized: 0, offset: 0, } } } /// A raw directory entry, similar to [`std::fs::DirEntry`]. /// /// Unlike the std version, this may represent the `.` or `..` entries. pub struct RawDirEntry<'a> { file_name: &'a CStr, file_type: u8, inode_number: u64, next_entry_cookie: i64, } impl<'a> fmt::Debug for RawDirEntry<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut f = f.debug_struct("RawDirEntry"); f.field("file_name", &self.file_name()); f.field("file_type", &self.file_type()); f.field("ino", &self.ino()); f.field("next_entry_cookie", &self.next_entry_cookie()); f.finish() } } impl<'a> RawDirEntry<'a> { /// Returns the file name of this directory entry. #[inline] pub fn file_name(&self) -> &CStr { self.file_name } /// Returns the type of this directory entry. #[inline] pub fn file_type(&self) -> FileType { FileType::from_dirent_d_type(self.file_type) } /// Returns the inode number of this directory entry. #[inline] #[doc(alias = "inode_number")] pub fn ino(&self) -> u64 { self.inode_number } /// Returns the seek cookie to the next directory entry. #[inline] #[doc(alias = "off")] pub fn next_entry_cookie(&self) -> u64 { self.next_entry_cookie as u64 } } impl<'buf, Fd: AsFd> RawDir<'buf, Fd> { /// Identical to [`Iterator::next`] except that [`Iterator::Item`] borrows /// from self. /// /// Note: this interface will be broken to implement a stdlib iterator API /// with GAT support once one becomes available. #[allow(unsafe_code)] #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Option<io::Result<RawDirEntry>> { if self.is_buffer_empty() { match getdents_uninit(self.fd.as_fd(), self.buf) { Ok(bytes_read) if bytes_read == 0 => return None, Ok(bytes_read) => { self.initialized = bytes_read; self.offset = 0; } Err(e) => return Some(Err(e)), } } let dirent_ptr = self.buf[self.offset..].as_ptr(); // SAFETY: // - This data is initialized by the check above. // - Assumption: the kernel will not give us partial structs. // - Assumption: the kernel uses proper alignment between structs. // - The starting pointer is aligned (performed in RawDir::new) let dirent = unsafe { &*dirent_ptr.cast::<linux_dirent64>() }; self.offset += usize::from(dirent.d_reclen); Some(Ok(RawDirEntry { file_type: dirent.d_type, inode_number: dirent.d_ino.into(), next_entry_cookie: dirent.d_off.into(), // SAFETY: The kernel guarantees a NUL-terminated string. file_name: unsafe { CStr::from_ptr(dirent.d_name.as_ptr().cast()) }, })) } /// Returns true if the internal buffer is empty and will be refilled when /// calling [`next`]. /// /// [`next`]: Self::next pub fn is_buffer_empty(&self) -> bool { self.offset >= self.initialized } }
#![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_parens)] use num::complex::Complex; use std::ops::{Mul}; use eventual::*; pub fn mandelbrot_point(x: f64, y: f64, iterations: u32) -> u8 { let c = Complex::new(x, y); let mut z = Complex::new(0.0, 0.0); for i in 0..iterations { z = z.mul(z) + c; if z.norm_sqr() >= 4.0 { return (i % 255) as u8; } } 0 } pub fn simple_mandelbrot_scene(iterations: u32, res: u32) -> Vec<u8> { let mut fractal: Vec<u8> = Vec::with_capacity((res * res) as usize); // Adapt our points in a scene resolution (pixels) to points in the domain (complex numbers as f64) for i in 0..res { for j in 0..res { let x = (j as f64 - (res as f64 / 2.0)) / (res as f64 / 4.0); let y = (i as f64 - (res as f64 / 2.0)) / (res as f64 / 4.0); fractal.push(mandelbrot_point(x, y, iterations)); } } fractal } pub fn mandelbrot_scene(iterations: u32, res: u32, threads: u32, center_x: f64, center_y: f64, zoom: f64) -> Vec<u8> { // This is the scene that will be returned // Partial computations results will be added orderly to this vector let mut scene: Vec<u8> = Vec::with_capacity((res * res) as usize); let mut thread_pool = Vec::new(); for process in 0..threads { let future = Future::spawn(move || { let mut fractal: Vec<u8> = match (process % threads) { 0 => Vec::with_capacity((res + res % threads) as usize), _ => Vec::with_capacity(res as usize), }; // Partition of rows in thread_pool // init_range and end_range define a portion to be processed // Pattern matching used for last process should it need to accomodate extra rows let init_range = process * res / threads; let end_range = match (process % threads) { 0 => init_range + res / threads + res % threads, _ => init_range + res / threads, }; for i in init_range..end_range { for j in 0..res { let x = center_x + ((j as f64 - (res as f64 / 2.0)) / (res as f64 / 4.0) / zoom); let y = center_y - ((i as f64 - (res as f64 / 2.0)) / (res as f64 / 4.0) / zoom); fractal.push(mandelbrot_point(x, y, iterations)); } } println!("Thread {} returning", process); fractal }); thread_pool.push(future); } // Recover the results orderly and append them to the scene array // 'thread_pool' has moved into the iterator 'it', so 'thread_pool' cannot be used again (into_iter iterates over T). // The iterator elements are consumed orderly in this loop, appending portions to the final scene. let mut it = thread_pool.into_iter(); loop { match it.next() { Some(future) => { let mut res: Vec<u8> = future.and_then(|v| { Ok(v) }).await().unwrap(); scene.append(&mut res); //println!("Process result appended"); }, None => break, } } scene } #[cfg(test)] mod tests { use super::*; #[test] fn inner_figure() { assert_eq!(mandelbrot_point(0.0, 0.0, 100), 0); } #[test] fn value_in_domain() { assert!(mandelbrot_point(1.5, 0.0, 100) > 0); } #[test] fn out_of_domain() { assert_eq!(mandelbrot_point(2.4, 2.4, 100), 0); } #[test] fn simple_scene_results() { let scene = simple_mandelbrot_scene(100, 100); assert_eq!(scene[0], 0); assert_eq!(scene[9999], 0); assert!(scene[3150] > 0); } #[test] fn scene_results() { let scene = mandelbrot_scene(100, 100, 1, 0.0, 0.0, 1.0); assert_eq!(scene[0], 0); assert_eq!(scene[9999], 0); assert!(scene[3150] > 0); } }
use std::error::Error; use std::fmt; use std::io; pub fn advanced_types() { type_alias_demo(); never_type_demo(); sized_demo(); } /// 类型别名用来创建类型同义词 type alias fn type_alias_demo() { type Kilometers = i32; let x: i32 = 3; let y: Kilometers = 4; assert_eq!(7, x + y); let f: Box<Fn() + Send + 'static> = Box::new(|| println!("hi")); let f1: Thunk = Box::new(|| println!("type alias")); } fn take_long_type(f: Box<Fn() + Send + 'static>) {} fn return_long_type() -> Box<Fn() + Send + 'static> { Box::new(|| println!("hi")) } type Thunk = Box<Fn() + Send + 'static>; fn take_type(f: Thunk) {} fn return_type() -> Thunk { Box::new(|| println!("type alias")) } /// 从不返回的 !,never type fn never_type_demo() { // bar(); println!("forever"); loop { println!("and ever"); break; } } //fn bar() -> ! { //} /// 动态大小类型和 Sized trait fn sized_demo() { // doesn't have a size known at compile-time // let s1: str = "hi"; // let s1: str = "hello"; let s1: &str = "hi"; let s1: &str = "hello"; } fn generic<T>(t: T) {} fn generic_default<T: Sized>(t: T) {} fn generic_unknown_sized<T: ?Sized>(t: &T) {}
use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::io::{Error as IOError}; use std::iter; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; use itertools::kmerge; use itertools::Itertools; use regex::Regex; use record_file::RecordFile; use sstable::SSTable; use record::Record; const WAL_HEADER: &[u8; 8] = b"WAL!\x01\x00\x00\x00"; // constants for now const DEFAULT_MEM_COUNT: usize = 100_000; const DEFAULT_GROUP_COUNT: u32 = 10_000; const DEFAULT_FILE_COUNT: usize = 6; const DEFAULT_BUFFER_SIZE: usize = 4096; const DEFAULT_CACHE_SIZE: usize = 100_000; #[derive(Debug, Clone)] pub struct KVSOptions { max_mem_count: usize, group_count: u32, file_count: usize, rec_file_buffer_size: usize, rec_file_cache_size: usize, db_dir: PathBuf } impl KVSOptions { /// Creates a new `KVSOptions` struct with the only required parameter /// /// See each of the methods of associated defaults. /// # Examples /// ``` /// let kvs = KVSOptions::new("/tmp/kvs").create().unwrap(); /// ``` pub fn new(db_dir: &PathBuf) -> KVSOptions { KVSOptions { max_mem_count: DEFAULT_MEM_COUNT, group_count: DEFAULT_GROUP_COUNT, file_count: DEFAULT_FILE_COUNT, rec_file_buffer_size: DEFAULT_BUFFER_SIZE, rec_file_cache_size: DEFAULT_CACHE_SIZE, db_dir: db_dir.to_path_buf() } } /// Sets the max number of items that will be kept in memory before persisting to disk. /// /// Generally you want this size to be as large as possible without taking up too much memory. /// It all depends upon the size the keys and values. The memory used per entry is: /// `size_of(key) * 2 + size_of(value)` /// /// Default: 100,000 pub fn mem_count(&mut self, count: usize) -> &mut KVSOptions { self.max_mem_count = count; self } /// Sets the number of records that are grouped together in the data files. /// /// The number of `u64` records kept in memory per data file equals: `num_records / group_count` /// /// Default: 10,000 pub fn group_count(&mut self, count: u32) -> &mut KVSOptions { self.group_count = count; self } /// The number of files to keep in the database directory. /// /// More files means faster searches, but slower writes. /// Fewer files mean faster writes, but slower reads. /// /// Default: 6 pub fn file_count(&mut self, count: usize) -> &mut KVSOptions { self.file_count = count; self } /// The size of the buffer used for writing. /// /// It's best to keep this size a multiple of a page (4096 on most systems) /// /// Default: 4096 pub fn file_buffer(&mut self, size: usize) -> &mut KVSOptions { self.rec_file_buffer_size = size; self } /// The size of the record cache. /// /// Key/value pairs, and other internal records are kepts in an in-memory cache. This sets /// the number of items kept in the cache. The memory usage will be approximately: /// size_of(key) + size_of(value) + 16 * this value /// /// Default: 100,000 pub fn cache_size(&mut self, count: usize) -> &mut KVSOptions { self.rec_file_cache_size = count; self } /// Creates a `KVS` instance using the configured options. /// /// **This should only be called when creating a new `KVS` instance, not opening an existing one.** /// To open an existing KVS directory/database, use the `KVS::open` function. /// /// # Examples /// ``` /// let kvs = KVSOptions::new("/tmp/kvs").create().unwrap(); /// ``` /// # Panics /// If any of the options are nonsensical. pub fn create(self) -> Result<KVS, IOError> { if self.max_mem_count < 2 { panic!("mem_count must be greater than 1: {}", self.max_mem_count); } if self.group_count < 100 { panic!("group_count is too small, make > 100: {}", self.group_count); } if self.file_count < 2 { panic!("file_count is too small, try > 2: {}", self.file_count); } if self.rec_file_buffer_size < 4096 { panic!("file_buffer is too small, try > 4096: {}", self.rec_file_buffer_size); } if self.rec_file_cache_size < 1 { panic!("cache_size must be greater than 1: {}", self.rec_file_cache_size); } KVS::new(self) } } pub struct KVS { options: KVSOptions, cur_sstable_num: u64, wal_file: RecordFile, mem_table: BTreeMap<Vec<u8>, Record>, cur_sstable: SSTable, sstables: BTreeSet<SSTable>, } /// Gets the timestamp/epoch in ms pub fn get_timestamp() -> u64 { let ts = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards"); return ts.as_secs() * 1000 + ts.subsec_nanos() as u64 / 1_000_000; } /// Used to coalesce records during iteration fn coalesce_records(prev: Record, curr: Record) -> Result<Record, (Record, Record)> { // we always go with the newest timestamp if prev.key() == curr.key() { Ok(if prev.created() > curr.created() { prev } else { curr }) } else { Err( (prev, curr) ) } } /* * Files have the following meanings: * data.wal - Write Ahead Log; journal of all put & deletes that are in mem_table * table.current - SSTable with the merges from mem_table * table-#.data - SSTables without overlapping ranges * *-new - A new version of the file with the same name */ impl KVS { /// Creates a new KVS given a directory to store the files fn new(options: KVSOptions) -> Result<KVS, IOError> { let db_dir = options.db_dir.to_path_buf(); let mut mem_table = BTreeMap::new(); let wal_file = RecordFile::new(&db_dir.join("data.wal"), WAL_HEADER, options.rec_file_buffer_size, options.rec_file_cache_size)?; // read back in our WAL file if we have one if wal_file.record_count() > 0 { for bytes in wal_file.iter() { let rec = Record::deserialize(bytes); mem_table.insert(rec.key(), rec); } } let sstable_current_path = db_dir.join("table.current"); let sstable_current = if sstable_current_path.exists() { SSTable::open(&sstable_current_path, options.rec_file_buffer_size, options.rec_file_cache_size) } else { SSTable::new(&sstable_current_path, &mut iter::empty::<Record>(), options.group_count, None, options.rec_file_buffer_size, options.rec_file_cache_size) }.expect("Error opening current SSTable"); let mut sstables = BTreeSet::<SSTable>::new(); let re = Regex::new(r"^table-(\d+).data$").unwrap(); let mut max_sstable_num : u64 = 0; // gather up all the SSTables in this directory for entry in fs::read_dir(db_dir.to_path_buf())? { let entry = entry.expect("Error reading directory entry"); let path = entry.path(); if path.is_dir() { continue } let file_name = path.file_name().expect("Error getting file name"); let captures = re.captures(file_name.to_str().expect("Error getting string for file name")); if let Some(capture) = captures { // add to our set of tables sstables.insert(SSTable::open(&path, options.rec_file_buffer_size, options.rec_file_cache_size)?); // get the number of the table let sstable_num = capture.get(1).expect("Error capturing SSTable number").as_str().parse::<u64>().expect("Error parsing number"); if sstable_num > max_sstable_num { max_sstable_num = sstable_num; } } } return Ok(KVS { options: options, cur_sstable_num: max_sstable_num + 1, wal_file: wal_file, mem_table: mem_table, cur_sstable: sstable_current, sstables: sstables, }) } /// Opens an existing KVS directory/database. /// /// All of the original options used to create the KVS instance will be used when open. /// /// # Examples /// ``` /// { // scope so it is dropped after opening /// KVSOptions::new("/tmp/kvs").create().unwrap(); /// } /// /// let kvs = KVS::open("/tmp/kvs").unwrap(); /// ``` pub fn open(db_dir: &PathBuf) -> Result<KVS, IOError> { } /// Returns the path to the WAL file (or new one) fn wal_file_path(&self, new: bool) -> PathBuf { if new { self.options.db_dir.join("data.wal-new") } else { self.options.db_dir.join("data.wal") } } /// Returns the path to the current SSTable (or new one) fn cur_sstable_path(&self, new: bool) -> PathBuf { if new { self.options.db_dir.join("table.current-new") } else { self.options.db_dir.join("table.current") } } /// Generates the path to the current SSTable fn sstable_path(&self) -> PathBuf { self.options.db_dir.join(format!("table-{}.data", self.cur_sstable_num)) } /// Creates a new WAL file, deletes current WAL file, and renames the new to current fn update_wal_file(&mut self) { { // create a new WAL file RecordFile::new(&self.wal_file_path(true), WAL_HEADER, self.options.rec_file_buffer_size, self.options.rec_file_cache_size).expect(&format!("Error creating WAL file: {:?}", self.wal_file_path(true))); } // remove the old one fs::remove_file(&self.wal_file_path(false)).expect(&format!("Error removing: {:?}", self.wal_file_path(false))); // rename the new to old fs::rename(self.wal_file_path(true), &self.wal_file_path(false)).expect(&format!("Error renaming WAL file: {:?} -> {:?}", self.wal_file_path(true), self.wal_file_path(false))); self.wal_file = RecordFile::new(&self.wal_file_path(false), WAL_HEADER, self.options.rec_file_buffer_size, self.options.rec_file_cache_size).expect(&format!("Error opening WAL file: {:?}", self.wal_file_path(false))); } /// flush the mem_table to disk /// return: true if the flush occured fn flush(&mut self, check_size: bool) -> bool { debug!("Starting a flush"); if check_size && self.mem_table.len() < self.options.max_mem_count { debug!("Too few records in mem_table: {} < {}", self.mem_table.len(), self.options.max_mem_count); return false; // don't need to do anything yet } // update the reference to our current SSTable self.cur_sstable = { let mem_it: Box<Iterator<Item=Record>> = Box::new(self.mem_table.values().map(move |r| r.to_owned())); let ss_it: Box<Iterator<Item=Record>> = Box::new(self.cur_sstable.iter()); // create an iterator that merge-sorts and also coalesces out similar records let mut it = kmerge(vec![mem_it, ss_it]).coalesce(coalesce_records); { // create and close the new SSTable SSTable::new(&self.cur_sstable_path(true), &mut it, self.options.group_count as u32, None, self.options.rec_file_buffer_size, self.options.rec_file_cache_size).expect(&format!("Error creating SSTable: {:?}", &self.cur_sstable_path(true))); } // remove the old one if it exists // in theory, this should *always* exist because we create blank ones // however, flush() is called by Drop, so we could be in a funky state during this call if self.cur_sstable_path(false).exists() { fs::remove_file(&self.cur_sstable_path(false)).expect(&format!("Error removing: {:?}", self.cur_sstable_path(false))); } // rename the new to old fs::rename(&self.cur_sstable_path(true), &self.cur_sstable_path(false)).expect(&format!("Error renaming current SSTable: {:?} -> {:?}", self.cur_sstable_path(true), self.cur_sstable_path(false))); SSTable::open(&self.cur_sstable_path(false), self.options.rec_file_buffer_size, self.options.rec_file_cache_size).expect(&format!("Error opening current SSTable: {:?}", self.cur_sstable_path(false))) }; // remove everything in the mem_table self.mem_table.clear(); // update the WAL file self.update_wal_file(); debug!("Leaving flush"); true } /// Compacts the mem_table, current_sstable, and sstables into new sstables /// return: true if the compaction actually ran fn compact(&mut self) -> bool { debug!("Starting a compaction"); // we wait until we have enough records for every file to get self.options.max_mem_count if self.mem_table.len() as u64 + self.cur_sstable.record_count() < (self.options.max_mem_count * self.options.file_count) as u64 { debug!("Not enough records for compact: {} < {}", self.mem_table.len() as u64 + self.cur_sstable.record_count(), (self.options.max_mem_count * self.options.file_count) as u64); return false; } // save off the file paths to the old SSTables as it's not nice to delete files that are still open let sstable_paths = self.sstables.iter().map(|table| table.file_path()).collect::<Vec<_>>(); // create iterators for all the SSTables and the mem_table self.sstables = { let mem_it: Box<Iterator<Item=Record>> = Box::new(self.mem_table.values().map(move |r| r.to_owned())); let ss_cur_it: Box<Iterator<Item=Record>> = Box::new(self.cur_sstable.iter()); let mut ss_its = Vec::with_capacity(self.options.file_count + 2); let mut record_count = self.mem_table.len() as u64 + self.cur_sstable.record_count(); ss_its.push(mem_it); ss_its.push(ss_cur_it); for sstable in self.sstables.iter() { record_count += sstable.record_count(); ss_its.push(Box::new(sstable.iter())); } let cur_time = get_timestamp(); let mut it = kmerge(ss_its).coalesce(coalesce_records).filter(|rec| { !rec.is_delete() && !rec.is_expired(cur_time) // remove all deleted and expired }); let records_per_file = record_count / self.options.file_count as u64; debug!("RECORDS PER FILE: {} = {} / {}", records_per_file, record_count, self.options.file_count as u64); let mut new_sstables = BTreeSet::<SSTable>::new(); // create all the tables but the last one for _i in 0..self.options.file_count-1 { let sstable = SSTable::new(&self.sstable_path(), &mut it, self.options.group_count as u32, Some(records_per_file), self.options.rec_file_buffer_size, self.options.rec_file_cache_size).expect(&format!("Error creating SSTable: {:?}", self.sstable_path())); self.cur_sstable_num += 1; new_sstables.insert(sstable); } // the last one gets all the rest of the records let sstable = SSTable::new(&self.sstable_path(), &mut it, self.options.group_count as u32, None, self.options.rec_file_buffer_size, self.options.rec_file_cache_size).expect(&format!("Error creating SSTable: {:?}", self.sstable_path())); self.cur_sstable_num += 1; new_sstables.insert(sstable); new_sstables }; // remove all the old SSTables for sstable_path in sstable_paths.iter() { fs::remove_file(&sstable_path).expect(&format!("Error removing old SSTable: {:?}", sstable_path)); } // remove the current SSTable fs::remove_file(self.cur_sstable_path(false)).expect(&format!("Error removing current SSTable: {:?}", self.cur_sstable_path(false))); // create a new empty current SSTable self.cur_sstable = SSTable::new(&self.cur_sstable_path(false), &mut iter::empty::<Record>(), self.options.group_count, None, self.options.rec_file_buffer_size, self.options.rec_file_cache_size).expect(&format!("Error creating blank current SSTable: {:?}", self.cur_sstable_path(false))); // remove everything from the mem_table self.mem_table.clear(); // update the WAL file self.update_wal_file(); debug!("Leaving compact"); true } pub fn get(&self, key: &Vec<u8>) -> Option<Vec<u8>> { debug!("Called get: {:?}", key); let cur_time = get_timestamp(); debug!("MEM TABLE: {}", self.mem_table.len()); // first check the mem_table if self.mem_table.contains_key(key) { let rec = self.mem_table.get(key).unwrap(); // found an expired or deleted key return if rec.is_expired(cur_time) || rec.is_delete() { debug!("Found expired or deleted key"); None } else { Some(rec.value()) }; } // next check the current SSTable if let Some(rec) = self.cur_sstable.get(key.to_vec()).expect("Error reading from SSTable") { return if rec.is_expired(cur_time) || rec.is_delete() { debug!("Found expired or deleted key"); None } else { Some(rec.value()) }; } // finally, need to go to SSTables for sstable in self.sstables.iter() { debug!("SSTABLE: {:?}", sstable); let ret_opt = sstable.get(key.to_vec()).expect("Error reading from SSTable"); // we didn't find the key if ret_opt.is_none() { continue; } let rec = ret_opt.unwrap(); // sanity check if rec.is_delete() { panic!("Found deleted key in SSTable: {:?}", sstable); } return Some(rec.value()); } None // if we get to here, we don't have it } fn insert(&mut self, record: Record) { self.wal_file.append_record(&record).expect("Error writing to WAL file"); // insert into the mem_table self.mem_table.insert(record.key(), record); // check to see if we need to flush to disk if self.mem_table.len() >= self.options.max_mem_count { // compact won't do anything if it's not needed if !self.compact() { // see if we need to flush, if a compaction didn't occur self.flush(true); } } } pub fn put(&mut self, key: Vec<u8>, value: Vec<u8>) { // debug!("Called put: {:?}", key); // create a record, and call insert let rec = Record::new(key.to_vec(), Some(value)); self.insert(rec) } pub fn delete(&mut self, key: &Vec<u8>) { debug!("Called delete: {:?}", key); // create a record, and call insert let rec = Record::new(key.to_vec(), None); self.insert(rec) } /// Returns an upper bound on the number of records /// To get an exact count, we'd need to read all the records in searching for deletes pub fn count_estimate(&self) -> u64 { let mut sum = self.mem_table.len() as u64; debug!("mem_table count: {}", sum); sum += self.cur_sstable.record_count(); debug!("cur_sstable count: {}", self.cur_sstable.record_count()); for sstable in self.sstables.iter() { debug!("{:?} count: {}", sstable, sstable.record_count()); sum += sstable.record_count(); } debug!("SUM: {}", sum); return sum; } } impl Drop for KVS { fn drop(&mut self) { debug!("KVS Drop"); // call flush without checking the size self.flush(false); } } #[cfg(test)] mod tests { use kvs::{KVSOptions, KVS}; use std::path::PathBuf; use rand::{thread_rng, Rng}; use std::fs::create_dir; use simple_logger; use ::LOGGER_INIT; const MAX_MEM_COUNT: usize = 100; const MAX_FILE_COUNT: usize = 6; fn gen_dir() -> PathBuf { LOGGER_INIT.call_once(|| simple_logger::init().unwrap()); // this will panic on error let tmp_dir: String = thread_rng().gen_ascii_chars().take(6).collect(); let ret_dir = PathBuf::from("/tmp").join(format!("kvs_{}", tmp_dir)); debug!("CREATING TMP DIR: {:?}", ret_dir); create_dir(&ret_dir).unwrap(); return ret_dir; } #[test] fn new() { let db_dir = gen_dir(); let _kvs = KVSOptions::new(&PathBuf::from(db_dir)).create().unwrap(); } #[test] fn put_flush_get() { let db_dir = gen_dir(); let mut kvs = KVSOptions::new(&PathBuf::from(db_dir)).create().unwrap(); let key = "KEY".as_bytes(); let value = "VALUE".as_bytes(); kvs.put(key.to_vec(), value.to_vec()); assert_eq!(kvs.count_estimate(), 1); kvs.flush(false); assert_eq!(kvs.count_estimate(), 1); let ret = kvs.get(&key.to_vec()); assert_eq!(value, ret.unwrap().as_slice()); } #[test] fn auto_flush() { let db_dir = gen_dir(); let mut kvs = KVSOptions::new(&PathBuf::from(db_dir)).create().unwrap(); for _i in 0..MAX_MEM_COUNT+1 { let rnd: String = thread_rng().gen_ascii_chars().take(6).collect(); let key = format!("KEY_{}", rnd).as_bytes().to_vec(); let value = rnd.as_bytes().to_vec(); kvs.put(key, value); } assert_eq!(kvs.count_estimate(), (MAX_MEM_COUNT+1) as u64); } #[test] fn compact() { let db_dir = gen_dir(); let mut kvs = KVSOptions::new(&PathBuf::from(db_dir)).create().unwrap(); for _i in 0..MAX_MEM_COUNT*MAX_FILE_COUNT + 1 { let rnd: String = thread_rng().gen_ascii_chars().take(6).collect(); let key = format!("KEY_{}", rnd).as_bytes().to_vec(); let value = rnd.as_bytes().to_vec(); kvs.put(key, value); } assert_eq!(kvs.count_estimate(), (MAX_MEM_COUNT*MAX_FILE_COUNT + 1) as u64); kvs.compact(); assert_eq!(kvs.count_estimate(), (MAX_MEM_COUNT*MAX_FILE_COUNT + 1) as u64); } #[test] fn compact2() { let db_dir = gen_dir(); { let mut kvs = KVSOptions::new(&db_dir).create().unwrap(); for _i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let rnd: String = thread_rng().gen_ascii_chars().take(6).collect(); let key = format!("KEY_{}", rnd).as_bytes().to_vec(); let value = rnd.as_bytes().to_vec(); kvs.put(key, value); } assert_eq!(kvs.count_estimate(), (MAX_MEM_COUNT*MAX_FILE_COUNT + 1) as u64); kvs.compact(); assert_eq!(kvs.count_estimate(), (MAX_MEM_COUNT*MAX_FILE_COUNT + 1) as u64); } let mut kvs = KVSOptions::new(&db_dir).create().unwrap(); for _i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let rnd: String = thread_rng().gen_ascii_chars().take(6).collect(); let key = format!("KEY_{}", rnd).as_bytes().to_vec(); let value = rnd.as_bytes().to_vec(); kvs.put(key, value); } assert_eq!(kvs.count_estimate(), ((MAX_MEM_COUNT*MAX_FILE_COUNT+1)*2) as u64); kvs.compact(); assert_eq!(kvs.count_estimate(), ((MAX_MEM_COUNT*MAX_FILE_COUNT+1)*2) as u64); } #[test] fn delete() { let db_dir = gen_dir(); let mut kvs = KVSOptions::new(&PathBuf::from(db_dir)).create().unwrap(); let key = "KEY".as_bytes(); let value = "VALUE".as_bytes(); kvs.put(key.to_vec(), value.to_vec()); assert_eq!(kvs.count_estimate(), 1); kvs.delete(&key.to_vec()); // should still be only 1 record assert_eq!(kvs.count_estimate(), 1); assert!(kvs.get(&key.to_vec()).is_none(), "Found key after deleting it!"); kvs.flush(false); // should still be only 1 record assert_eq!(kvs.count_estimate(), 1); assert!(kvs.get(&key.to_vec()).is_none(), "Found key after deleting it!"); } #[test] fn put_close_open_get() { let db_dir = gen_dir(); { let mut kvs = KVSOptions::new(&db_dir).create().unwrap(); // fill half the mem_table, so we're sure we don't flush for i in 0..MAX_MEM_COUNT / 2 { let rnd: String = thread_rng().gen_ascii_chars().take(6).collect(); let key = format!("KEY_{}", i).as_bytes().to_vec(); let value = rnd.as_bytes().to_vec(); kvs.put(key, value); } } { let kvs = KVSOptions::new(&db_dir).create().unwrap(); for i in 0..MAX_MEM_COUNT / 2 { let key = format!("KEY_{}", i).as_bytes().to_vec(); assert!(kvs.get(&key).is_some(), "Couldn't find key: {}", i); } } { let kvs = KVSOptions::new(&db_dir).create().unwrap(); for i in 0..MAX_MEM_COUNT / 2 { let key = format!("KEY_{}", i).as_bytes().to_vec(); assert!(kvs.get(&key).is_some(), "Couldn't find key: {}", i); } } } #[test] fn put_compact_get() { let db_dir = gen_dir(); let mut kvs = KVSOptions::new(&db_dir).create().unwrap(); for i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let rnd: String = thread_rng().gen_ascii_chars().take(6).collect(); let key = format!("KEY_{}", i).as_bytes().to_vec(); let value = rnd.as_bytes().to_vec(); kvs.put(key, value); } assert_eq!(kvs.count_estimate(), (MAX_MEM_COUNT*MAX_FILE_COUNT + 1) as u64); for i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let key = format!("KEY_{}", i).as_bytes().to_vec(); assert!(kvs.get(&key).is_some(), "Couldn't find key: {}", i); } } #[test] fn put_compact_update_get() { let db_dir = gen_dir(); let mut kvs = KVSOptions::new(&db_dir).create().unwrap(); for i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let rnd: String = thread_rng().gen_ascii_chars().take(6).collect(); let key = format!("KEY_{}", i).as_bytes().to_vec(); let value = rnd.as_bytes().to_vec(); kvs.put(key, value); } // compact would have happened here assert_eq!(kvs.count_estimate(), (MAX_MEM_COUNT*MAX_FILE_COUNT + 1) as u64); for i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let key = format!("KEY_{}", i).as_bytes().to_vec(); let value = format!("VALUE_{}", i).as_bytes().to_vec(); kvs.put(key, value); // update our keys } for i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let key = format!("KEY_{}", i).as_bytes().to_vec(); let ret = kvs.get(&key); assert!(ret.is_some(), "Couldn't find key: {}", i); assert_eq!(ret.unwrap(), format!("VALUE_{}", i).as_bytes().to_vec(), "Didn't get update for key: {}", i); } } #[test] fn put_compact_delete_get() { let db_dir = gen_dir(); let mut kvs = KVSOptions::new(&db_dir).create().unwrap(); for i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let rnd: String = thread_rng().gen_ascii_chars().take(6).collect(); let key = format!("KEY_{}", i).as_bytes().to_vec(); let value = rnd.as_bytes().to_vec(); kvs.put(key, value); } // compact would have happened here assert_eq!(kvs.count_estimate(), (MAX_MEM_COUNT*MAX_FILE_COUNT + 1) as u64); for i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let key = format!("KEY_{}", i).as_bytes().to_vec(); kvs.delete(&key); // delete our key } // compact would happen here for i in 0..MAX_MEM_COUNT * MAX_FILE_COUNT + 1 { let key = format!("KEY_{}", i).as_bytes().to_vec(); let ret = kvs.get(&key); assert!(ret.is_none(), "Found deleted key: {}", i); } } }
// `with_decimals` in integration tests mod with_scientific; use super::*; #[test] fn without_valid_option_errors_badarg() { crate::test::float_to_string::without_valid_option_errors_badarg(file!(), result); }
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn ldexp(x: f64, n: i32) -> f64 { super::scalbn(x, n) }
extern crate rand; extern crate piston_window; mod emulator; use std::env; use std::io::prelude::*; use std::path::Path; use piston_window::*; use emulator::ChipEight; fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 2 { let mut stderr = std::io::stderr(); writeln!(&mut stderr, "usage: {:?} [chip_eight_program]", args[0]).unwrap(); return; } let mut emulator = ChipEight::new(); let prog_path = Path::new(&args[1]); emulator.load_memory(&prog_path); let mut window: PistonWindow = WindowSettings::new( "Rusty Chips", [emulator::SCREEN_WIDTH as u32, emulator::SCREEN_HEIGHT as u32] ).exit_on_esc(true) .build() .unwrap(); let mut events = window.events(); while let Some(e) = events.next(&mut window) { if let Some(u) = e.update_args() { emulator.update_timer(u.dt); emulator.emulate_cycle(); } } }
//! The `snow` crate is a straightforward, Hard To Fuck Up™ Noise Protocol implementation. //! //! Read the [Noise Protocol Framework Spec](http://noiseprotocol.org/noise.html) for more //! information. //! //! The typical usage flow is to use `NoiseBuilder` to construct a `Session`, which is main //! state machine you will want to interact with. //! //! # Examples //! See `examples/simple.rs` for a more complete TCP client/server example. //! //! ```rust,ignore //! let noise = NoiseBuilder::new("Noise_NN_ChaChaPoly_BLAKE2s".parse().unwrap()) //! .build_initiator() //! .unwrap(); //! //! let mut buf = [0u8; 65535]; //! //! // write first handshake message //! noise.write_message(&[0u8; 0], &mut buf).unwrap(); //! //! // receive response message //! let incoming = receive_message_from_the_mysterious_ether(); //! noise.read_message(&incoming, &mut buf).unwrap(); //! //! // complete handshake, and transition the state machine into transport mode //! let noise = noise.into_transport_mode(); //! //! ``` #![cfg_attr(feature = "nightly", feature(try_from))] #![recursion_limit = "1024"] extern crate arrayvec; extern crate byteorder; #[macro_use] extern crate static_slice; #[macro_use] extern crate error_chain; #[cfg(feature = "ring-resolver")] extern crate ring; mod error; mod constants; mod utils; mod cipherstate; mod symmetricstate; mod handshakestate; mod noise; mod session; mod transportstate; pub mod params; pub mod types; pub mod wrappers; pub use error::*; pub use noise::{CryptoResolver, DefaultResolver}; pub use noise::NoiseBuilder; pub use session::Session; #[cfg(feature = "ring-resolver")] pub use wrappers::ring_wrapper::RingAcceleratedResolver;
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! some useful utils to create inner SQLs use core::fmt::Write; pub struct SelectBuilder { from: String, columns: Vec<String>, filters: Vec<String>, order_bys: Vec<String>, } impl SelectBuilder { pub fn from(table_name: &str) -> SelectBuilder { SelectBuilder { from: table_name.to_owned(), columns: vec![], filters: vec![], order_bys: vec![], } } pub fn with_column(&mut self, col_name: impl Into<String>) -> &mut Self { self.columns.push(col_name.into()); self } pub fn with_filter(&mut self, col_name: impl Into<String>) -> &mut Self { self.filters.push(col_name.into()); self } pub fn with_order_by(&mut self, order_by: &str) -> &mut Self { self.order_bys.push(order_by.to_owned()); self } pub fn build(self) -> String { let mut query = String::new(); let mut columns = String::new(); let s = self.columns.join(","); if s.is_empty() { write!(columns, "*").unwrap(); } else { write!(columns, "{s}").unwrap(); } let mut order_bys = String::new(); let s = self.order_bys.join(","); if s.is_empty() { write!(order_bys, "{s}").unwrap(); } else { write!(order_bys, "ORDER BY {s}").unwrap(); } let mut filters = String::new(); let s = self.filters.join(" and "); if !s.is_empty() { write!(filters, "where {s}").unwrap(); } else { write!(filters, "").unwrap(); } let from = self.from; write!(query, "SELECT {columns} FROM {from} {filters} {order_bys} ").unwrap(); query } }
#![recursion_limit = "1024"] use byteorder::{ByteOrder, LittleEndian as LE}; use custom_error::custom_error; use deoptloader::decompressor::{Decompressor, Error as DecompressorError, Op}; use deoptloader::fixup_converter::FixupConverter; use deoptloader::neexe::*; use nom::{do_parse, le_u16, named, named_args, tag, take_until, take_until_and_consume}; use std::io::prelude::*; use std::io; use std::fs::File; use std::error::Error as StdError; named!(detect_optloader<String>, do_parse!( take_until!("OPTLOADER") >> text: take_until_and_consume!("\0") >> (String::from_utf8_lossy(text).to_string()) ) ); #[derive(Debug, Clone)] struct OptOffsets { copy_from_offset: u16, copy_to_offset: u16, copy_length: u16, decompress_from_offset: u16, decompress_to_offset: u16, } const X86_MOV_SI: u8 = b'\xbe'; const X86_MOV_DI: u8 = b'\xbf'; named_args!(parse_offsets(code_size: u16)<OptOffsets>, do_parse!( take_until_and_consume!(&[X86_MOV_SI][..]) >> copy_from_offset: le_u16 >> tag!([X86_MOV_DI]) >> copy_to_offset_end: le_u16 >> take_until_and_consume!(&[X86_MOV_DI][..]) >> decompress_to_offset: le_u16 >> (OptOffsets { copy_from_offset, copy_to_offset: copy_to_offset_end - code_size, copy_length: code_size, decompress_from_offset: copy_to_offset_end - code_size + 1, decompress_to_offset }) ) ); custom_error!{OptError NotSelfLoading = "not a self-loading executable", MissingBootOffsets = "missing boot offsets", MissingCopyright = "missing copyright string" } struct OptUnpacker<'a> { ne: &'a NEExecutable<'a>, output: Vec<u8>, copyright: String, boot_code_offsets: OptOffsets, sector_alignment: usize, } impl<'a> OptUnpacker<'a> { pub fn new(ne: &'a NEExecutable) -> Result<Self, Box<dyn StdError>> { let (header, boot_code_size) = match ne.selfload_header()? { Some((header, extra_header_data)) => (header, LE::read_u16(&extra_header_data[6..])), None => { return Err(Box::new(OptError::NotSelfLoading)); } }; let (copyright, boot_code_offsets) = { let boot_code = &ne.segment_data(1)?[(header.boot_app_offset & 0xffff) as usize..]; match detect_optloader(boot_code) { Ok((boot_init_code, copyright)) => { (copyright, match parse_offsets(boot_init_code, boot_code_size) { Ok((_, offsets)) => offsets, Err(_) => { return Err(Box::new(OptError::MissingBootOffsets)); } }) }, Err(_) => { return Err(Box::new(OptError::MissingCopyright)); } } }; let mut output = Vec::with_capacity(ne.raw_data().len()); let header_size = ne.segment_header(1)?.offset as usize; output.extend_from_slice(&ne.raw_data()[0..header_size]); Ok(OptUnpacker { ne, output, copyright, boot_code_offsets, sector_alignment: 1 << ne.header().alignment_shift_count, }) } pub fn copyright(&self) -> &String { &self.copyright } pub fn unpack_all(&mut self) -> Result<(), Box<dyn StdError>> { // TODO: Delete the loader segment entirely instead? (It only needed // to be unpacked to reverse engineer the loader itself.) let size = self.unpack_boot_segment()?; println!("Unpacked boot segment ({} bytes)", size); for segment_number in 2..=self.ne.header().num_segments { let size = self.unpack_normal_segment(segment_number)?; println!("Unpacked segment {} ({} bytes)", segment_number, size); } let trailer_offset = match self.copy_resources() { Some(offset) => offset, None => { let last_segment = self.ne.segment_header(self.ne.header().num_segments)?; (last_segment.offset + last_segment.data_size) as usize } }; let input = self.ne.raw_data(); if trailer_offset != input.len() { let trailer_output_offset = self.output.len(); self.output.extend_from_slice(&input[trailer_offset..]); println!("Copied trailer ({} bytes)", self.output.len() - trailer_output_offset); // HACK: This is Macromedia Director-specific let director_offset = LE::read_u32(&input[input.len() - 4..]) as usize; if director_offset >= trailer_offset && director_offset < input.len() { let output_director_offset = trailer_output_offset + director_offset - trailer_offset; let delta = output_director_offset - director_offset; let director_offset_offset = self.output.len() - 4; LE::write_u32(&mut self.output[director_offset_offset..], output_director_offset as u32); let mut director_data_table = &mut self.output[output_director_offset + 4..]; for _ in 0..6 { let offset = LE::read_u32(director_data_table) as usize + delta; LE::write_u32(&mut director_data_table, offset as u32); director_data_table = &mut director_data_table[4..]; } println!("Rewrote Director trailer"); } } self.clear_selfload_header(); println!("Removed self-loading header"); Ok(()) } pub fn unpack_boot_segment(&mut self) -> Result<usize, Box<dyn StdError>> { let segment_header = self.ne.segment_header(1)?; let segment_data = self.ne.segment_data(1)?; let input = { let mut input: Vec<u8> = Vec::with_capacity(segment_header.alloc_size as usize); input.extend_from_slice(segment_data); input.resize(segment_header.alloc_size as usize, 0); safemem::copy_over( &mut input, self.boot_code_offsets.copy_from_offset as usize, self.boot_code_offsets.copy_to_offset as usize, self.boot_code_offsets.copy_length as usize + 1 ); input }; let (input_offset, output_offset) = (self.boot_code_offsets.decompress_from_offset as usize, self.boot_code_offsets.decompress_to_offset as usize); let output_segment_offset = self.output.len(); let max_needed_size = output_segment_offset + segment_header.alloc_size as usize; self.output.extend_from_slice(&input); self.output.resize(max_needed_size, 0); let (_, mut decompressed_size) = self.run_decompressor(&input, input_offset, output_segment_offset + output_offset)?; decompressed_size += output_offset; self.output.resize(output_segment_offset + decompressed_size as usize, 0); let new_segment_header = { let mut header = segment_header.clone(); header.data_size = decompressed_size as u32; header }; self.set_segment_table_entry(1, new_segment_header); if segment_header.flags.contains(NESegmentFlags::HAS_RELOC) { let fixup_table = &segment_data[segment_header.data_size as usize..]; self.output.extend_from_slice(fixup_table); decompressed_size += fixup_table.len(); } decompressed_size += self.align_output(self.sector_alignment); Ok(decompressed_size) } pub fn unpack_normal_segment(&mut self, segment_number: u16) -> Result<usize, Box<dyn StdError>> { let segment_header = self.ne.segment_header(segment_number)?; let segment_data = self.ne.segment_data(segment_number)?; let output_segment_offset = self.output.len(); let (has_relocations, code_size, total_size) = if segment_header.data_size > 0 { let num_relocations = LE::read_u16(segment_data); let extra_data = segment_header.offset % 512; let aligned_offset = (segment_header.offset - extra_data) as usize; let aligned_input = &self.ne.raw_data()[aligned_offset..aligned_offset + segment_data.len() + extra_data as usize]; let max_needed_size = output_segment_offset + segment_header.alloc_size as usize; self.output.extend_from_slice(aligned_input); if max_needed_size > self.output.len() { self.output.resize(max_needed_size, 0); } let (relocations_offset, decompressed_size) = self.run_decompressor(segment_data, 2, output_segment_offset)?; self.output.resize(output_segment_offset + decompressed_size as usize, 0); let mut total_size = decompressed_size; if num_relocations > 0 { self.output.extend_from_slice(&[ (num_relocations & 0xff) as u8, (num_relocations >> 8 & 0xff) as u8 ]); total_size += 2; let converter = FixupConverter::new(&segment_data[relocations_offset..], num_relocations); for fixup in converter { self.output.extend_from_slice(&fixup); total_size += fixup.len(); } } total_size += self.align_output(self.sector_alignment); (num_relocations > 0, decompressed_size, total_size) } else { (false, 0, 0) }; let new_segment_header = { let mut header = segment_header.clone(); header.offset = output_segment_offset as u32; header.data_size = code_size as u32; if has_relocations { header.flags |= NESegmentFlags::HAS_RELOC; } header }; self.set_segment_table_entry(segment_number, new_segment_header); Ok(total_size) } fn run_decompressor(&mut self, input: &[u8], input_offset: usize, output_offset: usize) -> Result<(usize, usize), DecompressorError> { let mut decompressor = Decompressor::new(&input[input_offset..])?; let mut output_index = output_offset; loop { let op = decompressor.next_op()?; match op { Op::Noop => { continue; }, Op::Literal(value) => { self.output[output_index] = value; output_index += 1; }, Op::Terminate(input_index) => { return Ok((input_offset + input_index, output_index - output_offset)); }, Op::CopyBytes{ offset, count } => { for i in 0..count { self.output[output_index + i as usize] = self.output[output_index - (offset as usize) - 1 + i as usize]; } output_index += count as usize; } } } } fn write_to_file(&self, filename: &str) -> Result<(usize, usize), io::Error> { std::fs::write(filename, &self.output)?; Ok((self.ne.raw_data().len(), self.output.len())) } fn set_segment_table_entry(&mut self, segment_number: u16, data: NESegmentEntry) { let ne_header = self.ne.header(); let offset = self.ne.header_offset() + ne_header.segment_table_offset as usize; let segment_table = &mut self.output[(offset + ((segment_number - 1) * 8) as usize) as usize..]; assert_eq!((data.offset % self.sector_alignment as u32), 0); LE::write_u16(segment_table, (data.offset / self.sector_alignment as u32) as u16); LE::write_u16(&mut segment_table[2..], data.data_size as u16); LE::write_u16(&mut segment_table[4..], data.flags.bits()); LE::write_u16(&mut segment_table[6..], data.alloc_size as u16); } fn set_resource_offset(&mut self, mut resource_index: u16, alignment: usize, offset: usize) { let table_offset = self.ne.header_offset() + self.ne.header().resource_table_offset as usize; let mut resource_table = &mut self.output[table_offset + 2..]; loop { let resources_in_block = LE::read_u16(&resource_table[2..]); if resource_index < resources_in_block { let resource = &mut resource_table[8 + resource_index as usize * 12..]; assert_eq!(offset % alignment, 0); LE::write_u16(resource, (offset / alignment) as u16); break; } else { resource_index -= resources_in_block; resource_table = &mut resource_table[8 + resources_in_block as usize * 12..]; } } } fn clear_selfload_header(&mut self) { let flags = self.ne.header().flags - NEFlags::SELF_LOAD; LE::write_u16(&mut self.output[self.ne.header_offset() + 12..], flags.bits()); } fn copy_resources(&mut self) -> Option<usize> { if let Some(alignment_shift) = self.ne.resource_table_alignment_shift() { let alignment = 1 << alignment_shift; self.align_output(alignment); let input = self.ne.raw_data(); let mut trailer_offset = 0; for (index, resource) in self.ne.iter_resources().enumerate() { let new_resource_start = self.output.len(); let end_offset = resource.offset + resource.length; self.output.extend_from_slice(&input[resource.offset as usize..end_offset as usize]); self.align_output(alignment); self.set_resource_offset(index as u16, alignment, new_resource_start); if trailer_offset < end_offset { trailer_offset = end_offset; } println!("Copied resource {} ({} bytes)", index + 1, resource.length); } Some(trailer_offset as usize) } else { None } } fn align_output(&mut self, alignment: usize) -> usize { let last_sector_size = self.output.len() % alignment; if last_sector_size != 0 { let padding_bytes = alignment - last_sector_size; self.output.resize(self.output.len() + padding_bytes as usize, 0); padding_bytes } else { 0 } } } fn fix_file(in_filename: &str, out_filename: &str) -> Result<(usize, usize), Box<dyn StdError>> { let input = { let mut file = File::open(&in_filename)?; let mut input: Vec<u8> = Vec::with_capacity(file.metadata()?.len() as usize); file.read_to_end(&mut input)?; input }; let executable = NEExecutable::new(&input)?; let mut unpacker = OptUnpacker::new(&executable)?; let name = match executable.name() { Some(name) => name, None => in_filename.to_string() }; println!("Unpacking {}", name); println!("{}", unpacker.copyright()); unpacker.unpack_all()?; Ok(unpacker.write_to_file(out_filename)?) } fn main() { let (in_filename, out_filename) = { let args: Vec<_> = std::env::args().collect(); if args.len() < 2 { println!("Usage: {} <packed executable> [<output filename>]", &args[0]); std::process::exit(1); } let out_file = if args.len() > 2 { args[2].clone() } else { args[1].clone() + ".out" }; (args[1].clone(), out_file) }; match fix_file(&in_filename, &out_filename) { Ok((in_size, out_size)) => { println!("Successfully unpacked {} to {} ({} -> {} bytes)", in_filename, out_filename, in_size, out_size); }, Err(e) => { println!("Failed to unpack {}: {}", in_filename, e); std::process::exit(1); } }; }
fn main() { // if is an expression, so it can be used // on the right side of a 'let' statement let condition = true; let number = if condition { 5 } else { 6 // note the lack of semicolon // on this expression }; println!("The value of number is: {}", number); }
/* 设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。 注意:本题相对原题做了扩展 示例: 输入:4 输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] 解释: 4 皇后问题存在如下两个不同的解法。 [ [".Q..",  // 解法 1 "...Q", "Q...", "..Q."], ["..Q.",  // 解法 2 "Q...", "...Q", ".Q.."] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/eight-queens-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ impl Solution { pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> { let n = n as usize; let mut result: Vec<Vec<String>> = vec![]; let mut v = vec![0; n]; fn solve(v: &mut Vec<usize>, i: usize, result: &mut Vec<Vec<String>>) { let n = v.len(); if i == v.len() { let mut mat = vec![]; for x in v { let mut res = vec!["."; n]; res[*x] = "Q"; mat.push((res).join("")); } result.push(mat); return; } // 遍历可以填的数字 for x in 0..v.len() { //假装填入数字 v[i] = x; let mut checked = true; // 遍历已经填的数字 for j in 0..i { if (v[j] as i32 - v[i] as i32).pow(2) == (i as i32 - j as i32).pow(2) || v[j] == v[i] { checked = false; break; } } if checked { solve(v, i + 1, result); } // 还原 v[i] = 0; } } solve(&mut v, 0, &mut result); return result; } } fn main() { let res = Solution::solve_n_queens(8); dbg!(&res); dbg!(&res.len()); } struct Solution {}
#[doc = "Reader of register M5FDRH"] pub type R = crate::R<u32, super::M5FDRH>; #[doc = "Reader of field `FEC`"] pub type FEC_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Failing error code"] #[inline(always)] pub fn fec(&self) -> FEC_R { FEC_R::new((self.bits & 0xffff_ffff) as u32) } }
use nalgebra::{ allocator::Allocator, storage::Storage, DefaultAllocator, Dim, Norm, OVector, RealField, Vector, }; pub fn distance_to_space<X, D, S1, S2, S3>( p1: &Vector<X, D, S1>, min_bounds: &Vector<X, D, S2>, max_bounds: &Vector<X, D, S3>, norm: &impl Norm<X>, ) -> X where X: RealField, D: Dim, S1: Storage<X, D>, S2: Storage<X, D>, S3: Storage<X, D>, DefaultAllocator: Allocator<X, D>, { let (rows, cols) = p1.shape_generic(); let p2 = OVector::from_fn_generic(rows, cols, |i, _| { if p1[i] > max_bounds[i] { max_bounds[i].clone() } else if p1[i] < min_bounds[i] { min_bounds[i].clone() } else { p1[i].clone() } }); norm.metric_distance(&p1, &p2) } #[cfg(test)] mod tests { use super::distance_to_space; use crate::norm::EuclideanNormSquared; use std::f64::{INFINITY, NEG_INFINITY}; #[test] fn test_normal_distance_to_space() { let dis = distance_to_space( &[0.0, 0.0].into(), &[1.0, 1.0].into(), &[2.0, 2.0].into(), &EuclideanNormSquared, ); assert_eq!(dis, 2.0); } #[test] fn test_distance_outside_inf() { let dis = distance_to_space( &[0.0, 0.0].into(), &[1.0, 1.0].into(), &[INFINITY, INFINITY].into(), &EuclideanNormSquared, ); assert_eq!(dis, 2.0); } #[test] fn test_distance_inside_inf() { let dis = distance_to_space( &[2.0, 2.0].into(), &[NEG_INFINITY, NEG_INFINITY].into(), &[INFINITY, INFINITY].into(), &EuclideanNormSquared, ); assert_eq!(dis, 0.0); } #[test] fn test_distance_inside_normal() { let dis = distance_to_space( &[2.0, 2.0].into(), &[0.0, 0.0].into(), &[3.0, 3.0].into(), &EuclideanNormSquared, ); assert_eq!(dis, 0.0); } #[test] fn distance_to_half_space() { let dis = distance_to_space( &[-2.0, 0.0].into(), &[0.0, NEG_INFINITY].into(), &[INFINITY, INFINITY].into(), &EuclideanNormSquared, ); assert_eq!(dis, 4.0); } }
/** * @lc app=leetcode.cn id=216 lang=rust * * [216] 组合总和 III * * https://leetcode-cn.com/problems/combination-sum-iii/description/ * * algorithms * Medium (63.45%) * Total Accepted: 3.1K * Total Submissions: 4.9K * Testcase Example: '3\n7' * * 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。 * * 说明: * * * 所有数字都是正整数。 * 解集不能包含重复的组合。 * * * 示例 1: * * 输入: k = 3, n = 7 * 输出: [[1,2,4]] * * * 示例 2: * * 输入: k = 3, n = 9 * 输出: [[1,2,6], [1,3,5], [2,3,4]] * * */ impl Solution { pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> { let mut res = Vec::new(); Self::dfs(&mut res, &mut vec![], n, k as usize); res } pub fn dfs(res: &mut Vec<Vec<i32>>, temp: &mut Vec<i32>, target: i32, k: usize) { if temp.len() == k { if target == 0 { res.push(temp.clone()); } return; } let start = temp.last().map(|it| it + 1).unwrap_or(1); for i in start..10 { if !temp.contains(&i) { temp.push(i); Self::dfs(res, temp, target - i, k); temp.pop(); } } } } fn main() { let res = Solution::combination_sum3(3, 9); res.iter().for_each(|v| println!("{:?}", v)); } struct Solution {}
use crate::{ event::{self, Event}, sinks::util::{ encoding::EncodingConfigWithDefault, http::{Auth, BatchedHttpSink, HttpClient, HttpSink}, service2::TowerRequestConfig, BatchConfig, BatchSettings, BoxedRawValue, JsonArrayBuffer, UriSerde, }, topology::config::{DataType, SinkConfig, SinkContext, SinkDescription}, }; use futures::{FutureExt, TryFutureExt}; use futures01::Sink; use http::{Request, StatusCode, Uri}; use serde::{Deserialize, Serialize}; use serde_json::json; use std::time::SystemTime; lazy_static::lazy_static! { static ref HOST: UriSerde = Uri::from_static("https://logs.logdna.com").into(); } const PATH: &str = "/logs/ingest"; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct LogdnaConfig { api_key: String, host: Option<UriSerde>, hostname: String, mac: Option<String>, ip: Option<String>, tags: Option<Vec<String>>, #[serde( skip_serializing_if = "crate::serde::skip_serializing_if_default", default )] pub encoding: EncodingConfigWithDefault<Encoding>, default_app: Option<String>, #[serde(default)] batch: BatchConfig, #[serde(default)] request: TowerRequestConfig, } inventory::submit! { SinkDescription::new_without_default::<LogdnaConfig>("logdna") } #[derive(Deserialize, Serialize, Debug, Eq, PartialEq, Clone, Derivative)] #[serde(rename_all = "snake_case")] #[derivative(Default)] pub enum Encoding { #[derivative(Default)] Default, } #[typetag::serde(name = "logdna")] impl SinkConfig for LogdnaConfig { fn build(&self, cx: SinkContext) -> crate::Result<(super::RouterSink, super::Healthcheck)> { let request_settings = self.request.unwrap_with(&TowerRequestConfig::default()); let batch_settings = BatchSettings::default() .bytes(bytesize::mib(10u64)) .timeout(1) .parse_config(self.batch)?; let client = HttpClient::new(cx.resolver(), None)?; let sink = BatchedHttpSink::new( self.clone(), JsonArrayBuffer::new(batch_settings.size), request_settings, batch_settings.timeout, client.clone(), cx.acker(), ) .sink_map_err(|e| error!("Fatal logdna sink error: {}", e)); let healthcheck = healthcheck(self.clone(), client).boxed().compat(); Ok((Box::new(sink), Box::new(healthcheck))) } fn input_type(&self) -> DataType { DataType::Log } fn sink_type(&self) -> &'static str { "logdna" } } #[async_trait::async_trait] impl HttpSink for LogdnaConfig { type Input = serde_json::Value; type Output = Vec<BoxedRawValue>; fn encode_event(&self, event: Event) -> Option<Self::Input> { let mut log = event.into_log(); let line = log .remove(&event::log_schema().message_key()) .unwrap_or_else(|| "".into()); let timestamp = log .remove(&event::log_schema().timestamp_key()) .unwrap_or_else(|| chrono::Utc::now().into()); let mut map = serde_json::map::Map::new(); map.insert("line".to_string(), json!(line)); map.insert("timestamp".to_string(), json!(timestamp)); if let Some(app) = log.remove(&"app".into()) { map.insert("app".to_string(), json!(app)); } if let Some(file) = log.remove(&"file".into()) { map.insert("file".to_string(), json!(file)); } if !map.contains_key("app") && !map.contains_key("file") { if let Some(default_app) = &self.default_app { map.insert("app".to_string(), json!(default_app.as_str())); } else { map.insert("app".to_string(), json!("vector")); } } if !log.is_empty() { map.insert("meta".into(), json!(&log)); } Some(map.into()) } async fn build_request(&self, events: Self::Output) -> crate::Result<http::Request<Vec<u8>>> { let mut query = url::form_urlencoded::Serializer::new(String::new()); let now = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .expect("Time can't drift behind the epoch!") .as_millis(); query.append_pair("hostname", &self.hostname); query.append_pair("now", &format!("{}", now)); if let Some(mac) = &self.mac { query.append_pair("mac", mac); } if let Some(ip) = &self.ip { query.append_pair("ip", ip); } if let Some(tags) = &self.tags { let tags = tags.join(","); query.append_pair("tags", &tags); } let query = query.finish(); let body = serde_json::to_vec(&json!({ "lines": events, })) .unwrap(); let uri = self.build_uri(&query); let mut request = Request::builder() .uri(uri) .method("POST") .header("Content-Type", "application/json") .body(body) .unwrap(); let auth = Auth::Basic { user: self.api_key.clone(), password: "".to_string(), }; auth.apply(&mut request); Ok(request) } } impl LogdnaConfig { fn build_uri(&self, query: &str) -> Uri { let host: Uri = self.host.clone().unwrap_or_else(|| HOST.clone()).into(); let uri = format!("{}{}?{}", host, PATH, query); uri.parse::<http::Uri>() .expect("This should be a valid uri") } } async fn healthcheck(config: LogdnaConfig, mut client: HttpClient) -> crate::Result<()> { let uri = config.build_uri(""); let req = Request::post(uri).body(hyper::Body::empty()).unwrap(); let res = client.send(req).await?; if res.status().is_server_error() { return Err("Server returned a server error".into()); } if res.status() == StatusCode::FORBIDDEN { return Err("Token is not valid, 403 returned.".into()); } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::event::Event; use crate::sinks::util::test::{build_test_server, load_sink}; use crate::test_util; use crate::topology::config::SinkConfig; use futures01::{Sink, Stream}; use serde_json::json; #[test] fn encode_event() { let (config, _, _) = load_sink::<LogdnaConfig>( r#" api_key = "mylogtoken" hostname = "vector" "#, ) .unwrap(); let mut event1 = Event::from("hello world"); event1.as_mut_log().insert("app", "notvector"); let mut event2 = Event::from("hello world"); event2.as_mut_log().insert("file", "log.txt"); let event3 = Event::from("hello world"); let event1_out = config.encode_event(event1).unwrap(); let event1_out = event1_out.as_object().unwrap(); let event2_out = config.encode_event(event2).unwrap(); let event2_out = event2_out.as_object().unwrap(); let event3_out = config.encode_event(event3).unwrap(); let event3_out = event3_out.as_object().unwrap(); assert_eq!(event1_out.get("app").unwrap(), &json!("notvector")); assert_eq!(event2_out.get("file").unwrap(), &json!("log.txt")); assert_eq!(event3_out.get("app").unwrap(), &json!("vector")); } #[test] fn smoke() { crate::test_util::trace_init(); let (mut config, cx, mut rt) = load_sink::<LogdnaConfig>( r#" api_key = "mylogtoken" ip = "127.0.0.1" mac = "some-mac-addr" hostname = "vector" tags = ["test","maybeanothertest"] "#, ) .unwrap(); // Make sure we can build the config let _ = config.build(cx.clone()).unwrap(); let addr = test_util::next_addr(); // Swap out the host so we can force send it // to our local server let host = format!("http://{}", addr).parse::<http::Uri>().unwrap(); config.host = Some(host.into()); let (sink, _) = config.build(cx).unwrap(); let (rx, _trigger, server) = build_test_server(addr, &mut rt); rt.spawn(server); let lines = test_util::random_lines(100).take(10).collect::<Vec<_>>(); let mut events = Vec::new(); // Create 10 events where the first one contains custom // fields that are not just `message`. for (i, line) in lines.iter().enumerate() { let event = if i == 0 { let mut event = Event::from(line.as_str()); event.as_mut_log().insert("key1", "value1"); event } else { Event::from(line.as_str()) }; events.push(event); } let pump = sink.send_all(futures01::stream::iter_ok(events)); let _ = rt.block_on(pump).unwrap(); let output = rx.take(1).wait().collect::<Result<Vec<_>, _>>().unwrap(); let request = &output[0].0; let body: serde_json::Value = serde_json::from_slice(&output[0].1[..]).unwrap(); let query = request.uri.query().unwrap(); assert!(query.contains("hostname=vector")); assert!(query.contains("ip=127.0.0.1")); assert!(query.contains("mac=some-mac-addr")); assert!(query.contains("tags=test%2Cmaybeanothertest")); let output = body .as_object() .unwrap() .get("lines") .unwrap() .as_array() .unwrap(); for (i, line) in output.iter().enumerate() { // All lines are json objects let line = line.as_object().unwrap(); assert_eq!(line.get("app").unwrap(), &json!("vector")); assert_eq!(line.get("line").unwrap(), &json!(lines[i])); if i == 0 { assert_eq!( line.get("meta").unwrap(), &json!({ "key1": "value1" }) ); } } } }
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use helixdb::Entry; use rand::{thread_rng, Rng}; fn do_benchmark(key_size: usize, value_size: usize, c: &mut Criterion) { let mut rng = thread_rng(); let key = (0..key_size).map(|_| rng.gen()).collect(); let value = (0..value_size).map(|_| rng.gen()).collect(); let entry = Entry { timestamp: 1234423, key, value, }; c.bench_function( &format!("encode {}B / {}B entry", key_size, value_size), |b| b.iter(|| entry.encode()), ); let bytes = entry.encode(); c.bench_function( &format!("decode {}B / {}B entry", key_size, value_size), |b| b.iter(|| Entry::decode(&bytes)), ); } fn entry_codec_benchmark(c: &mut Criterion) { do_benchmark(64, 8, c); do_benchmark(64, 32, c); do_benchmark(64, 1024, c); do_benchmark(64, 4096, c); } fn fibonacci(n: u64) -> u64 { let mut a = 0; let mut b = 1; match n { 0 => b, _ => { for _ in 0..n { let c = a + b; a = b; b = c; } b } } } fn some_bench(c: &mut Criterion) { c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20)))); } criterion_group!(benches, entry_codec_benchmark, some_bench); criterion_main!(benches);
use core::{cmp, mem, ptr, slice}; use orbclient::{Color, Renderer}; use std::fs::find; use std::proto::Protocol; use std::string::String; use std::vec::Vec; use uefi::status::{Error, Result}; use uefi::guid::GuidKind; use uefi::memory::MemoryType; use crate::disk::DiskEfi; use crate::display::{Display, ScaledDisplay, Output}; use crate::image::{self, Image}; use crate::key::{key, Key}; use crate::text::TextDisplay; use self::memory_map::memory_map; use self::paging::{paging_create, paging_enter}; mod memory_map; mod paging; mod partitions; static KERNEL: &'static str = concat!("\\", env!("BASEDIR"), "\\kernel"); static SPLASHBMP: &'static [u8] = include_bytes!("../../../res/splash.bmp"); static PHYS_OFFSET: u64 = 0xFFFF800000000000; static mut KERNEL_PHYS: u64 = 0; static mut KERNEL_SIZE: u64 = 0; static mut KERNEL_ENTRY: u64 = 0; static mut STACK_PHYS: u64 = 0; static STACK_SIZE: u64 = 0x20000; static mut ENV_PHYS: u64 = 0; static mut ENV_SIZE: u64 = 0; static mut RSDPS_AREA: Option<Vec<u8>> = None; #[repr(packed)] pub struct KernelArgs { kernel_base: u64, kernel_size: u64, stack_base: u64, stack_size: u64, env_base: u64, env_size: u64, acpi_rsdps_base: u64, acpi_rsdps_size: u64, } unsafe fn allocate_zero_pages(pages: usize) -> Result<usize> { let uefi = std::system_table(); let mut ptr = 0; (uefi.BootServices.AllocatePages)( 0, // AllocateAnyPages MemoryType::EfiRuntimeServicesData, // Keeps this memory out of free space list pages, &mut ptr )?; ptr::write_bytes(ptr as *mut u8, 0, 4096); Ok(ptr) } unsafe fn exit_boot_services(key: usize) { let handle = std::handle(); let uefi = std::system_table(); let _ = (uefi.BootServices.ExitBootServices)(handle, key); } unsafe fn enter() -> ! { let args = KernelArgs { kernel_base: KERNEL_PHYS, kernel_size: KERNEL_SIZE, stack_base: STACK_PHYS, stack_size: STACK_SIZE, env_base: ENV_PHYS, env_size: ENV_SIZE, acpi_rsdps_base: RSDPS_AREA.as_ref().map(Vec::as_ptr).unwrap_or(core::ptr::null()) as usize as u64 + PHYS_OFFSET, acpi_rsdps_size: RSDPS_AREA.as_ref().map(Vec::len).unwrap_or(0) as u64, }; let entry_fn: extern "sysv64" fn(args_ptr: *const KernelArgs) -> ! = mem::transmute(KERNEL_ENTRY); entry_fn(&args); } fn get_correct_block_io() -> Result<DiskEfi> { // Get all BlockIo handles. let mut handles = vec! [uefi::Handle(0); 128]; let mut size = handles.len() * mem::size_of::<uefi::Handle>(); (std::system_table().BootServices.LocateHandle)(uefi::boot::LocateSearchType::ByProtocol, &uefi::guid::BLOCK_IO_GUID, 0, &mut size, handles.as_mut_ptr())?; let max_size = size / mem::size_of::<uefi::Handle>(); let actual_size = std::cmp::min(handles.len(), max_size); // Return the handle that seems bootable. for handle in handles.into_iter().take(actual_size) { let block_io = DiskEfi::handle_protocol(handle)?; if !block_io.0.Media.LogicalPartition { continue; } let part = partitions::PartitionProto::handle_protocol(handle)?.0; if part.sys == 1 { continue; } assert_eq!({part.rev}, partitions::PARTITION_INFO_PROTOCOL_REVISION); if part.ty == partitions::PartitionProtoDataTy::Gpt as u32 { let gpt = unsafe { part.info.gpt }; assert_ne!(gpt.part_ty_guid, partitions::ESP_GUID, "detected esp partition again"); if gpt.part_ty_guid == partitions::REDOX_FS_GUID || gpt.part_ty_guid == partitions::LINUX_FS_GUID { return Ok(block_io); } } else if part.ty == partitions::PartitionProtoDataTy::Mbr as u32 { let mbr = unsafe { part.info.mbr }; if mbr.ty == 0x83 { return Ok(block_io); } } else { continue; } } panic!("Couldn't find handle for partition"); } struct Invalid; fn validate_rsdp(address: usize, v2: bool) -> core::result::Result<usize, Invalid> { #[repr(packed)] #[derive(Clone, Copy, Debug)] struct Rsdp { signature: [u8; 8], // b"RSD PTR " chksum: u8, oem_id: [u8; 6], revision: u8, rsdt_addr: u32, // the following fields are only available for ACPI 2.0, and are reserved otherwise length: u32, xsdt_addr: u64, extended_chksum: u8, _rsvd: [u8; 3], } // paging is not enabled at this stage; we can just read the physical address here. let rsdp_bytes = unsafe { core::slice::from_raw_parts(address as *const u8, core::mem::size_of::<Rsdp>()) }; let rsdp = unsafe { (rsdp_bytes.as_ptr() as *const Rsdp).as_ref::<'static>().unwrap() }; println!("RSDP: {:?}", rsdp); if rsdp.signature != *b"RSD PTR " { return Err(Invalid); } let mut base_sum = 0u8; for base_byte in &rsdp_bytes[..20] { base_sum = base_sum.wrapping_add(*base_byte); } if base_sum != 0 { return Err(Invalid); } if rsdp.revision == 2 { let mut extended_sum = 0u8; for byte in rsdp_bytes { extended_sum = extended_sum.wrapping_add(*byte); } if extended_sum != 0 { return Err(Invalid); } } let length = if rsdp.revision == 2 { rsdp.length as usize } else { core::mem::size_of::<Rsdp>() }; Ok(length) } fn find_acpi_table_pointers() -> Result<()> { let rsdps_area = unsafe { RSDPS_AREA = Some(Vec::new()); RSDPS_AREA.as_mut().unwrap() }; let cfg_tables = std::system_table().config_tables(); for (address, v2) in cfg_tables.iter().find_map(|cfg_table| if cfg_table.VendorGuid.kind() == GuidKind::Acpi { Some((cfg_table.VendorTable, false)) } else if cfg_table.VendorGuid.kind() == GuidKind::Acpi2 { Some((cfg_table.VendorTable, true)) } else { None }) { match validate_rsdp(address, v2) { Ok(length) => { let align = 8; rsdps_area.extend(&u32::to_ne_bytes(length as u32)); rsdps_area.extend(unsafe { core::slice::from_raw_parts(address as *const u8, length) }); rsdps_area.resize(((rsdps_area.len() + (align - 1)) / align) * align, 0u8); } Err(_) => println!("Found RSDP that wasn't valid at {:p}", address as *const u8), } } Ok(()) } fn redoxfs() -> Result<redoxfs::FileSystem<DiskEfi>> { // TODO: Scan multiple partitions for a kernel. // TODO: pass block_opt for performance reasons redoxfs::FileSystem::open(get_correct_block_io()?, None).map_err(|_| Error::DeviceError) } const MB: usize = 1024 * 1024; fn inner() -> Result<()> { //TODO: detect page size? let page_size = 4096; { let mut env = String::new(); if let Ok(output) = Output::one() { let mode = &output.0.Mode; env.push_str(&format!("FRAMEBUFFER_ADDR={:016x}\n", mode.FrameBufferBase)); env.push_str(&format!("FRAMEBUFFER_WIDTH={:016x}\n", mode.Info.HorizontalResolution)); env.push_str(&format!("FRAMEBUFFER_HEIGHT={:016x}\n", mode.Info.VerticalResolution)); } println!("Loading Kernel..."); let kernel = if let Ok((_i, mut kernel_file)) = find(KERNEL) { let info = kernel_file.info()?; let len = info.FileSize; let kernel = unsafe { let ptr = allocate_zero_pages((len as usize + page_size - 1) / page_size)?; slice::from_raw_parts_mut( ptr as *mut u8, len as usize ) }; let mut i = 0; for mut chunk in kernel.chunks_mut(4 * MB) { print!("\r{}% - {} MB", i as u64 * 100 / len, i / MB); let count = kernel_file.read(&mut chunk)?; if count == 0 { break; } //TODO: return error instead of assert assert_eq!(count, chunk.len()); i += count; } println!("\r{}% - {} MB", i as u64 * 100 / len, i / MB); kernel } else { let mut fs = redoxfs()?; let root = fs.header.1.root; let node = fs.find_node("kernel", root).map_err(|_| Error::DeviceError)?; let len = fs.node_len(node.0).map_err(|_| Error::DeviceError)?; let kernel = unsafe { let ptr = allocate_zero_pages((len as usize + page_size - 1) / page_size)?; println!("{:X}", ptr); slice::from_raw_parts_mut( ptr as *mut u8, len as usize ) }; let mut i = 0; for mut chunk in kernel.chunks_mut(4 * MB) { print!("\r{}% - {} MB", i as u64 * 100 / len, i / MB); let count = fs.read_node(node.0, i as u64, &mut chunk, 0, 0).map_err(|_| Error::DeviceError)?; if count == 0 { break; } //TODO: return error instead of assert assert_eq!(count, chunk.len()); i += count; } println!("\r{}% - {} MB", i as u64 * 100 / len, i / MB); env.push_str(&format!("REDOXFS_BLOCK={:016x}\n", fs.block)); env.push_str("REDOXFS_UUID="); for i in 0..fs.header.1.uuid.len() { if i == 4 || i == 6 || i == 8 || i == 10 { env.push('-'); } env.push_str(&format!("{:>02x}", fs.header.1.uuid[i])); } kernel }; unsafe { KERNEL_PHYS = kernel.as_ptr() as u64; KERNEL_SIZE = kernel.len() as u64; KERNEL_ENTRY = *(kernel.as_ptr().offset(0x18) as *const u64); println!("Kernel {:X}:{:X} entry {:X}", KERNEL_PHYS, KERNEL_SIZE, KERNEL_ENTRY); } println!("Allocating stack {:X}", STACK_SIZE); unsafe { STACK_PHYS = allocate_zero_pages(STACK_SIZE as usize / page_size)? as u64; println!("Stack {:X}:{:X}", STACK_PHYS, STACK_SIZE); } println!("Allocating env {:X}", env.len()); unsafe { ENV_PHYS = allocate_zero_pages((env.len() + page_size - 1) / page_size)? as u64; ENV_SIZE = env.len() as u64; ptr::copy(env.as_ptr(), ENV_PHYS as *mut u8, env.len()); println!("Env {:X}:{:X}", ENV_PHYS, ENV_SIZE); } println!("Parsing and writing ACPI RSDP structures."); find_acpi_table_pointers(); println!("Done!"); } println!("Creating page tables"); let page_phys = unsafe { paging_create(KERNEL_PHYS)? }; println!("Entering kernel"); unsafe { let key = memory_map(); exit_boot_services(key); } unsafe { llvm_asm!("cli" : : : "memory" : "intel", "volatile"); paging_enter(page_phys); } unsafe { llvm_asm!("mov rsp, $0" : : "r"(STACK_PHYS + PHYS_OFFSET + STACK_SIZE) : "memory" : "intel", "volatile"); enter(); } } fn draw_text(display: &mut ScaledDisplay, mut x: i32, y: i32, text: &str, color: Color) { for c in text.chars() { display.char(x, y, c, color); x += 8; } } fn draw_background(display: &mut ScaledDisplay, splash: &Image) { let bg = Color::rgb(0x4a, 0xa3, 0xfd); display.set(bg); { let x = (display.width() as i32 - splash.width() as i32)/2; let y = 16; splash.draw(display, x, y); } { let prompt = format!( "Redox Bootloader {} {}", env!("CARGO_PKG_VERSION"), env!("TARGET").split('-').next().unwrap_or("") ); let x = (display.width() as i32 - prompt.len() as i32 * 8)/2; let y = display.height() as i32 - 32; draw_text(display, x, y, &prompt, Color::rgb(0xff, 0xff, 0xff)); } } fn select_mode(output: &mut Output, splash: &Image) -> Result<()> { // Read all available modes let mut modes = Vec::new(); for i in 0..output.0.Mode.MaxMode { let mut mode_ptr = ::core::ptr::null_mut(); let mut mode_size = 0; (output.0.QueryMode)(output.0, i, &mut mode_size, &mut mode_ptr)?; let mode = unsafe { &mut *mode_ptr }; let w = mode.HorizontalResolution; let h = mode.VerticalResolution; let mut aspect_w = w; let mut aspect_h = h; for i in 2..cmp::min(aspect_w / 2, aspect_h / 2) { while aspect_w % i == 0 && aspect_h % i == 0 { aspect_w /= i; aspect_h /= i; } } //TODO: support resolutions that are not perfect multiples of 4 if w % 4 != 0 { continue; } modes.push((i, w, h, format!("{:>4}x{:<4} {:>3}:{:<3}", w, h, aspect_w, aspect_h))); } // Sort modes by pixel area, reversed modes.sort_by(|a, b| (b.1 * b.2).cmp(&(a.1 * a.2))); // Find current mode index let mut selected = output.0.Mode.Mode; // If there are no modes from querymode, don't change mode if modes.is_empty() { return Ok(()); } let white = Color::rgb(0xff, 0xff, 0xff); let black = Color::rgb(0x00, 0x00, 0x00); let rows = 12; loop { { // Create a scaled display let mut display = Display::new(output); let mut display = ScaledDisplay::new(&mut display); draw_background(&mut display, splash); let off_x = (display.width() as i32 - 60 * 8)/2; let mut off_y = 16 + splash.height() as i32 + 16; draw_text( &mut display, off_x, off_y, "Arrow keys and enter select mode", white ); off_y += 24; let mut row = 0; let mut col = 0; for (i, w, h, text) in modes.iter() { if row >= rows as i32 { col += 1; row = 0; } let x = off_x + col * 20 * 8; let y = off_y + row * 16; let fg = if *i == selected { display.rect(x - 8, y, text.len() as u32 * 8 + 16, 16, white); black } else { white }; draw_text(&mut display, x, y, text, fg); row += 1; } display.sync(); } match key(true)? { Key::Left => { if let Some(mut mode_i) = modes.iter().position(|x| x.0 == selected) { if mode_i < rows { while mode_i < modes.len() { mode_i += rows; } } mode_i -= rows; if let Some(new) = modes.get(mode_i) { selected = new.0; } } }, Key::Right => { if let Some(mut mode_i) = modes.iter().position(|x| x.0 == selected) { mode_i += rows; if mode_i >= modes.len() { mode_i = mode_i % rows; } if let Some(new) = modes.get(mode_i) { selected = new.0; } } }, Key::Up => { if let Some(mut mode_i) = modes.iter().position(|x| x.0 == selected) { if mode_i % rows == 0 { mode_i += rows; if mode_i > modes.len() { mode_i = modes.len(); } } mode_i -= 1; if let Some(new) = modes.get(mode_i) { selected = new.0; } } }, Key::Down => { if let Some(mut mode_i) = modes.iter().position(|x| x.0 == selected) { mode_i += 1; if mode_i % rows == 0 { mode_i -= rows; } if mode_i >= modes.len() { mode_i = mode_i - mode_i % rows; } if let Some(new) = modes.get(mode_i) { selected = new.0; } } }, Key::Enter => { (output.0.SetMode)(output.0, selected)?; return Ok(()); }, _ => (), } } } fn pretty_pipe<T, F: FnMut() -> Result<T>>(output: &mut Output, splash: &Image, f: F) -> Result<T> { let mut display = Display::new(output); let mut display = ScaledDisplay::new(&mut display); draw_background(&mut display, splash); display.sync(); { let cols = 80; let off_x = (display.width() as i32 - cols as i32 * 8)/2; let off_y = 16 + splash.height() as i32 + 16; let rows = (display.height() as i32 - 64 - off_y - 1) as usize/16; display.rect(off_x, off_y, cols as u32 * 8, rows as u32 * 16, Color::rgb(0, 0, 0)); display.sync(); let mut text = TextDisplay::new(display); text.off_x = off_x; text.off_y = off_y; text.cols = cols; text.rows = rows; text.pipe(f) } } pub fn main() -> Result<()> { if let Ok(mut output) = Output::one() { let mut splash = Image::new(0, 0); { println!("Loading Splash..."); if let Ok(image) = image::bmp::parse(&SPLASHBMP) { splash = image; } println!(" Done"); } select_mode(&mut output, &splash)?; pretty_pipe(&mut output, &splash, inner)?; } else { inner()?; } Ok(()) }
use rust_algorithms::union_find::UnionFind; use rust_algorithms::union_find::quick_find::QuickFind; use crate::union_find::common::*; #[test] #[should_panic] fn quick_find_not_zero() { QuickFind::new(0); } #[test] #[should_panic] fn quick_find_out_of_bounds() { let size = 10; test_out_of_bounds(&mut QuickFind::new(size), size); } #[test] fn quick_find_component_count() { let size = 10; test_component_count(&QuickFind::new(size), size); } #[test] fn quick_find_union() { test_union(&mut QuickFind::new(5)); } #[test] fn quick_find_union_already_connected() { test_union_already_connected(&mut QuickFind::new(5)); }
use tree_sitter::Node; use crate::lint::core::{ValidationError, Validator}; use crate::lint::grammar::FIELD_IDENTIFIER; use crate::lint::rule::RULE_EXPECT_CALL; use crate::lint::utils::node_lowercase_eq; pub struct ExpectCallValidator; impl Validator for ExpectCallValidator { fn validate(&self, node: &Node, source: &str) -> Result<(), ValidationError> { if node_lowercase_eq(FIELD_IDENTIFIER, node, source, "expect") { Err(ValidationError::from_node(node, RULE_EXPECT_CALL)) } else { Ok(()) } } } #[cfg(test)] mod tests { use super::*; use crate::lint::filters::filter_nothing::NothingFilter; use crate::lint::utils::{assert_source_ok, validate}; use crate::RuleCode; #[test] fn test_no_expect_call() { let filter = NothingFilter; let source_code = "fn test() -> usize { a.no_expect_call() }"; assert_source_ok(source_code, Box::new(ExpectCallValidator), &filter); } #[test] fn test_expect_call() { let filter = NothingFilter; let source_code = "fn test() -> usize { a.expect() }"; let res = validate(source_code, Box::new(ExpectCallValidator), &filter); let err = assert_err!(res); assert_eq!(err.rule.code, RuleCode::Expect); } }
// https://github.com/TylerGlaiel/FrameTimingControl/blob/master/frame_timer.cpp use super::*; //these are loaded from Settings in production code const UPDATE_RATE: f64 = 60.; //compute how many ticks one update should be const FIXED_DELTATIME: f64 = 1.0 / UPDATE_RATE; pub(crate) const DESIRED_FRAMETIME: f64 = 1.0 / UPDATE_RATE; //these are to snap deltaTime to vsync values if it's close enough const VSYNC_MAXERROR: f64 = 0.02; const TIME_60HZ: f64 = 1.0 / 60.; //since this is about snapping to common vsync values const SNAP_FREQUENCIES: [f64; 5] = [ TIME_60HZ, //60fps TIME_60HZ * 2., //30fps TIME_60HZ * 3., //20fps TIME_60HZ * 4., //15fps (TIME_60HZ + 1.) / 2., //120fps //120hz, 240hz, or higher need to round up, so that adding 120hz twice guaranteed is at least the same as adding time_60hz once // (time_60hz + 2.) / 3., //180fps //that's where the +1 and +2 come from in those equations // (time_60hz + 3.) / 4., //240fps //I do not want to snap to anything higher than 120 in my engine, but I left the math in here anyway ]; impl<G: Game> Runner<G> { pub(crate) fn frame_timer(&mut self, ctx: &mut mq::Context) -> f64 { //frame timer let current_frame_time: f64 = mq::date::now(); let mut delta_time = current_frame_time - self.frame_time; self.frame_time = current_frame_time; //handle unexpected timer anomalies (overflow, extra slow frames, etc) if delta_time > DESIRED_FRAMETIME * 8. { //ignore extra-slow frames delta_time = DESIRED_FRAMETIME; } if delta_time < 0. { delta_time = 0.; } //vsync time snapping for snap in SNAP_FREQUENCIES { if f64::abs(delta_time - snap) < VSYNC_MAXERROR { delta_time = snap; break; } } //delta time averaging self.time_averager.push(delta_time); delta_time = self.time_averager.iter().sum::<f64>() / self.time_averager.len() as f64; //add to the accumulator self.frame_accumulator += delta_time; //spiral of death protection if self.frame_accumulator > DESIRED_FRAMETIME * 8. { self.resync = true; } //timer resync if requested if self.resync { self.frame_accumulator = 0.; delta_time = DESIRED_FRAMETIME; self.resync = false; } let mut consumed_delta_time = delta_time; while self.frame_accumulator >= DESIRED_FRAMETIME { if consumed_delta_time > DESIRED_FRAMETIME { //cap variable update's dt to not be larger than fixed update let eng = Engine { now: current_frame_time, delta: FIXED_DELTATIME, fps: self.fps(), overstep_percentage: self.overstep_percentage, quad_ctx: ctx, egui_ctx: self.egui_mq.egui_ctx(), mouse_over_ui: self.mouse_over_ui, input: &mut self.input, script: &mut self.script, event_sender: &self.event_sender, }; self.game.update(eng); consumed_delta_time -= DESIRED_FRAMETIME; } self.frame_accumulator -= DESIRED_FRAMETIME; } let eng = Engine { now: current_frame_time, delta: consumed_delta_time, fps: self.fps(), overstep_percentage: self.overstep_percentage, quad_ctx: ctx, egui_ctx: self.egui_mq.egui_ctx(), mouse_over_ui: self.mouse_over_ui, input: &mut self.input, script: &mut self.script, event_sender: &self.event_sender, }; self.game.update(eng); // store frame_percentage to be used later by render self.frame_accumulator / DESIRED_FRAMETIME } }
/// /// Creates a retina map that can be used to simulate macular degeneration. /// /// # Arguments /// /// - `res` - resolution of the returned retina map /// - `severity` - the severity of the disease, value between 0 and 100 /// pub fn generate_simple( res: (u32, u32), severity: u8, ) -> image::ImageBuffer<image::Rgba<u8>, Vec<u8>> { // convert severity from int between 0 and 100 to float between 0.5 and 1 let severity = severity as f64 / 100.0; let severity = 1.0 - 0.5 * (1.0 - severity).powi(2); let radius = severity * res.0 as f64 / 3.0; generate(res, radius, severity) } /// /// Creates a retina map that can be used to simulate macular degeneration. /// /// # Arguments /// /// - `res` - resolution of the returned retina map /// - `radius` - radius of the affected area /// - `intensity` - intensity of the degeneration, value between 0.0 and 1.0 /// pub fn generate( res: (u32, u32), radius: f64, intensity: f64, ) -> image::ImageBuffer<image::Rgba<u8>, Vec<u8>> { let mut map = image::ImageBuffer::new(res.0, res.1); let cx = (res.0 / 2) as i32; let cy = (res.1 / 2) as i32; for (x, y, pixel) in map.enumerate_pixels_mut() { let distance_squared = (cx - x as i32).pow(2) + (cy - y as i32).pow(2); // enlarges the black spot in the center. let spot_factor = 1.78; // ensures the outer areas are zero. let tail_factor = 0.72; let relative_falloff = 1.0 - (radius.powi(2) - distance_squared as f64).max(0.0) / radius.powi(2); let x = spot_factor * (-relative_falloff).exp() - tail_factor; let cells = 255 - (255.0 * x * intensity).max(0.0).min(255.0) as u8; *pixel = image::Rgba([cells, cells, cells, cells]); } map }
use serde_json::Value; use super::constants::AUTH_RULE; #[allow(non_camel_case_types)] #[derive(Deserialize, Debug, Serialize, PartialEq)] pub enum AuthAction { ADD, EDIT } #[derive(Serialize, Deserialize, PartialEq, Debug)] #[serde(tag = "constraint_id")] pub enum Constraint { #[serde(rename = "OR")] OrConstraint(CombinationConstraint), #[serde(rename = "AND")] AndConstraint(CombinationConstraint), #[serde(rename = "ROLE")] RoleConstraint(RoleConstraint), } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct RoleConstraint { pub sig_count: u32, pub role: String, #[serde(skip_serializing_if = "Option::is_none")] pub metadata: Option<Value>, #[serde(skip_serializing_if = "Option::is_none")] pub need_to_be_owner: Option<bool>, } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct CombinationConstraint { pub auth_constraints: Vec<Constraint> } #[derive(Serialize, PartialEq, Debug)] pub struct AuthRuleOperation { #[serde(rename = "type")] pub _type: String, pub auth_type: String, pub field: String, pub auth_action: AuthAction, #[serde(skip_serializing_if = "Option::is_none")] pub old_value: Option<String>, pub new_value: String, pub constraint: Constraint, } impl AuthRuleOperation { pub fn new(auth_type: String, field: String, auth_action: AuthAction, old_value: Option<String>, new_value: String, constraint: Constraint) -> AuthRuleOperation { AuthRuleOperation { _type: AUTH_RULE.to_string(), auth_type, field, auth_action, old_value, new_value, constraint, } } }
//! Traits for pointers. use std::{mem::ManuallyDrop, ptr::NonNull}; use crate::{ sabi_types::{MovePtr, RMut, RRef}, utils::Transmuter, }; #[allow(unused_imports)] use core_extensions::utils::transmute_ignore_size; #[cfg(test)] mod tests; /// /// Determines whether the referent of a pointer is dropped when the /// pointer deallocates the memory. /// /// On Yes, the referent of the pointer is dropped. /// /// On No,the memory the pointer owns is deallocated without calling the destructor /// of the referent. #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] pub enum CallReferentDrop { /// Yes, /// No, } /// Determines whether the pointer is deallocated. #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq, StableAbi)] pub enum Deallocate { /// No, /// Yes, } /////////// /// What kind of pointer this is. /// /// # Safety /// /// Each associated item describes their requirements for the implementor. /// /// pub unsafe trait GetPointerKind: Sized { /// The kind of the pointer. /// /// # Safety for implementor /// /// This is what each kind requires to be used as this associated type: /// /// - [`PK_Reference`]: `Self` must be a `&T`, /// or a `Copy` and `#[repr(transparent)]` wrapper around a raw pointer or reference, /// with `&T` semantics. /// Note that converting into and then back from `&Self::PtrTarget` might /// be a lossy operation for such a type and therefore incorrect. /// /// - [`PK_MutReference`]: `Self` must be a `&mut T`, /// or a non-`Drop` and `#[repr(transparent)]` wrapper around a /// primitive pointer, with `&mut T` semantics. /// /// - [`PK_SmartPointer`]: Any pointer type that's neither of the two other kinds. /// /// /// [`PK_Reference`]: ./struct.PK_Reference.html /// [`PK_MutReference`]: ./struct.PK_MutReference.html /// [`PK_SmartPointer`]: ./struct.PK_SmartPointer.html type Kind: PointerKindVariant; /// What this pointer points to. /// /// This is here so that pointers don't *have to* implement `Deref`. /// /// # Safety for implementor /// /// If the type implements `std::ops::Deref` this must be the same as /// `<Self as Deref>::Target`. /// type PtrTarget; /// The value-level version of the [`Kind`](#associatedtype.Kind) associated type. /// /// # Safety for implementor /// /// This must not be overriden. const KIND: PointerKind = <Self::Kind as PointerKindVariant>::VALUE; } unsafe impl<'a, T> GetPointerKind for &'a T { type Kind = PK_Reference; type PtrTarget = T; } unsafe impl<'a, T> GetPointerKind for &'a mut T { type Kind = PK_MutReference; type PtrTarget = T; } //////////////////////////////////////////// /// For restricting types to the type-level equivalents of [`PointerKind`] variants. /// /// This trait is sealed, cannot be implemented outside this module, /// and won't be implemented for any more types. /// /// [`PointerKind`]: ./enum.PointerKind.html pub trait PointerKindVariant: Sealed { /// The value of the PointerKind variant Self is equivalent to. const VALUE: PointerKind; } use self::sealed::Sealed; mod sealed { pub trait Sealed {} } /// Describes the kind of a pointer. #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, StableAbi)] #[repr(u8)] pub enum PointerKind { /// A `&T`-like pointer Reference, /// a `&mut T`-like pointer MutReference, /// Any pointer type that's neither of the other variants SmartPointer, } /// The type-level equivalent of [`PointerKind::Reference`]. /// /// [`PointerKind::Reference`]: ./enum.PointerKind.html#variant.Reference #[allow(non_camel_case_types)] pub struct PK_Reference; /// The type-level equivalent of [`PointerKind::MutReference`]. /// /// [`PointerKind::MutReference`]: ./enum.PointerKind.html#variant.MutReference #[allow(non_camel_case_types)] pub struct PK_MutReference; /// The type-level equivalent of [`PointerKind::SmartPointer`]. /// /// [`PointerKind::SmartPointer`]: ./enum.PointerKind.html#variant.SmartPointer #[allow(non_camel_case_types)] pub struct PK_SmartPointer; impl Sealed for PK_Reference {} impl Sealed for PK_MutReference {} impl Sealed for PK_SmartPointer {} impl PointerKindVariant for PK_Reference { const VALUE: PointerKind = PointerKind::Reference; } impl PointerKindVariant for PK_MutReference { const VALUE: PointerKind = PointerKind::MutReference; } impl PointerKindVariant for PK_SmartPointer { const VALUE: PointerKind = PointerKind::SmartPointer; } /////////// /// Whether the pointer can be transmuted to an equivalent pointer with `T` as the referent type. /// /// # Safety /// /// Implementors of this trait must ensure that: /// /// - The memory layout of this /// type is the same regardless of the type of the referent. /// /// - The pointer type is either `!Drop`(no drop glue either), /// or it uses a vtable to Drop the referent and deallocate the memory correctly. /// /// - `transmute_element_` must return a pointer to the same allocation as `self`, /// at the same offset, /// and with no reduced provenance /// (the range of addresses that are valid to dereference with pointers /// derived from the returned pointer). /// /// # Example /// /// ```rust /// use abi_stable::{ /// pointer_trait::{ /// PK_Reference, /// AsPtr, CanTransmuteElement, GetPointerKind, TransmuteElement, /// }, /// sabi_types::StaticRef, /// std_types::{Tuple2, Tuple4}, /// }; /// /// fn main() { /// let reff = FooRef::new(&Tuple4::<u8, u16, u32, u64>(3, 5, 8, 13)); /// /// // safety: `Tuple2<u8, u16>` is a compatible prefix of `Tuple4<u8, u16, u32, u64>` /// let smaller = unsafe{ reff.transmute_element::<Tuple2<u8, u16>>() }; /// assert_eq!(smaller.get(), &Tuple2(3u8, 5u16)); /// } /// /// /// #[derive(Debug, Copy, Clone)] /// #[repr(transparent)] /// struct FooRef<T>(StaticRef<T>); /// /// impl<T: 'static> FooRef<T> { /// pub const fn new(reff: &'static T) -> Self { /// Self(StaticRef::new(reff)) /// } /// pub fn get(self) -> &'static T { /// self.0.get() /// } /// } /// /// unsafe impl<T: 'static> GetPointerKind for FooRef<T> { /// type PtrTarget = T; /// type Kind = PK_Reference; /// } /// /// unsafe impl<T, U> CanTransmuteElement<U> for FooRef<T> /// where /// T: 'static, /// U: 'static, /// { /// type TransmutedPtr = FooRef<U>; /// /// unsafe fn transmute_element_(self) -> Self::TransmutedPtr { /// FooRef(self.0.transmute_element_()) /// } /// } /// /// unsafe impl<T: 'static> AsPtr for FooRef<T> { /// fn as_ptr(&self) -> *const T { /// self.0.as_ptr() /// } /// } /// /// /// /// /// ``` pub unsafe trait CanTransmuteElement<T>: GetPointerKind { /// The type of the pointer after it's element type has been changed. type TransmutedPtr: AsPtr<PtrTarget = T>; /// Transmutes the element type of this pointer.. /// /// # Safety /// /// Callers must ensure that it is valid to convert from a pointer to `Self::Referent` /// to a pointer to `T` . /// /// For example: /// /// It is undefined behavior to create unaligned references , /// therefore transmuting from `&u8` to `&u16` is UB /// if the caller does not ensure that the reference is aligned to a multiple of 2 address. /// /// /// # Example /// /// ``` /// use abi_stable::{ /// pointer_trait::TransmuteElement, /// std_types::RBox, /// }; /// /// let signed:RBox<u32>=unsafe{ /// RBox::new(1_i32) /// .transmute_element::<u32>() /// }; /// /// ``` unsafe fn transmute_element_(self) -> Self::TransmutedPtr; } /// Allows transmuting pointers to point to a different type. pub trait TransmuteElement { /// Transmutes the element type of this pointer.. /// /// # Safety /// /// Callers must ensure that it is valid to convert from a pointer to `Self::PtrTarget` /// to a pointer to `T`, and then use the pointed-to data. /// /// For example: /// /// It is undefined behavior to create unaligned references , /// therefore transmuting from `&u8` to `&u16` is UB /// if the caller does not ensure that the reference is aligned to a multiple of 2 address. /// /// /// # Example /// /// ``` /// use abi_stable::{ /// pointer_trait::TransmuteElement, /// std_types::RBox, /// }; /// /// let signed:RBox<u32>=unsafe{ /// RBox::new(1_i32) /// .transmute_element::<u32>() /// }; /// /// ``` #[inline(always)] unsafe fn transmute_element<T>(self) -> <Self as CanTransmuteElement<T>>::TransmutedPtr where Self: CanTransmuteElement<T>, { unsafe { self.transmute_element_() } } } impl<This: ?Sized> TransmuteElement for This {} /////////// unsafe impl<'a, T: 'a, O: 'a> CanTransmuteElement<O> for &'a T { type TransmutedPtr = RRef<'a, O>; unsafe fn transmute_element_(self) -> Self::TransmutedPtr { unsafe { RRef::from_raw(self as *const T as *const O) } } } /////////// unsafe impl<'a, T: 'a, O: 'a> CanTransmuteElement<O> for &'a mut T { type TransmutedPtr = RMut<'a, O>; unsafe fn transmute_element_(self) -> Self::TransmutedPtr { unsafe { RMut::from_raw(self as *mut T as *mut O) } } } /////////////////////////////////////////////////////////////////////////////// /// For getting a const raw pointer to the value that this points to. /// /// # Safety /// /// The implementor of this trait must return a pointer to the same data as /// `Deref::deref`, without constructing a `&Self::Target` in `as_ptr` /// (or any function it calls), /// /// The implementor of this trait must not override the defaulted methods. /// /// # Example /// /// ```rust /// use abi_stable::{ /// erased_types::interfaces::DebugDefEqInterface, /// pointer_trait::{ /// PK_Reference, /// AsPtr, CanTransmuteElement, GetPointerKind, TransmuteElement, /// }, /// sabi_types::StaticRef, /// DynTrait, /// }; /// /// fn main() { /// let reff: DynTrait<BarRef<()>, DebugDefEqInterface> = /// DynTrait::from_ptr(BarRef::new(&1234i32)); /// /// assert_eq!(format!("{:?}", reff), "1234"); /// } /// /// /// #[derive(Debug, Copy, Clone)] /// #[repr(transparent)] /// struct BarRef<T>(StaticRef<T>); /// /// impl<T: 'static> BarRef<T> { /// pub const fn new(reff: &'static T) -> Self { /// Self(StaticRef::new(reff)) /// } /// } /// /// unsafe impl<T: 'static> GetPointerKind for BarRef<T> { /// type PtrTarget = T; /// type Kind = PK_Reference; /// } /// /// unsafe impl<T, U> CanTransmuteElement<U> for BarRef<T> /// where /// T: 'static, /// U: 'static, /// { /// type TransmutedPtr = BarRef<U>; /// /// unsafe fn transmute_element_(self) -> Self::TransmutedPtr { /// BarRef(self.0.transmute_element_()) /// } /// } /// /// unsafe impl<T: 'static> AsPtr for BarRef<T> { /// fn as_ptr(&self) -> *const T { /// self.0.as_ptr() /// } /// } /// /// /// ``` pub unsafe trait AsPtr: GetPointerKind { /// Gets a const raw pointer to the value that this points to. fn as_ptr(&self) -> *const Self::PtrTarget; /// Converts this pointer to an `RRef`. #[inline(always)] fn as_rref(&self) -> RRef<'_, Self::PtrTarget> { unsafe { RRef::from_raw(self.as_ptr()) } } } /// For getting a mutable raw pointer to the value that this points to. /// /// # Safety /// /// The implementor of this trait must return a pointer to the same data as /// `DerefMut::deref_mut`, /// without constructing a `&mut Self::Target` in `as_mut_ptr` /// (or any function it calls). /// /// The implementor of this trait must not override the defaulted methods. /// /// # Example /// /// ```rust /// use abi_stable::{ /// erased_types::interfaces::DEIteratorInterface, /// pointer_trait::{ /// PK_MutReference, /// AsPtr, AsMutPtr, CanTransmuteElement, GetPointerKind, TransmuteElement, /// }, /// sabi_types::RMut, /// DynTrait, /// }; /// /// fn main() { /// let mut iter = 0..=5; /// let reff: DynTrait<QuxMut<()>, DEIteratorInterface<_>> = /// DynTrait::from_ptr(QuxMut::new(&mut iter)).interface(DEIteratorInterface::NEW); /// /// assert_eq!(reff.collect::<Vec<u32>>(), [0, 1, 2, 3, 4, 5]); /// /// assert_eq!(iter.next(), None); /// } /// /// /// #[derive(Debug)] /// #[repr(transparent)] /// struct QuxMut<'a, T>(RMut<'a, T>); /// /// impl<'a, T> QuxMut<'a, T> { /// pub fn new(reff: &'a mut T) -> Self { /// Self(RMut::new(reff)) /// } /// } /// /// unsafe impl<T> GetPointerKind for QuxMut<'_, T> { /// type PtrTarget = T; /// type Kind = PK_MutReference; /// } /// /// unsafe impl<'a, T: 'a, U: 'a> CanTransmuteElement<U> for QuxMut<'a, T> { /// type TransmutedPtr = QuxMut<'a, U>; /// /// unsafe fn transmute_element_(self) -> Self::TransmutedPtr { /// QuxMut(self.0.transmute_element_()) /// } /// } /// /// unsafe impl<T> AsPtr for QuxMut<'_, T> { /// fn as_ptr(&self) -> *const T { /// self.0.as_ptr() /// } /// } /// /// unsafe impl<T> AsMutPtr for QuxMut<'_, T> { /// fn as_mut_ptr(&mut self) -> *mut T { /// self.0.as_mut_ptr() /// } /// } /// /// /// ``` pub unsafe trait AsMutPtr: AsPtr { /// Gets a mutable raw pointer to the value that this points to. fn as_mut_ptr(&mut self) -> *mut Self::PtrTarget; /// Converts this pointer to an `RRef`. #[inline(always)] fn as_rmut(&mut self) -> RMut<'_, Self::PtrTarget> { unsafe { RMut::from_raw(self.as_mut_ptr()) } } } /////////////////////////////////////////////////////////////////////////////// /// For owned pointers, allows extracting their contents separate from deallocating them. /// /// # Safety /// /// Implementors must: /// /// - Implement this trait such that `get_move_ptr` can be called before `drop_allocation`. /// /// - Not override `with_move_ptr` /// /// - Not override `in_move_ptr` /// /// # Example /// /// Implementing this trait for a Box-like type. /// /// ```rust /// use abi_stable::{ /// pointer_trait::{ /// CallReferentDrop, PK_SmartPointer, /// GetPointerKind, AsPtr, AsMutPtr, OwnedPointer, /// }, /// sabi_types::MovePtr, /// std_types::RString, /// StableAbi, /// }; /// /// use std::{ /// alloc::{self, Layout}, /// marker::PhantomData, /// mem::ManuallyDrop, /// }; /// /// /// fn main(){ /// let this = BoxLike::new(RString::from("12345")); /// /// let string: RString = this.in_move_ptr(|x: MovePtr<'_, RString>|{ /// MovePtr::into_inner(x) /// }); /// /// assert_eq!(string, "12345"); /// } /// /// /// #[repr(C)] /// #[derive(StableAbi)] /// pub struct BoxLike<T> { /// ptr: *mut T, /// /// dropper: unsafe extern "C" fn(*mut T, CallReferentDrop), /// /// _marker: PhantomData<T>, /// } /// /// /// impl<T> BoxLike<T>{ /// pub fn new(value:T)->Self{ /// let box_ = Box::new(value); /// /// Self{ /// ptr: Box::into_raw(box_), /// dropper: destroy_box::<T>, /// _marker:PhantomData, /// } /// } /// } /// /// unsafe impl<T> GetPointerKind for BoxLike<T> { /// type PtrTarget = T; /// type Kind = PK_SmartPointer; /// } /// /// unsafe impl<T> AsPtr for BoxLike<T> { /// fn as_ptr(&self) -> *const T { /// self.ptr /// } /// } /// /// unsafe impl<T> AsMutPtr for BoxLike<T> { /// fn as_mut_ptr(&mut self) -> *mut T { /// self.ptr /// } /// } /// /// unsafe impl<T> OwnedPointer for BoxLike<T> { /// unsafe fn get_move_ptr(this: &mut ManuallyDrop<Self>) -> MovePtr<'_,Self::PtrTarget>{ /// MovePtr::from_raw(this.ptr) /// } /// /// unsafe fn drop_allocation(this: &mut ManuallyDrop<Self>) { /// unsafe{ /// (this.dropper)(this.ptr, CallReferentDrop::No) /// } /// } /// } /// /// impl<T> Drop for BoxLike<T>{ /// fn drop(&mut self){ /// unsafe{ /// (self.dropper)(self.ptr, CallReferentDrop::Yes) /// } /// } /// } /// /// unsafe extern "C" fn destroy_box<T>(v: *mut T, call_drop: CallReferentDrop) { /// abi_stable::extern_fn_panic_handling! { /// let mut box_ = Box::from_raw(v as *mut ManuallyDrop<T>); /// if call_drop == CallReferentDrop::Yes { /// ManuallyDrop::drop(&mut *box_); /// } /// drop(box_); /// } /// } /// /// /// ``` pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// Gets a move pointer to the contents of this pointer. /// /// # Safety /// /// This function logically moves the owned contents out of this pointer, /// the only safe thing that can be done with the pointer afterwads /// is to call `OwnedPointer::drop_allocation`. /// /// <span id="get_move_ptr-example"></span> /// # Example /// /// ```rust /// use abi_stable::{ /// pointer_trait::OwnedPointer, /// sabi_types::MovePtr, /// std_types::{RBox, RVec}, /// rvec, StableAbi, /// }; /// /// use std::mem::ManuallyDrop; /// /// let mut this = ManuallyDrop::new(RBox::new(rvec![3, 5, 8])); /// /// // safety: /// // this is only called once, /// // and the `RVec` is never accessed again through the `RBox`. /// let moveptr: MovePtr<'_, RVec<u8>> = unsafe { OwnedPointer::get_move_ptr(&mut this) }; /// /// let vector: RVec<u8> = MovePtr::into_inner(moveptr); /// /// // safety: this is only called once, after all uses of `this` /// unsafe{ OwnedPointer::drop_allocation(&mut this); } /// /// assert_eq!(vector[..], [3, 5, 8]); /// /// ``` unsafe fn get_move_ptr(this: &mut ManuallyDrop<Self>) -> MovePtr<'_, Self::PtrTarget>; /// Deallocates the pointer without dropping its owned contents. /// /// Note that if `Self::get_move_ptr` has not been called this will /// leak the values owned by the referent of the pointer. /// /// # Safety /// /// This method must only be called once, /// since it'll deallocate whatever memory this pointer owns. /// /// # Example /// /// [`get_move_ptr` has an example](#get_move_ptr-example) that uses both that function /// and this one. unsafe fn drop_allocation(this: &mut ManuallyDrop<Self>); /// Runs a callback with the contents of this pointer, and then deallocates it. /// /// The pointer is deallocated even in the case that `func` panics /// /// # Example /// /// ```rust /// use abi_stable::{ /// pointer_trait::OwnedPointer, /// sabi_types::MovePtr, /// std_types::{RBox, RCow, RCowSlice}, /// }; /// /// use std::mem::ManuallyDrop; /// /// let this = ManuallyDrop::new(RBox::new(RCow::from_slice(&[13, 21, 34]))); /// /// let cow: RCowSlice<'static, u8> = OwnedPointer::with_move_ptr(this, |moveptr|{ /// MovePtr::into_inner(moveptr) /// }); /// /// assert_eq!(cow[..], [13, 21, 34]); /// /// ``` #[inline] fn with_move_ptr<F, R>(mut this: ManuallyDrop<Self>, func: F) -> R where F: FnOnce(MovePtr<'_, Self::PtrTarget>) -> R, { unsafe { let guard = DropAllocationMutGuard(&mut this); func(Self::get_move_ptr(guard.0)) } } /// Runs a callback with the contents of this pointer, and then deallocates it. /// /// The pointer is deallocated even in the case that `func` panics /// /// # Example /// /// ```rust /// use abi_stable::{ /// pointer_trait::OwnedPointer, /// sabi_types::MovePtr, /// std_types::RBox, /// }; /// /// let this = RBox::new(Foo(41)); /// /// let cow: Foo = this.in_move_ptr(|moveptr| MovePtr::into_inner(moveptr) ); /// /// assert_eq!(cow, Foo(41)); /// /// /// #[derive(Debug, PartialEq)] /// struct Foo(u32); /// /// ``` #[inline] fn in_move_ptr<F, R>(self, func: F) -> R where F: FnOnce(MovePtr<'_, Self::PtrTarget>) -> R, { unsafe { let mut guard = DropAllocationGuard(ManuallyDrop::new(self)); func(Self::get_move_ptr(&mut guard.0)) } } } struct DropAllocationGuard<T: OwnedPointer>(ManuallyDrop<T>); impl<T: OwnedPointer> Drop for DropAllocationGuard<T> { #[inline(always)] fn drop(&mut self) { unsafe { T::drop_allocation(&mut self.0) } } } struct DropAllocationMutGuard<'a, T: OwnedPointer>(&'a mut ManuallyDrop<T>); impl<T: OwnedPointer> Drop for DropAllocationMutGuard<'_, T> { #[inline(always)] fn drop(&mut self) { unsafe { T::drop_allocation(self.0) } } } /////////////////////////////////////////////////////////////////////////////// /// Trait for non-owning pointers that are shared-reference-like. /// /// # Safety /// /// As implied by `GetPointerKind<Kind = PK_Reference>`, /// implementors must be `#[repr(transparent)]` wrappers around references, /// and semantically act like references. pub unsafe trait ImmutableRef: Copy + GetPointerKind<Kind = PK_Reference> { /// Converts this pointer to a `NonNull`. #[inline(always)] fn to_nonnull(self) -> NonNull<Self::PtrTarget> { unsafe { Transmuter { from: self }.to } } /// Constructs this pointer from a `NonNull`. /// /// # Safety /// /// `from` must be a non-dangling pointer from a call to `to_nonnull` or /// `to_raw_ptr` on an instance of `Self` or a compatible pointer type. /// /// #[inline(always)] unsafe fn from_nonnull(from: NonNull<Self::PtrTarget>) -> Self { unsafe { Transmuter { from }.to } } /// Converts this pointer to a raw pointer. #[inline(always)] fn to_raw_ptr(self) -> *const Self::PtrTarget { unsafe { Transmuter { from: self }.to } } /// Constructs this pointer from a raw pointer. /// /// # Safety /// /// This has the same safety requirements as [`from_nonnull`](Self::from_nonnull), /// with the exception that null pointers are allowed. /// #[inline(always)] unsafe fn from_raw_ptr(from: *const Self::PtrTarget) -> Option<Self> { unsafe { Transmuter { from }.to } } } unsafe impl<T> ImmutableRef for T where T: Copy + GetPointerKind<Kind = PK_Reference> {} /// `const` equivalents of [`ImmutableRef`] methods. pub mod immutable_ref { use super::*; use crate::utils::const_transmute; /// Converts the `from` pointer to a `NonNull`. /// /// # Example /// /// ```rust /// use abi_stable::pointer_trait::immutable_ref; /// /// use std::ptr::NonNull; /// /// const X: NonNull<i8> = immutable_ref::to_nonnull(&3i8); /// unsafe { /// assert_eq!(*X.as_ref(), 3i8); /// } /// ``` /// pub const fn to_nonnull<T>(from: T) -> NonNull<T::PtrTarget> where T: GetPointerKind<Kind = PK_Reference>, { unsafe { const_transmute!(T, NonNull<T::PtrTarget>, from) } } /// Constructs this pointer from a `NonNull`. /// /// # Safety /// /// `from` must be a non-dangling pointer from a call to `to_nonnull` or /// `to_raw_ptr` on an instance of `T` or a compatible pointer type. /// /// # Example /// /// ```rust /// use abi_stable::pointer_trait::immutable_ref; /// /// const X: &u32 = unsafe { /// let nn = abi_stable::utils::ref_as_nonnull(&5u32); /// immutable_ref::from_nonnull(nn) /// }; /// assert_eq!(*X, 5u32); /// ``` /// pub const unsafe fn from_nonnull<T>(from: NonNull<T::PtrTarget>) -> T where T: GetPointerKind<Kind = PK_Reference>, { unsafe { const_transmute!(NonNull<T::PtrTarget>, T, from) } } /// Converts the `from` pointer to a raw pointer. /// /// # Example /// /// ```rust /// use abi_stable::pointer_trait::immutable_ref; /// /// unsafe { /// const X: *const u32 = immutable_ref::to_raw_ptr(&8u32); /// assert_eq!(*X, 8u32); /// } /// ``` /// pub const fn to_raw_ptr<T>(from: T) -> *const T::PtrTarget where T: GetPointerKind<Kind = PK_Reference>, { unsafe { const_transmute!(T, *const T::PtrTarget, from) } } /// Converts a raw pointer to an `T` pointer. /// /// # Safety /// /// This has the same safety requirements as [`from_nonnull`], /// with the exception that null pointers are allowed. /// /// # Example /// /// ```rust /// use abi_stable::pointer_trait::immutable_ref; /// /// unsafe { /// const X: Option<&u8> = unsafe { /// immutable_ref::from_raw_ptr(&13u8 as *const u8) /// }; /// assert_eq!(*X.unwrap(), 13u8); /// } /// ``` /// pub const unsafe fn from_raw_ptr<T>(from: *const T::PtrTarget) -> Option<T> where T: GetPointerKind<Kind = PK_Reference>, { unsafe { const_transmute!(*const T::PtrTarget, Option<T>, from) } } }
use super::cstate::*; #[derive(Debug)] pub enum FreeGroup<A> { One(A), And(Box<FreeGroup<A>>, Box<FreeGroup<A>>), Not(Box<FreeGroup<A>>), Empty, } impl<A> FreeGroup<A> { fn empty() -> FreeGroup<A> { FreeGroup::Empty } fn and(self, other: FreeGroup<A>) -> FreeGroup<A> { FreeGroup::And(Box::new(self), Box::new(other)) } fn not(self) -> FreeGroup<A> { match self { FreeGroup::Not(s) => *s, _ => FreeGroup::Not(Box::new(self)), } } fn one(item: A) -> FreeGroup<A> { FreeGroup::One(item) } // pub fn iter<'a>(&'a self) -> &'a impl Iterator<Item = A> { // self.iter_helper(false) // } // fn iter_helper<'a>(&'a self, negated: bool) -> &'a impl Iterator<Item=(&'a A, bool)> { // use std::iter::*; // match self { // FreeGroup::One(a) => &once((a, negated)), // FreeGroup::Not(inner) => &inner.iter_helper(!negated), // FreeGroup::Empty => &empty(), // FreeGroup::And(one, two) => &one.iter_helper(negated).chain(two.iter_helper(negated)) // } // } } pub(crate) type ClickAnaState = SpecialStateWrapper<MemoElem<iseq::Seq<i32>>>; pub trait Computer { type Action; type Output; fn apply(&mut self, action: Self::Action, positive: bool); fn compute_new_value(&mut self) -> Self::Output; } pub mod iseq { #[derive(Debug)] pub struct Seq<T>(Vec<Interval<T>>); use common::SizeOf; impl SizeOf for Seq<i32> { fn size_of(&self) -> u64 { std::mem::size_of::<Self>() as u64 } fn deep_size_of(&self) -> u64 { // TODO do a proper implementation here and find out if its even should have one self.size_of() } } impl<T> Default for Seq<T> { fn default() -> Self { Seq(Vec::new()) } } impl<T: std::fmt::Debug + std::cmp::Ord> super::Computer for Seq<T> { type Action = Action<T>; type Output = f64; fn apply(&mut self, action: Self::Action, positive: bool) { self.handle_helper(action, !positive) } fn compute_new_value(&mut self) -> Self::Output { let lens : Vec<usize> = self.complete_intervals().map(|i| i.elems.len()).collect(); let l = lens.len(); let sum : usize = lens.into_iter().sum(); sum as f64 / l as f64 } } #[derive(Debug)] pub struct Interval<T> { lower_bound: Option<T>, upper_bound: Option<T>, elems: Vec<T>, } impl<T: std::fmt::Debug> Interval<T> { fn bounded(lower: T, upper: T, elems: Vec<T>) -> Interval<T> where T: std::cmp::Ord, { debug_assert!(lower <= upper); Interval { lower_bound: Option::Some(lower), upper_bound: Option::Some(upper), elems: elems, } } fn with_upper_bound(upper: T, elems: Vec<T>) -> Interval<T> { Interval { lower_bound: Option::None, upper_bound: Option::Some(upper), elems: elems, } } fn with_lower_bound(lower: T, elems: Vec<T>) -> Interval<T> { Interval { lower_bound: Option::Some(lower), upper_bound: Option::None, elems: elems, } } fn with_bound(lower: bool, bound: T, elems: Vec<T>) -> Interval<T> { if lower { Self::with_lower_bound(bound, elems) } else { Self::with_upper_bound(bound, elems) } } fn compare_elem(&self, elem: &T) -> std::cmp::Ordering where T: std::cmp::Ord, { use std::cmp::Ordering; match (&self.lower_bound, &self.upper_bound) { (Option::Some(ref l), Option::Some(ref u)) => { if elem < l { Ordering::Greater } else if elem < u { Ordering::Equal } else { Ordering::Less } } (Option::Some(b), Option::None) | (Option::None, Option::Some(b)) => // TODO recheck if this is correct { b.cmp(elem) //elem.cmp(&b) } // Invariant: elems is never empty (if no bounds exist) (Option::None, Option::None) => { debug_assert!(self.elems.len() != 0); self.elems[0].cmp(elem) } } } fn has_lower_bound(&self) -> bool { self.lower_bound.is_some() } fn insert_elem(&mut self, elem: T) where T: std::cmp::Ord, { debug_assert!(self.is_in_bounds(&elem)); self.elems.push(elem); } fn remove_element(&mut self, elem: &T) -> bool where T: std::cmp::Eq, { self.elems .iter() .position(|e| e == elem) .map(|p| self.elems.remove(p)) .is_some() } pub fn has_upper_bound(&self) -> bool { self.upper_bound.is_some() } pub fn is_closed(&self) -> bool { self.has_upper_bound() && self.has_lower_bound() } fn new(elems: Vec<T>) -> Interval<T> { Interval { elems: elems, upper_bound: Option::None, lower_bound: Option::None, } } /// Split off all elements which are larger (`true`) or smaller /// (`false`) than the provided pivot element. The larger section is /// always inclusive with respect to the pivot. fn steal_elems(&mut self, splitter: &T, larger: bool) -> Vec<T> where T: std::cmp::Ord, { self.elems.sort(); // We can collapse here, because in every case the index points to the // element that should be the first element in v2. let idx = collapse_result(self.elems.binary_search(splitter)); let mut v2 = self.elems.split_off(idx); if !larger { std::mem::swap(&mut self.elems, &mut v2); } v2 } fn adjust_upper_bound(&mut self, bound: T) -> Option<Interval<T>> where T: std::cmp::Ord, { self.adjust_bound(bound, false) } fn adjust_lower_bound(&mut self, bound: T) -> Option<Interval<T>> where T: std::cmp::Ord, { self.adjust_bound(bound, true) } fn get_bound_mut<'a>(&'a mut self, lower: bool) -> &'a mut Option<T> where T: 'a, { if lower { &mut self.lower_bound } else { &mut self.upper_bound } } fn get_bound<'a>(&'a self, lower: bool) -> &'a Option<T> where T: 'a, { if lower { &self.lower_bound } else { &self.upper_bound } } pub fn is_in_lower_bound(&self, item: &T) -> bool where T: std::cmp::Ord, { self.lower_bound.as_ref().map_or(true, |b| b <= item) } pub fn is_in_upper_bound(&self, item: &T) -> bool where T: std::cmp::Ord, { self.upper_bound.as_ref().map_or(true, |b| item <= b) } pub fn is_in_bounds(&self, item: &T) -> bool where T: std::cmp::Ord, { self.is_in_upper_bound(item) && self.is_in_lower_bound(item) } fn adjust_bound(&mut self, bound: T, lower: bool) -> Option<Interval<T>> where T: std::cmp::Ord, T: std::fmt::Debug, { debug_assert!( if lower { self.is_in_upper_bound(&bound) } else { self.is_in_lower_bound(&bound) }, "The provided {} bound {:?} is invalid in \n{}", if lower { "lower" } else { "upper" }, bound, self.draw() ); let new_bound_is_larger = self .get_bound(lower) .as_ref() .map(|a| if lower { a >= &bound } else { a <= &bound }) .unwrap_or(false); let other_elements = if new_bound_is_larger { Vec::new() } else { self.steal_elems(&bound, !lower) }; let old_bound = self.get_bound_mut(lower).replace(bound); if other_elements.is_empty() && old_bound.is_none() { Option::None } else { let mut new_elem = Interval::new(other_elements); old_bound.map(|b| new_elem.get_bound_mut(lower).replace(b)); Option::Some(new_elem) } } fn needs_cleanup(&self) -> bool { !self.has_lower_bound() && !self.has_upper_bound() && self.elems.is_empty() } #[cfg(test)] pub fn bounds_are_valid(&self) -> bool where T: std::cmp::Ord, { self.lower_bound .as_ref() .map_or(true, |l| self.is_in_upper_bound(l)) } #[cfg(test)] pub fn assert_is_left_of(&self, other: &Interval<T>) where T: std::cmp::Ord + std::fmt::Debug, { if let Option::Some(b1) = self.lower_bound.as_ref() { assert!( !other.has_lower_bound() || !other.is_in_lower_bound(b1), "lower bound is wrong between\n{}\n{}", self.draw(), other.draw() ); assert!( !other.has_upper_bound() || other.is_in_upper_bound(b1), "lower bound is wrong between\n{}\n{}", self.draw(), other.draw() ); } if let Option::Some(b1) = self.upper_bound.as_ref() { assert!( !other.has_lower_bound() || !other.is_in_lower_bound(b1), "upper bound is wrong between\n{}\n{}", self.draw(), other.draw() ); assert!( !other.has_upper_bound() || other.is_in_upper_bound(b1), "upper bound is wrong between \n{}\n{}", self.draw(), other.draw() ); } } #[cfg(test)] pub fn assert_no_common_element_with(&self, other: &Interval<T>) where T: std::cmp::PartialEq + std::fmt::Debug, { for e in self.elems.iter() { for e2 in other.elems.iter() { assert!( e != e2, "Element {:?} is the same in \n{}\n{}", e, self.draw(), other.draw() ); } } } #[cfg(test)] pub fn assert_all_elems_in_bound(&self) where T: std::cmp::Ord, { for elem in self.elems.iter() { assert!( self.is_in_bounds(elem), "Element {:?} is out of bounds\n{}", elem, self.draw() ); } } fn draw(&self) -> String where T: std::fmt::Debug, { format!( "[{},{}) <{}>", self.lower_bound .as_ref() .map_or("...".to_string(), |a| format!("{:?}", a)), self.upper_bound .as_ref() .map_or("...".to_string(), |a| format!("{:?}", a)), format!("{:?}", self.elems) ) } } fn collapse_result<T>(r: Result<T, T>) -> T { match r { Ok(t) | Err(t) => t, } } #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub enum Action<B> { Open(B), Close(B), Insert(B), } /// Split the elements vector into two parts on an element `e` such that all /// elements of of the first vector are strictly smaller than `e` and the /// elements of the second larger or equal to `e`. use super::FreeGroup; impl<T: std::cmp::Ord + std::fmt::Debug> Seq<T> { #[cfg(test)] fn from_intervals(intervals: Vec<Interval<T>>) -> Seq<T> { Seq(intervals) } pub fn new() -> Seq<T> { Seq(Vec::new()) } pub fn handle(&mut self, action: FreeGroup<Action<T>>) where T: std::fmt::Debug, { match dbg!(action) { FreeGroup::One(ac) => self.handle_helper(ac, false), FreeGroup::Not(n) => match *n { FreeGroup::One(ac) => self.handle_helper(ac, true), _ => unimplemented!(), }, _ => unimplemented!(), } } pub fn handle_helper(&mut self, action: Action<T>, negate: bool) { match action { Action::Open(i) => { if !negate { self.open_interval(i) } else { self.reverse_open_interval(&i) } } Action::Close(i) => { if !negate { self.close_interval(i) } else { self.reverse_close_interval(&i) } } Action::Insert(i) => { if !negate { self.insert_element(i) } else { self.remove_element(&i) } } } } fn open_interval(&mut self, bound: T) { self.expand_interval(bound, true) } fn reverse_open_interval(&mut self, bound: &T) { self.contract_interval(bound, true) } fn close_interval(&mut self, bound: T) { self.expand_interval(bound, false) } fn reverse_close_interval(&mut self, bound: &T) { self.contract_interval(bound, false) } fn insert_element(&mut self, elem: T) { match self.find_target_index(&elem) { Ok(idx) => self.0[idx].insert_elem(elem), Err(idx) => self.0.insert(idx, Interval::new(vec![elem])), } } fn remove_element(&mut self, elem: &T) { if let Result::Ok(idx) = self.find_target_index(elem) { let cleanup_necessary = { let ref mut target = self.0[idx]; debug_assert!(target.remove_element(elem)); target.needs_cleanup() }; if cleanup_necessary { self.0.remove(idx); } } else { panic!("Element-to-remove is not present"); } } fn complete_intervals<'a>(&'a self) -> impl Iterator<Item = &'a Interval<T>> { self.0.iter().filter(|e| e.is_closed()) } fn contract_interval(&mut self, bound: &T, lower: bool) { let idx = self.find_exact_bound(bound, lower); let neighbor = if lower { idx - 1 } else { idx + 1 }; let do_cleanup = { let ref mut target = self.0[idx]; let removed = if lower { target.lower_bound.take() } else { target.upper_bound.take() }; debug_assert!(&removed.unwrap() == bound); target.needs_cleanup() }; if do_cleanup { self.0.remove(idx); } else if self .0 .get(neighbor) .map_or(false, |b| b.get_bound(!lower).is_none()) { let mut target = self.0.remove(idx); let ref mut other = self.0[if lower { neighbor } else { neighbor - 1 }]; other.elems.append(&mut target.elems); std::mem::swap(other.get_bound_mut(!lower), target.get_bound_mut(!lower)) } } fn expand_interval(&mut self, bound: T, lower: bool) { #[cfg(test)] eprintln!( "Expanding intervals with {} bound {:?}", if lower { "lower" } else { "upper" }, &bound ); match self.find_target_index(&bound) { Ok(idx) => { let ref mut target = self.0[idx]; eprintln!("Targeting {}", target.draw()); target.adjust_bound(bound, lower).map(|new_node| { let iidx = if lower { idx } else { idx + 1 }; eprintln!( "Inserting leftover interval at index {}\n{}", iidx, new_node.draw() ); self.0.insert(iidx, new_node) }); } Err(idx) => { eprintln!("Inserting new interval at {}", idx); self.0.insert( idx, if lower { Interval::with_lower_bound(bound, Vec::new()) } else { Interval::with_upper_bound(bound, Vec::new()) }, ) } } } /// Find an exact interval index with this bound fn find_exact_bound(&self, bound: &T, lower: bool) -> usize { self.0 .binary_search_by(|e| { if (if lower { e.lower_bound.as_ref().map_or(false, |b| b == bound) } else { e.upper_bound.as_ref().map_or(false, |b| b == bound) }) { std::cmp::Ordering::Equal } else { e.compare_elem(bound) } }) .expect( "Invariant broken, a bound to be removed should be present in the sequence.", ) } /// Finds an index where new elements should be inserted to preserve /// ordering. If the result is `Ok` the index points to a *closed* /// interval that contains the element. For `Err` there may be open /// intervals before or after the index that *can* contain the element fn find_insert_index(&self, idx: &T) -> Result<usize, usize> { self.0.binary_search_by(|e| e.compare_elem(idx)) } fn prev<'a>(&'a self, idx: usize) -> Option<&'a Interval<T>> { if idx == 0 { Option::None } else { self.get(idx - 1) } } fn get<'a>(&'a self, idx: usize) -> Option<&'a Interval<T>> { self.0.get(idx) } /// This is the more comprehensive version of `find_insert_index`. The /// `Ok` value here may point either to a bounded interval that should /// contain the element or the only available partially bounded interval /// that should contain the element. An `Err` value indicates that no /// suitable interval was found and a new one will have to be created to /// contain the element. fn find_target_index(&self, elem: &T) -> Result<usize, usize> { // An important invariant is that there is only ever one partially // bounded interval. A situation like [b1, ...), (..., b2] cannot // happen, because b2 would have become the upper bound for the // first interval and vice versa. self.find_insert_index(elem).or_else(|idx| { let candidates = (self.prev(idx), self.get(idx)); debug_assert!( candidates.0.map_or(true, |e| e.has_upper_bound()) || candidates.1.map_or(true, |e| e.has_lower_bound()), "Invariant broken, both intervals lack bounds." ); match candidates { (Option::Some(t), _) if !t.has_upper_bound() => Ok(idx - 1), (_, Option::Some(t)) if !t.has_lower_bound() => Ok(idx), _ => Err(idx), } }) } #[cfg(test)] pub fn check_invariants(&self) where T: std::cmp::Ord + std::fmt::Debug, { for (idx, iv) in self.0.iter().enumerate() { assert!(iv.bounds_are_valid(), "bounds invalid"); assert!( iv.has_upper_bound() || self.0.get(idx + 1).map_or(true, Interval::has_lower_bound), "Two open intervals next to each other" ); iv.assert_all_elems_in_bound(); for iv2 in self.0[idx + 1..].iter() { iv.assert_is_left_of(iv2); iv.assert_no_common_element_with(iv2); } } } pub fn draw(&self) -> String where T: std::fmt::Debug, { format!( "Seq({})\n{}", self.0.len(), self.0 .iter() .map(Interval::draw) .collect::<Vec<String>>() .join("\n") ) } } #[cfg(test)] mod tests { use super::*; use rand::random; use std::collections::HashSet; #[test] fn test_iseq_insert() { let mut seq = Seq::new(); seq.insert_element(1); println!("{}", seq.draw()); seq.insert_element(2); seq.check_invariants(); println!("{}", seq.draw()); } #[test] fn test_iseq_action_around_closed_interval() { for t in &[(1, 2), (-2, -1)] { let mut seq = Seq::new(); println!("\nTesting {:?}", &t); let (b1, b2): &(i32, i32) = t; seq.open_interval(b1); seq.close_interval(b2); seq.check_invariants(); seq.open_interval(&-3); seq.check_invariants(); seq.close_interval(&3); seq.check_invariants(); } } #[test] fn test_iseq_double_close() { for t in &[(1, 2), (2, 1), (-1, -2), (-2, -1)] { let (b1, b2): &(i32, i32) = t; println!("\nTesting {:?}", *t); let mut seq = Seq::new(); seq.close_interval(b1); seq.close_interval(b2); println!("{}", seq.draw()); seq.check_invariants(); } } #[test] fn test_interval_compare() { use std::cmp::Ordering; { let iv = Interval::<i32>::bounded(1, 10, Vec::new()); use std::cmp::Ordering; assert!(iv.compare_elem(&0) == Ordering::Greater); assert!(iv.compare_elem(&2) == Ordering::Equal); assert!(iv.compare_elem(&11) == Ordering::Less); } { let iv = Interval::<i32>::with_lower_bound(1, Vec::new()); assert!(iv.compare_elem(&0) == Ordering::Greater); // Not sure this should be equal assert!(iv.compare_elem(&1) == Ordering::Equal); assert!(iv.compare_elem(&2) == Ordering::Less); } } // #[test] // fn test_search_index() { // let seq = Seq::from_intervals( // vec![Interval::bounded(1,2), Interval::bounded()] // ); // } #[test] fn test_iseq_random() { let mut taken = HashSet::new(); let mut seq = Seq::new(); for i in 0..100 { let ac = random_action(); if taken.insert(ac.clone()) { seq.handle(FreeGroup::one(ac)); seq.check_invariants(); } } for i in 0..100 { let _: u32 = i; if i % 2 == 0 { let ac = random_action(); if taken.insert(ac.clone()) { seq.handle(FreeGroup::one(ac)); } } else { let ac = taken.drain().next().unwrap(); seq.handle(FreeGroup::not(FreeGroup::one(ac))); } seq.check_invariants(); } for ac in taken.drain() { seq.handle(FreeGroup::not(FreeGroup::one(ac))); seq.check_invariants(); } } fn random_action() -> Action<i32> { let v = random(); match random::<u8>() % 3 { 0 => Action::Open(v), 1 => Action::Close(v), 2 => Action::Insert(v), i => panic!("{}", i), } } } }
#[cfg(test)] mod tests { //若使用泛型,必须提供类型注解来表明希望使用 Iterator 的哪一个实现 //关联类型更通用 pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; } }
mod file_data; mod file_database; mod file_database_builder; mod recursive_path; mod serde_types; pub use self::file_data::*; pub use self::file_database::*; pub use self::file_database_builder::*; pub use self::recursive_path::*; pub use self::serde_types::*; // ex: noet ts=4 filetype=rust
use solana_program::program_error::ProgramError; use std::mem::size_of; #[repr(C)] #[derive(Debug)] pub enum AuctionInstruction { CreateAuction { start_price: u64 }, Bidding { price: u64, decimals: u8 }, CloseAuction, } impl AuctionInstruction { pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> { let (&tag, rest) = input .split_first() .ok_or(ProgramError::InvalidInstructionData)?; Ok(match tag { 0 => Self::CreateAuction { start_price: { let mut fixed_data = [0u8; 8]; fixed_data.copy_from_slice(&rest[..8]); u64::from_le_bytes(fixed_data) }, }, 1 => Self::Bidding { price: { let mut fixed_data = [0u8; 8]; fixed_data.copy_from_slice(&rest[..8]); u64::from_le_bytes(fixed_data) }, decimals: rest[8], }, 2 => Self::CloseAuction, _ => return Err(ProgramError::InvalidInstructionData.into()), }) } pub fn pack(&self) -> Vec<u8> { let mut buf = Vec::with_capacity(size_of::<Self>()); match self { &Self::CreateAuction { start_price } => { buf.push(0); buf.extend_from_slice(&start_price.to_le_bytes()); } &Self::Bidding { price, decimals } => { buf.push(1); buf.extend_from_slice(&price.to_le_bytes()); buf.extend_from_slice(&decimals.to_le_bytes()); } Self::CloseAuction => buf.push(2), }; buf } }
#[macro_use] extern crate quote; extern crate proc_macro; extern crate syn; mod native; use syn::{ parse::{Parse, ParseStream}, parse_macro_input, parse_quote, FnArg, ItemFn, Result, Signature, }; #[proc_macro] pub fn export_native(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream { native::export_native(tokens) } #[proc_macro] pub fn export(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream { let Exported::Fns(mut fns) = parse_macro_input!(tokens as Exported); if cfg!(debug_assertions) { return quote!(#(#fns)*).into(); }; for f in fns.iter_mut() { replace_values_with_pointers(f); return_null(f); } quote!(#(#fns)*).into() } enum Exported { Fns(Vec<syn::ItemFn>), } impl Parse for Exported { fn parse(input: ParseStream) -> Result<Self> { Ok(Exported::Fns( syn::Block::parse_within(input) .unwrap() .iter() .cloned() .filter_map(|stmt| { if let syn::Stmt::Item(syn::Item::Fn(f)) = stmt { Some(f) } else { None } }) .collect::<Vec<syn::ItemFn>>(), )) } } fn return_null<'a>(f: &'a mut ItemFn) { if f.sig.output == parse_quote!() { f.sig.output = parse_quote!(-> wasm_rpc::Pointer); f.block.stmts.push(syn::Stmt::Expr(parse_quote!( wasm_rpc::serde_cbor::Value::Null ))); } } fn replace_values_with_pointers(f: &mut ItemFn) { let ItemFn { sig: Signature { inputs, output, .. }, block, .. } = f.clone(); let pointers: Vec<syn::ExprMethodCall> = f .sig .inputs .clone() .into_iter() .map(&pointer_to_value) .collect(); f.attrs.push(parse_quote!(#[no_mangle])); f.block = parse_quote!({wasm_rpc::pointer::from_value(&(|#inputs|#output #block)(#(#pointers),*))}); f.sig.inputs = f .sig .inputs .iter() .cloned() .map(|input| { if let FnArg::Typed(mut pat) = input { pat.ty = parse_quote!(wasm_rpc::Pointer); FnArg::Typed(pat) } else { input } }) .collect(); f.sig.output = parse_quote!(-> wasm_rpc::Pointer); } fn pointer_to_value(input: FnArg) -> syn::ExprMethodCall { if let FnArg::Typed(syn::PatType { pat, .. }) = input { parse_quote!(wasm_rpc::pointer::to_value(#pat).unwrap()) } else { parse_quote!(#input) } }
use crate::{ core::{ visitor::{ Visitor, VisitResult, Visit }, math::{ Rect, mat4::Mat4, vec2::Vec2, }, }, scene::base::{ Base, AsBase, BaseBuilder, }, }; #[derive(Clone)] pub struct Camera { base: Base, fov: f32, z_near: f32, z_far: f32, viewport: Rect<f32>, view_matrix: Mat4, projection_matrix: Mat4, enabled: bool, } impl AsBase for Camera { fn base(&self) -> &Base { &self.base } fn base_mut(&mut self) -> &mut Base { &mut self.base } } impl Default for Camera { fn default() -> Camera { CameraBuilder::new(BaseBuilder::new()).build() } } impl Visit for Camera { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.fov.visit("Fov", visitor)?; self.z_near.visit("ZNear", visitor)?; self.z_far.visit("ZFar", visitor)?; self.viewport.visit("Viewport", visitor)?; self.base.visit("Base", visitor)?; self.enabled.visit("Enabled", visitor)?; visitor.leave_region() } } impl Camera { #[inline] pub fn calculate_matrices(&mut self, frame_size: Vec2) { let pos = self.base.global_position(); let look = self.base.look_vector(); let up = self.base.up_vector(); if let Some(view_matrix) = Mat4::look_at(pos, pos + look, up) { self.view_matrix = view_matrix; } else { self.view_matrix = Mat4::IDENTITY; } let viewport = self.viewport_pixels(frame_size); self.projection_matrix = Mat4::perspective(self.fov, viewport.w as f32 / viewport.h as f32, self.z_near, self.z_far); } #[inline] pub fn viewport_pixels(&self, frame_size: Vec2) -> Rect<i32> { Rect { x: (self.viewport.x * frame_size.x) as i32, y: (self.viewport.y * frame_size.y) as i32, w: (self.viewport.w * frame_size.x) as i32, h: (self.viewport.h * frame_size.y) as i32, } } #[inline] pub fn view_projection_matrix(&self) -> Mat4 { self.projection_matrix * self.view_matrix } #[inline] pub fn projection_matrix(&self) -> Mat4 { self.projection_matrix } #[inline] pub fn view_matrix(&self) -> Mat4 { self.view_matrix } #[inline] pub fn inv_view_matrix(&self) -> Result<Mat4, ()> { self.view_matrix.inverse() } #[inline] pub fn set_z_far(&mut self, z_far: f32) -> &mut Self { self.z_far = z_far; self } #[inline] pub fn z_far(&self) -> f32 { self.z_far } #[inline] pub fn set_z_near(&mut self, z_near: f32) -> &mut Self { self.z_near = z_near; self } #[inline] pub fn z_near(&self) -> f32 { self.z_near } /// In radians #[inline] pub fn set_fov(&mut self, fov: f32) -> &mut Self { self.fov = fov; self } #[inline] pub fn fov(&self) -> f32 { self.fov } #[inline] pub fn is_enabled(&self) -> bool { self.enabled } #[inline] pub fn set_enabled(&mut self, enabled: bool) -> &mut Self { self.enabled = enabled; self } } pub struct CameraBuilder { base_builder: BaseBuilder, fov: f32, z_near: f32, z_far: f32, viewport: Rect<f32>, enabled: bool, } impl CameraBuilder { pub fn new(base_builder: BaseBuilder) -> Self { Self { enabled: true, base_builder, fov: 75.0f32.to_radians(), z_near: 0.025, z_far: 2048.0, viewport: Rect { x: 0.0, y: 0.0, w: 1.0, h: 1.0 }, } } pub fn with_fov(mut self, fov: f32) -> Self { self.fov = fov; self } pub fn with_z_near(mut self, z_near: f32) -> Self { self.z_near = z_near; self } pub fn with_z_far(mut self, z_far: f32) -> Self { self.z_far = z_far; self } pub fn with_viewport(mut self, viewport: Rect<f32>) -> Self { self.viewport = viewport; self } pub fn enabled(mut self, enabled: bool) -> Self { self.enabled = enabled; self } pub fn build(self) -> Camera { Camera { enabled: self.enabled, base: self.base_builder.build(), fov: self.fov, z_near: self.z_near, z_far: self.z_far, viewport: self.viewport, // No need to calculate these matrices - they'll be automatically // recalculated before rendering. view_matrix: Mat4::IDENTITY, projection_matrix: Mat4::IDENTITY, } } }
use rustc_lint::LateLintPass; use rustc_session::{declare_lint, declare_lint_pass}; declare_lint! { /// **What it does:** /// /// **Why is this bad?** /// /// **Known problems:** None. /// /// **Example:** /// /// ```rust /// // example code where a warning is issued /// ``` /// Use instead: /// ```rust /// // example code that does not raise a warning /// ``` pub FILL_ME_IN, Warn, "description goes here" } declare_lint_pass!(FillMeIn => [FILL_ME_IN]); impl<'hir> LateLintPass<'hir> for FillMeIn { // A list of things you might check can be found here: // https://doc.rust-lang.org/stable/nightly-rustc/rustc_lint/trait.LateLintPass.html }
//! The `info` subcommand: shows metadata about the git-global installation. use chrono::Duration; use std::path::PathBuf; use std::time::SystemTime; use config::Config; use errors::Result; use report::Report; /// Returns the age of a file in terms of days, hours, minutes, and seconds. fn get_age(filename: PathBuf) -> Option<String> { filename .metadata() .ok() .and_then(|metadata| metadata.modified().ok()) .and_then(|mtime| SystemTime::now().duration_since(mtime).ok()) .and_then(|dur| Duration::from_std(dur).ok()) .and_then(|dur| { let days = dur.num_days(); let hours = dur.num_hours() - (days * 24); let mins = dur.num_minutes() - (days * 24 * 60) - (hours * 60); let secs = dur.num_seconds() - (days * 24 * 60 * 60) - (hours * 60 * 60) - (mins * 60); Some(format!("{}d, {}h, {}m, {}s", days, hours, mins, secs)) }) } /// Gathers metadata about the git-global installation. pub fn execute(mut config: Config) -> Result<Report> { let repos = config.get_repos(); let mut report = Report::new(&repos); let version = format!("{}", crate_version!()); // beginning of underline: git-global x.x.x let mut underline = format!("==========="); for _ in 0..version.len() { underline.push('='); } report.add_message(format!("git-global {}", version)); report.add_message(underline); report.add_message(format!("Number of repos: {}", repos.len())); report.add_message(format!("Base directory: {}", config.basedir.display())); report.add_message(format!("Cache file: {}", config.cache_file.display())); if let Some(age) = get_age(config.cache_file) { report.add_message(format!("Cache file age: {}", age)); } report.add_message(format!("Ignored patterns:")); for pat in config.ignored_patterns.iter() { report.add_message(format!(" {}", pat)); } report.add_message(format!("Default command: {}", config.default_cmd)); report.add_message(format!("Show untracked: {}", config.show_untracked)); Ok(report) }
pub struct Solution; impl Solution { pub fn contains_duplicate(nums: Vec<i32>) -> bool { let mut nums = nums; nums.sort(); for i in 1..nums.len() { if nums[i - 1] == nums[i] { return true; } } return false; } } #[test] fn test0217() { fn case(nums: Vec<i32>, want: bool) { let got = Solution::contains_duplicate(nums); assert_eq!(got, want); } case(vec![1, 2, 3, 1], true); case(vec![1, 2, 3, 4], false); case(vec![1, 1, 1, 3, 3, 4, 3, 2, 4, 2], true); }
//! types and functions for signing operations on the `secp256r1` curve. use libc::{uint8_t,c_int}; /// size of curve. const BYTES: usize = 32; /// a public ecc key on the `secp256r1` curve. pub struct Public([u8;BYTES+1]); impl_newtype_bytearray_ext!(Public,BYTES+1); impl_serhex_bytearray!(Public,BYTES+1); /// a secret ecc key on the `secp256r1` curve. #[derive(Debug,Default,PartialEq,Eq)] pub struct Secret([u8;BYTES]); impl_newtype_bytearray!(Secret,BYTES); impl_serhex_bytearray!(Secret,BYTES); /// an ecc signature on the `secp256r1` curve. pub struct Signature([u8;BYTES*2]); impl_newtype_bytearray_ext!(Signature,BYTES*2); impl_serhex_bytearray!(Signature,BYTES*2); /// generate a new ecc keypair. pub fn keygen(public: &mut Public, secret: &mut Secret) -> Result<(),()> { let rslt = unsafe { ecc_make_key(&mut public.0 as *mut [u8;BYTES+1], &mut secret.0 as *mut [u8;BYTES]) }; match rslt { 1 => Ok(()), _ => Err(()) } } /// generate a new ecc signature. pub fn sign(key: &Secret, msg: &[u8;BYTES], sig: &mut Signature) -> Result<(),()> { let rslt = unsafe { ecdsa_sign(&key.0 as *const [u8;BYTES], msg as *const [u8;BYTES], &mut sig.0 as *mut [u8;BYTES*2]) }; match rslt { 1 => Ok(()), _ => Err(()) } } /// verify an ecc signature. pub fn verify(key: &Public, msg: &[u8;BYTES], sig: &Signature) -> Result<(),()> { let rslt = unsafe { ecdsa_verify(&key.0 as *const [u8;BYTES+1], msg as *const [u8;BYTES], &sig.0 as *const [u8;BYTES*2]) }; match rslt { 1 => Ok(()), _ => Err(()) } } // ffi function defs. #[link(name = "p256", kind = "static")] extern { // int ecc_make_key(uint8_t p_publicKey[ECC_BYTES+1], uint8_t p_privateKey[ECC_BYTES]); fn ecc_make_key(p_publicKey: *mut [uint8_t; BYTES+1], p_privateKey: *mut [uint8_t;BYTES]) -> c_int; // int ecdsa_sign(const uint8_t p_privateKey[ECC_BYTES], const uint8_t p_hash[ECC_BYTES], uint8_t p_signature[ECC_BYTES*2]); fn ecdsa_sign(p_privateKey: *const [uint8_t;BYTES], p_hash: *const [uint8_t; BYTES], p_signature: *mut [uint8_t; BYTES * 2]) -> c_int; // int ecdsa_verify(const uint8_t p_publicKey[ECC_BYTES+1], const uint8_t p_hash[ECC_BYTES], const uint8_t p_signature[ECC_BYTES*2]); fn ecdsa_verify(p_publicKey: *const [uint8_t;BYTES+1], p_hash: *const [uint8_t;BYTES], p_signature: *const [uint8_t;BYTES*2]) -> c_int; } #[cfg(test)] mod tests { use secp256r1::{BYTES,Public,Secret,Signature,keygen,sign,verify}; #[test] fn keygen_ok() { let mut public = Public::default(); let mut secret = Secret::default(); keygen(&mut public, &mut secret).unwrap(); assert!(public != Public::default()); assert!(secret != Secret::default()); } #[test] fn signing_ok() { let mut public = Public::default(); let mut secret = Secret::default(); keygen(&mut public, &mut secret).unwrap(); let mut sig = Signature::default(); let mut msg = [0u8;BYTES]; msg[0] = 1; msg[2] = 3; msg[4] = 5; sign(&secret,&msg,&mut sig).unwrap(); verify(&public,&msg,&sig).unwrap(); } #[test] #[should_panic] fn signing_err() { let mut public = Public::default(); let mut secret = Secret::default(); keygen(&mut public, &mut secret).unwrap(); let mut sig = Signature::default(); let mut msg = [0u8;BYTES]; msg[0] = 1; msg[2] = 3; msg[4] = 5; sign(&secret,&msg,&mut sig).unwrap(); msg[0] ^= 0xff; verify(&public,&msg,&sig).unwrap(); } #[test] fn precomputed_ok() { let public = Public::from([ 0x03, 0x94, 0x58, 0xdd, 0x87, 0xbd, 0xb4, 0x7d, 0xe4, 0x8b, 0xb9, 0x47, 0x0b, 0x8c, 0x25, 0xcb, 0x5f, 0x94, 0x06, 0x90, 0x7c, 0x45, 0xd8, 0x65, 0x26, 0x5a, 0xea, 0x38, 0xd6, 0xb0, 0xbb, 0x37, 0x80 ]); let secret = Secret::from([ 0xab, 0x73, 0x28, 0xe4, 0xbd, 0x9b, 0xea, 0xd4, 0x75, 0xdd, 0x7c, 0xd8, 0x99, 0xc1, 0xba, 0x91, 0x18, 0xc8, 0xb1, 0xfc, 0xb9, 0x0c, 0x93, 0xa8, 0x85, 0x85, 0x37, 0xd3, 0x6e, 0x3c, 0x1e, 0x98 ]); let mut sig = Signature::default(); let mut msg = [0u8;BYTES]; msg[6] = 7; msg[8] = 9; msg[10] = 11; sign(&secret,&msg,&mut sig).unwrap(); verify(&public,&msg,&sig).unwrap(); } #[test] #[should_panic] fn precomputed_err() { let public = Public::from([ 0x03, 0x94, 0x58, 0xdd, 0x87, 0xbd, 0xb4, 0x7d, 0xe4, 0x8b, 0xb9, 0x47, 0x0b, 0x8c, 0x25, 0xcb, 0x5f, 0x94, 0x06, 0x90, 0x7c, 0x45, 0xd8, 0x65, 0x26, 0x5a, 0xea, 0x38, 0xd6, 0xb0, 0xbb, 0x37, 0x80 ]); let secret = Secret::from([ 0xab, 0x73, 0x28, 0xe4, 0xbd, 0x9b, 0xea, 0xd4, 0x75, 0xdd, 0x7c, 0xd8, 0x99, 0xc1, 0xba, 0x91, 0x18, 0xc8, 0xb1, 0xfc, 0xb9, 0x0c, 0x93, 0xa8, 0x85, 0x85, 0x37, 0xd3, 0x6e, 0x3c, 0x1e, 0x98 ]); let mut sig = Signature::default(); let mut msg = [0u8;BYTES]; msg[6] = 7; msg[8] = 9; msg[10] = 11; sign(&secret,&msg,&mut sig).unwrap(); msg[10] ^= 0xff; verify(&public,&msg,&sig).unwrap(); } }
use rust_src::{Dir, DOWN, LEFT, RIGHT, UP}; #[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)] #[repr(C)] pub struct Point { pub x: usize, pub y: usize, } impl Point { pub fn new(x: usize, y: usize) -> Point { Point { x, y } } pub fn dist(&self, other: &Point) -> usize { ((self.x as i32 - other.x as i32).abs() + (self.y as i32 - other.y as i32).abs()) as usize } pub fn get_in_dir(&self, dir: Dir) -> Option<Point> { self.jump_in_dir(dir, 1) } pub fn jump_in_dir(&self, dir: Dir, distance: usize) -> Option<Point> { match dir { UP => if self.y >= distance { Some(Point::new(self.x, self.y - distance)) } else { None }, DOWN => if self.y + distance < ::height() { Some(Point::new(self.x, self.y + distance)) } else { None }, LEFT => if self.x >= distance { Some(Point::new(self.x - distance, self.y)) } else { None }, RIGHT => if self.x + distance < ::width() { Some(Point::new(self.x + distance, self.y)) } else { None }, _ => None, } } pub fn get_dir_to(&self, other: Point) -> Dir { if other.x > self.x { return Dir::RIGHT; } else if other.x < self.x { return Dir::LEFT; } else if other.y > self.y { return Dir::DOWN; } else { return Dir::UP; } } pub fn neighbors(&self) -> Neighbors { Neighbors::new(*self) } } #[derive(Debug)] pub struct Neighbors(Point, usize); impl Neighbors { pub fn new(point: Point) -> Neighbors { Neighbors(point, 0) } } impl ::std::iter::Iterator for Neighbors { type Item = Point; fn next(&mut self) -> Option<Point> { if self.1 >= 4 { return None; } else { let ret = self.0.get_in_dir(self.1.into()); self.1 += 1; ret.or_else(|| self.next()) } } } impl From<(usize, usize)> for Point { fn from((x, y): (usize, usize)) -> Point { Point::new(x, y) } } impl Into<(usize, usize)> for Point { fn into(self) -> (usize, usize) { (self.x, self.y) } } use std::fmt::{Display, Formatter, Result}; use std::ops::{Add, Div, Mul, Sub}; impl Display for Point { fn fmt(&self, w: &mut Formatter<'_>) -> Result { write!(w, "({}, {})", self.x, self.y) } } impl Add<Point> for Point { type Output = Point; fn add(self, rhs: Point) -> Point { Point { x: self.x + rhs.x, y: self.y + rhs.y, } } } impl Sub<Point> for Point { type Output = Point; fn sub(self, rhs: Point) -> Point { Point { x: self.x - rhs.x, y: self.y - rhs.y, } } } impl Mul<usize> for Point { type Output = Point; fn mul(self, rhs: usize) -> Point { Point { x: self.x * rhs, y: self.y * rhs, } } } impl Div<usize> for Point { type Output = Point; fn div(self, rhs: usize) -> Point { Point { x: self.x / rhs, y: self.y / rhs, } } }
// Copyright 2013 Google Inc. All Rights Reserved. // Copyright 2017 The Ninja-rs Project Developers. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::cell::{Cell, RefCell}; #[derive(Clone, Copy, PartialEq)] pub enum LinePrinterLineType { Full, Elide, } #[cfg(not(windows))] struct LinePrinterOs {} #[cfg(not(windows))] impl LinePrinterOs { fn new() -> Self { LinePrinterOs {} } fn should_be_smart(&self) -> bool { use libc; use std::env; use std::ffi; if unsafe { libc::isatty(1usize as _) } != 0 { return false; } if let Some(term) = env::var_os("TERM") { if term != ffi::OsString::from("dumb") { return true; } } return false; } } #[cfg(windows)] struct LinePrinterOs { console: ::winapi::HANDLE, } #[cfg(windows)] impl LinePrinterOs { fn new() -> Self { use kernel32; use winapi; LinePrinterOs { console: unsafe { kernel32::GetStdHandle(winapi::STD_OUTPUT_HANDLE) } } } fn should_be_smart(&self) -> bool { use kernel32; use winapi; use std::mem; let mut csbi = unsafe { mem::zeroed::<winapi::CONSOLE_SCREEN_BUFFER_INFO>() }; unsafe { kernel32::GetConsoleScreenBufferInfo(self.console, &mut csbi as *mut _) != winapi::FALSE } } } /// Prints lines of text, possibly overprinting previously printed lines /// if the terminal supports it. pub struct LinePrinter { /// Whether we can do fancy terminal control codes. smart_terminal: bool, /// Whether the caret is at the beginning of a blank line. have_blank_line: Cell<bool>, /// Whether console is locked. console_locked: bool, /// Buffered current line while console is locked. line_buffer: RefCell<Vec<u8>>, /// Buffered line type while console is locked. line_type: Cell<LinePrinterLineType>, /// Buffered console output while console is locked. output_buffer: RefCell<Vec<u8>>, extra: LinePrinterOs, } impl LinePrinter { pub fn new() -> Self { let lp_os = LinePrinterOs::new(); let smart = lp_os.should_be_smart(); LinePrinter { smart_terminal: smart, have_blank_line: Cell::new(true), console_locked: false, line_buffer: RefCell::new(Vec::new()), line_type: Cell::new(LinePrinterLineType::Full), output_buffer: RefCell::new(Vec::new()), extra: lp_os, } } pub fn is_smart_terminal(&self) -> bool { self.smart_terminal } pub fn set_smart_terminal(&mut self, smart: bool) { self.smart_terminal = smart; } /// Overprints the current line. If type is ELIDE, elides to_print to fit on /// one line. pub fn print(&self, to_print: &[u8], line_type: LinePrinterLineType) { if self.console_locked { *self.line_buffer.borrow_mut() = to_print.to_owned(); self.line_type.set(line_type); return; } if self.smart_terminal { print!("\r"); // Print over previous line, if any. // On Windows, calling a C library function writing to stdout also handles // pausing the executable when the "Pause" key or Ctrl-S is pressed. } if self.smart_terminal && line_type == LinePrinterLineType::Elide { /* #ifdef _WIN32 CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(console_, &csbi); to_print = ElideMiddle(to_print, static_cast<size_t>(csbi.dwSize.X)); // We don't want to have the cursor spamming back and forth, so instead of // printf use WriteConsoleOutput which updates the contents of the buffer, // but doesn't move the cursor position. COORD buf_size = { csbi.dwSize.X, 1 }; COORD zero_zero = { 0, 0 }; SMALL_RECT target = { csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y, static_cast<SHORT>(csbi.dwCursorPosition.X + csbi.dwSize.X - 1), csbi.dwCursorPosition.Y }; vector<CHAR_INFO> char_data(csbi.dwSize.X); for (size_t i = 0; i < static_cast<size_t>(csbi.dwSize.X); ++i) { char_data[i].Char.AsciiChar = i < to_print.size() ? to_print[i] : ' '; char_data[i].Attributes = csbi.wAttributes; } WriteConsoleOutput(console_, &char_data[0], buf_size, zero_zero, &target); #else // Limit output to width of the terminal if provided so we don't cause // line-wrapping. winsize size; if ((ioctl(0, TIOCGWINSZ, &size) == 0) && size.ws_col) { to_print = ElideMiddle(to_print, size.ws_col); } printf("%s", to_print.c_str()); printf("\x1B[K"); // Clear to end of line. fflush(stdout); #endif have_blank_line_ = false; */ self.have_blank_line.set(false); return; unimplemented!(); } else { use std::io::{self, Write}; let stdout = io::stdout(); let mut handle = stdout.lock(); let _ = handle.write(to_print); let _ = handle.write(b"\n"); } } /// Print the given data to the console, or buffer it if it is locked. fn print_or_buffer(&self, to_print: &[u8]) { if self.console_locked { self.output_buffer.borrow_mut().extend_from_slice(to_print); } else { use std::io::{self, Write}; let stdout = io::stdout(); let mut handle = stdout.lock(); let _ = handle.write(to_print); } } /// Prints a string on a new line, not overprinting previous output. pub fn print_on_new_line(&self, to_print: &[u8]) { if self.console_locked && !self.line_buffer.borrow().is_empty() { let mut line_buffer = self.line_buffer.borrow_mut(); let mut output_buffer = self.output_buffer.borrow_mut(); output_buffer.extend(line_buffer.drain(..)); output_buffer.push(b'\n'); } if !self.have_blank_line.get() { self.print_or_buffer(b"\n"); } if !to_print.is_empty() { self.print_or_buffer(to_print); } self.have_blank_line.set(match to_print.last() { None | Some(&b'\n') => true, _ => false, }); } /// Lock or unlock the console. Any output sent to the LinePrinter while the /// console is locked will not be printed until it is unlocked. pub fn set_console_locked(&mut self, locked: bool) { use std::mem; if self.console_locked == locked { return; } if locked { self.print_on_new_line(b""); } self.console_locked = locked; if !locked { let mut output_buffer = Vec::new(); let mut line_buffer = Vec::new(); mem::swap(&mut output_buffer, &mut *self.output_buffer.borrow_mut()); mem::swap(&mut line_buffer, &mut *self.line_buffer.borrow_mut()); self.print_on_new_line(&output_buffer); if !line_buffer.is_empty() { self.print(&line_buffer, self.line_type.get()); } } return; } } /* struct LinePrinter { LinePrinter(); bool is_smart_terminal() const { return smart_terminal_; } void set_smart_terminal(bool smart) { smart_terminal_ = smart; } /// Overprints the current line. If type is ELIDE, elides to_print to fit on /// one line. void Print(string to_print, LineType type); /// Prints a string on a new line, not overprinting previous output. void PrintOnNewLine(const string& to_print); /// Lock or unlock the console. Any output sent to the LinePrinter while the /// console is locked will not be printed until it is unlocked. void SetConsoleLocked(bool locked); private: /// Whether we can do fancy terminal control codes. bool smart_terminal_; /// Whether the caret is at the beginning of a blank line. bool have_blank_line_; /// Whether console is locked. bool console_locked_; /// Buffered current line while console is locked. string line_buffer_; /// Buffered line type while console is locked. LineType line_type_; /// Buffered console output while console is locked. string output_buffer_; #ifdef _WIN32 void* console_; #endif /// Print the given data to the console, or buffer it if it is locked. void PrintOrBuffer(const char *data, size_t size); }; #endif // NINJA_LINE_PRINTER_H_ */
use std::cell::RefCell; use std::collections::HashMap; use wasi_common::hostcalls::*; use wasi_common::{WasiCtx, WasiCtxBuilder}; use wasminspect_vm::*; use wasmparser::{FuncType, Type}; pub struct WasiContext { ctx: RefCell<WasiCtx>, } pub fn instantiate_wasi() -> (WasiContext, HashMap<String, HostValue>) { let builder = WasiCtxBuilder::new().inherit_stdio(); let wasi_ctx = builder.build().unwrap(); let mut module: HashMap<String, HostValue> = HashMap::new(); fn define_wasi_fn< F: Fn( &[WasmValue], &mut Vec<WasmValue>, &mut HostContext, &mut WasiCtx, ) -> Result<(), Trap> + 'static, >( args_ty: Vec<Type>, ret_ty: Option<Type>, f: F, ) -> HostValue { let ty = FuncType { form: Type::Func, params: args_ty.into_boxed_slice(), returns: ret_ty .map(|t| vec![t]) .unwrap_or_default() .into_boxed_slice(), }; return HostValue::Func(HostFuncBody::new(ty, move |args, ret, ctx, store| { let wasi_ctx = store.get_embed_context::<WasiContext>().unwrap(); let mut wasi_ctx = wasi_ctx.ctx.borrow_mut(); f(args, ret, ctx, &mut *wasi_ctx) })); } let func = define_wasi_fn(vec![Type::I32], None, |args, _ret, _ctx, _wasi_ctx| { unsafe { proc_exit(args[0].as_i32().unwrap() as u32); } Ok(()) }); module.insert("proc_exit".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = args_get( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("args_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = args_sizes_get( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("args_sizes_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, _| { unsafe { let result = clock_res_get( ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("clock_res_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I64, Type::I32], Some(Type::I32), |args, ret, ctx, _| { unsafe { let result = clock_time_get( ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i64().unwrap() as u64, args[2].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("clock_time_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = environ_get( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("environ_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = environ_sizes_get( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("environ_sizes_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_close(wasi_ctx, args[0].as_i32().unwrap() as u32); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_close".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_fdstat_get( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_fdstat_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_fdstat_set_flags( wasi_ctx, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u16, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_fdstat_set_flags".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_tell( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_tell".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I64, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_seek( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i64().unwrap(), args[2].as_i32().unwrap() as u8, args[3].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_seek".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_prestat_get( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_prestat_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_prestat_dir_name( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_prestat_dir_name".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_read( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_read".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_write( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_write".to_string(), func); let func = define_wasi_fn( vec![ Type::I32, Type::I32, Type::I32, Type::I32, Type::I32, Type::I64, Type::I64, Type::I32, Type::I32, ], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_open( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, args[4].as_i32().unwrap() as u16, args[5].as_i64().unwrap() as u64, args[6].as_i64().unwrap() as u64, args[7].as_i32().unwrap() as u16, args[8].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_open".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, _wasi_ctx| { unsafe { let result = random_get( ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("random_get".to_string(), func); let func = define_wasi_fn(vec![], Some(Type::I32), |_args, ret, _ctx, _wasi_ctx| { unsafe { let result = sched_yield(); ret.push(WasmValue::I32(result as i32)); } Ok(()) }); module.insert("sched_yield".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = poll_oneoff( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("poll_oneoff".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_filestat_get( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_filestat_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_filestat_get( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, args[4].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_filestat_get".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_create_directory( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_create_directory".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_unlink_file( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_unlink_file".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I64, Type::I64], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_allocate( wasi_ctx, args[0].as_i32().unwrap() as u32, args[1].as_i64().unwrap() as u64, args[2].as_i64().unwrap() as u64, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_allocate".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I64, Type::I64, Type::I32], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_advise( wasi_ctx, args[0].as_i32().unwrap() as u32, args[1].as_i64().unwrap() as u64, args[2].as_i64().unwrap() as u64, args[3].as_i32().unwrap() as u8, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_advise".to_string(), func); let func = define_wasi_fn( vec![Type::I32], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_datasync(wasi_ctx, args[0].as_i32().unwrap() as u32); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_datasync".to_string(), func); let func = define_wasi_fn( vec![Type::I32], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_sync(wasi_ctx, args[0].as_i32().unwrap() as u32); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_sync".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I64, Type::I64], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_fdstat_set_rights( wasi_ctx, args[0].as_i32().unwrap() as u32, args[1].as_i64().unwrap() as u64, args[2].as_i64().unwrap() as u64, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_fdstat_set_rights".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I64], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_filestat_set_size( wasi_ctx, args[0].as_i32().unwrap() as u32, args[1].as_i64().unwrap() as u64, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_filestat_set_size".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I64, Type::I64, Type::I32], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_filestat_set_times( wasi_ctx, args[0].as_i32().unwrap() as u32, args[1].as_i64().unwrap() as u64, args[2].as_i64().unwrap() as u64, args[3].as_i32().unwrap() as u16, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_filestat_set_times".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32, Type::I64, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_pread( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i64().unwrap() as u64, args[4].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_pread".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32, Type::I64, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_pwrite( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i64().unwrap() as u64, args[4].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_pwrite".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32, Type::I64, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = fd_readdir( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i64().unwrap() as u64, args[4].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_readdir".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32], Some(Type::I32), |args, ret, _ctx, wasi_ctx| { unsafe { let result = fd_renumber( wasi_ctx, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("fd_renumber".to_string(), func); let func = define_wasi_fn( vec![ Type::I32, Type::I32, Type::I32, Type::I32, Type::I64, Type::I64, Type::I32, ], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_filestat_set_times( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, args[4].as_i64().unwrap() as u64, args[5].as_i64().unwrap() as u64, args[6].as_i32().unwrap() as u16, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_filestat_set_times".to_string(), func); let func = define_wasi_fn( vec![ Type::I32, Type::I32, Type::I32, Type::I32, Type::I32, Type::I32, Type::I32, ], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_link( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, args[4].as_i32().unwrap() as u32, args[5].as_i32().unwrap() as u32, args[6].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_link".to_string(), func); let func = define_wasi_fn( vec![ Type::I32, Type::I32, Type::I32, Type::I32, Type::I32, Type::I32, ], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_readlink( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, args[4].as_i32().unwrap() as u32, args[5].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_readlink".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_remove_directory( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_remove_directory".to_string(), func); let func = define_wasi_fn( vec![ Type::I32, Type::I32, Type::I32, Type::I32, Type::I32, Type::I32, ], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_rename( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, args[4].as_i32().unwrap() as u32, args[5].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_rename".to_string(), func); let func = define_wasi_fn( vec![Type::I32, Type::I32, Type::I32, Type::I32, Type::I32], Some(Type::I32), |args, ret, ctx, wasi_ctx| { unsafe { let result = path_symlink( wasi_ctx, ctx.mem, args[0].as_i32().unwrap() as u32, args[1].as_i32().unwrap() as u32, args[2].as_i32().unwrap() as u32, args[3].as_i32().unwrap() as u32, args[4].as_i32().unwrap() as u32, ); ret.push(WasmValue::I32(result as i32)); } Ok(()) }, ); module.insert("path_symlink".to_string(), func); let context = WasiContext { ctx: RefCell::new(wasi_ctx), }; (context, module) }
// // https://github.com/rib/jsonwebtokens // use serde_json::json; use serde_json::{Map, Value}; use std::fs; use std::process; use std::str; use std::str::FromStr; use std::time::{SystemTime, UNIX_EPOCH}; use clap::clap_app; use jsonwebtokens as jwt; use jwt::{raw, Algorithm, AlgorithmID, Verifier}; use openssl::x509::X509; fn main() -> Result<(), jwt::error::Error> { let matches = clap_app!(myapp => (version: "0.1") (author: "JW Hance. <jwhance@gmail.com>") (about: "Generates or Validates a JWT") //(@arg CONFIG: -c --config +takes_value "Sets a custom config file") //(@arg INPUT: +required "Sets the input file to use") //(@arg verbose: -v --verbose "Print test information verbosely") (@subcommand generate => (about: "Generates a JWT using the specified parameters.") (@arg debug: -d --debug ... "Sets the level of debugging information") (@arg privatekey: -p --privatekey +required ... "Private Key PEM file") (@arg algorithm: -a --algorithm +required ... "JWT signing algorithm") (@arg iss: -i --iss ... "Issuer") (@arg sub: -s --sub ... "Subject") (@arg aud: -u --aud ... "Audience") (@arg exp: -e --exp ... "Expiration in minutes") ) (@subcommand validate => (about: "Validates a JWT against the specified parameters.") (@arg debug: -d --debug ... "Sets the level of debugging information") (@arg publickey: -p --publickey +required ... "Public Key PEM file") (@arg jwtfile: -j --jwtfile +required ... "JWT file") (@arg iss: -i --iss ... "Issuer") (@arg sub: -s --sub ... "Subject") (@arg aud: -u --aud ... "Audience") ) ) .get_matches(); eprintln!("Beginning JWT Utility"); // Read X.509 certificate from file let public_cert = fs::read_to_string("./src/fiserv_test.crt").expect("Something went wrong reading the file"); // For X.509 certificate: https://docs.rs/openssl/0.10.4/openssl/x509/struct.X509.html let x509 = X509::from_pem(public_cert.as_bytes()).unwrap(); eprintln!("X509 Issuer : {:?}", x509.issuer_name()); eprintln!("X509 Not Before: {:?}", x509.not_before()); eprintln!("X509 Not After : {:?}", x509.not_after()); eprintln!("X509 PKey : {:?}", x509.public_key().unwrap()); let pubk = x509.public_key().unwrap().public_key_to_pem().unwrap(); eprintln!("PUBK: {:?}", str::from_utf8(&pubk).unwrap()); // End of X.509 stuff let current_time = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs(); if matches.subcommand_name() == None { } else if matches.subcommand_name().unwrap() == String::from("validate") { eprintln!(" => Validating JWT"); // Options let sub_command = matches.subcommand_matches("validate").unwrap(); let public_key_file = sub_command.value_of("publickey").unwrap(); let jwt_file = sub_command.value_of("jwtfile").unwrap(); //Read public key from file let public_key = fs::read_to_string(&public_key_file).expect("Something went wrong reading the file"); //Read JWT from file let jwt = fs::read_to_string(&jwt_file).expect("Something went wrong reading the file"); let decoded = raw::decode_only(&jwt)?; eprintln!(" Header: {:?}", decoded.header); //eprintln!("Alg: {0}", decoded.header.get("alg").unwrap()); eprintln!(" Payload: {:?}", decoded.claims); let jwt_alg = AlgorithmID::from_str(decoded.header["alg"].as_str().unwrap()).unwrap(); let alg = Algorithm::new_rsa_pem_verifier(jwt_alg, &public_key.as_bytes()).unwrap(); let mut verifier = Verifier::create(); if get_claim_verification_value(sub_command, "iss") != None { verifier.issuer(get_claim_verification_value(sub_command, "iss").unwrap()); } if get_claim_verification_value(sub_command, "aud") != None { verifier.audience(get_claim_verification_value(sub_command, "aud").unwrap()); } match verifier.build().unwrap().verify(&jwt.trim(), &alg) { Ok(output) => { println!(" Verification: {0}", output); } Err(error) => { eprintln!(" Error: {:?}", error); } } } else if matches.subcommand_name().unwrap() == String::from("generate") { // // GENERATE JWT // eprintln!(" => Generating JWT"); // Options let sub_command = matches.subcommand_matches("generate").unwrap(); let _alg = sub_command.value_of("algorithm").unwrap(); let private_key_file = sub_command.value_of("privatekey").unwrap(); // Read private key from file let private_key = fs::read_to_string(&private_key_file).expect("Something went wrong reading the file"); let jwt_alg = AlgorithmID::from_str(_alg).unwrap(); let alg = Algorithm::new_rsa_pem_signer(jwt_alg, &private_key.as_bytes())?; let header = json!({ "alg": alg.name(), "typ": "JWT" }); let mut claims_map = Map::new(); // iat = current time claims_map.insert(String::from("iat"), Value::from(current_time)); // Add any optional claims: iss, sub, aud, exp add_claim_str(&mut claims_map, sub_command, "aud"); add_claim_str(&mut claims_map, sub_command, "iss"); add_claim_str(&mut claims_map, sub_command, "sub"); add_claim_exp(&mut claims_map, sub_command, "exp", current_time); let token_str = jwt::encode(&header, &claims_map, &alg)?; print!("{0}", token_str.trim()); } else { eprintln!("Unknown option"); } process::exit(0); } fn get_claim_verification_value(sub_command: &clap::ArgMatches, claim: &str) -> Option<String> { let clm = sub_command.value_of(claim); if clm != None { Some(clm.unwrap().to_string()) } else { None } } fn add_claim_str(map: &mut Map<String, Value>, sub_command: &clap::ArgMatches, claim: &str) { let clm = sub_command.value_of(claim); if clm != None { map.insert(String::from(claim), Value::String(clm.unwrap().to_string())); } } fn add_claim_exp( map: &mut Map<String, Value>, sub_command: &clap::ArgMatches, claim: &str, current_time: u64, ) { let clm = sub_command.value_of(claim); if clm != None { let exp: u64 = clm.unwrap().parse().unwrap(); map.insert(String::from(claim), Value::from(exp + current_time)); } }
#[doc = "Reader of register IER1"] pub type R = crate::R<u32, super::IER1>; #[doc = "Writer for register IER1"] pub type W = crate::W<u32, super::IER1>; #[doc = "Register IER1 `reset()`'s with value 0"] impl crate::ResetValue for super::IER1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TIM2IE`"] pub type TIM2IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM2IE`"] pub struct TIM2IE_W<'a> { w: &'a mut W, } impl<'a> TIM2IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `TIM3IE`"] pub type TIM3IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM3IE`"] pub struct TIM3IE_W<'a> { w: &'a mut W, } impl<'a> TIM3IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `TIM4IE`"] pub type TIM4IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM4IE`"] pub struct TIM4IE_W<'a> { w: &'a mut W, } impl<'a> TIM4IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `TIM5IE`"] pub type TIM5IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM5IE`"] pub struct TIM5IE_W<'a> { w: &'a mut W, } impl<'a> TIM5IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `TIM6IE`"] pub type TIM6IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM6IE`"] pub struct TIM6IE_W<'a> { w: &'a mut W, } impl<'a> TIM6IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `TIM7IE`"] pub type TIM7IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM7IE`"] pub struct TIM7IE_W<'a> { w: &'a mut W, } impl<'a> TIM7IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `WWDGIE`"] pub type WWDGIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WWDGIE`"] pub struct WWDGIE_W<'a> { w: &'a mut W, } impl<'a> WWDGIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `IWDGIE`"] pub type IWDGIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IWDGIE`"] pub struct IWDGIE_W<'a> { w: &'a mut W, } impl<'a> IWDGIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `SPI2IE`"] pub type SPI2IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SPI2IE`"] pub struct SPI2IE_W<'a> { w: &'a mut W, } impl<'a> SPI2IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `SPI3IE`"] pub type SPI3IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SPI3IE`"] pub struct SPI3IE_W<'a> { w: &'a mut W, } impl<'a> SPI3IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `USART2IE`"] pub type USART2IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USART2IE`"] pub struct USART2IE_W<'a> { w: &'a mut W, } impl<'a> USART2IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `USART3IE`"] pub type USART3IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USART3IE`"] pub struct USART3IE_W<'a> { w: &'a mut W, } impl<'a> USART3IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `UART4IE`"] pub type UART4IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UART4IE`"] pub struct UART4IE_W<'a> { w: &'a mut W, } impl<'a> UART4IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `UART5IE`"] pub type UART5IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UART5IE`"] pub struct UART5IE_W<'a> { w: &'a mut W, } impl<'a> UART5IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `I2C1IE`"] pub type I2C1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `I2C1IE`"] pub struct I2C1IE_W<'a> { w: &'a mut W, } impl<'a> I2C1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `I2C2IE`"] pub type I2C2IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `I2C2IE`"] pub struct I2C2IE_W<'a> { w: &'a mut W, } impl<'a> I2C2IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `I2C3IE`"] pub type I2C3IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `I2C3IE`"] pub struct I2C3IE_W<'a> { w: &'a mut W, } impl<'a> I2C3IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `CRSIE`"] pub type CRSIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CRSIE`"] pub struct CRSIE_W<'a> { w: &'a mut W, } impl<'a> CRSIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `DACIE`"] pub type DACIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DACIE`"] pub struct DACIE_W<'a> { w: &'a mut W, } impl<'a> DACIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `OPAMPIE`"] pub type OPAMPIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OPAMPIE`"] pub struct OPAMPIE_W<'a> { w: &'a mut W, } impl<'a> OPAMPIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `LPTIM1IE`"] pub type LPTIM1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LPTIM1IE`"] pub struct LPTIM1IE_W<'a> { w: &'a mut W, } impl<'a> LPTIM1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `LPUART1IE`"] pub type LPUART1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LPUART1IE`"] pub struct LPUART1IE_W<'a> { w: &'a mut W, } impl<'a> LPUART1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `I2C4IE`"] pub type I2C4IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `I2C4IE`"] pub struct I2C4IE_W<'a> { w: &'a mut W, } impl<'a> I2C4IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `LPTIM2IE`"] pub type LPTIM2IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LPTIM2IE`"] pub struct LPTIM2IE_W<'a> { w: &'a mut W, } impl<'a> LPTIM2IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `LPTIM3IE`"] pub type LPTIM3IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LPTIM3IE`"] pub struct LPTIM3IE_W<'a> { w: &'a mut W, } impl<'a> LPTIM3IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `FDCAN1IE`"] pub type FDCAN1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FDCAN1IE`"] pub struct FDCAN1IE_W<'a> { w: &'a mut W, } impl<'a> FDCAN1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `USBFSIE`"] pub type USBFSIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USBFSIE`"] pub struct USBFSIE_W<'a> { w: &'a mut W, } impl<'a> USBFSIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `UCPD1IE`"] pub type UCPD1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UCPD1IE`"] pub struct UCPD1IE_W<'a> { w: &'a mut W, } impl<'a> UCPD1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `VREFBUFIE`"] pub type VREFBUFIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VREFBUFIE`"] pub struct VREFBUFIE_W<'a> { w: &'a mut W, } impl<'a> VREFBUFIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `COMPIE`"] pub type COMPIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMPIE`"] pub struct COMPIE_W<'a> { w: &'a mut W, } impl<'a> COMPIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `TIM1IE`"] pub type TIM1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM1IE`"] pub struct TIM1IE_W<'a> { w: &'a mut W, } impl<'a> TIM1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `SPI1IE`"] pub type SPI1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SPI1IE`"] pub struct SPI1IE_W<'a> { w: &'a mut W, } impl<'a> SPI1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - TIM2IE"] #[inline(always)] pub fn tim2ie(&self) -> TIM2IE_R { TIM2IE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TIM3IE"] #[inline(always)] pub fn tim3ie(&self) -> TIM3IE_R { TIM3IE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - TIM4IE"] #[inline(always)] pub fn tim4ie(&self) -> TIM4IE_R { TIM4IE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - TIM5IE"] #[inline(always)] pub fn tim5ie(&self) -> TIM5IE_R { TIM5IE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - TIM6IE"] #[inline(always)] pub fn tim6ie(&self) -> TIM6IE_R { TIM6IE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - TIM7IE"] #[inline(always)] pub fn tim7ie(&self) -> TIM7IE_R { TIM7IE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - WWDGIE"] #[inline(always)] pub fn wwdgie(&self) -> WWDGIE_R { WWDGIE_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - IWDGIE"] #[inline(always)] pub fn iwdgie(&self) -> IWDGIE_R { IWDGIE_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - SPI2IE"] #[inline(always)] pub fn spi2ie(&self) -> SPI2IE_R { SPI2IE_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - SPI3IE"] #[inline(always)] pub fn spi3ie(&self) -> SPI3IE_R { SPI3IE_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - USART2IE"] #[inline(always)] pub fn usart2ie(&self) -> USART2IE_R { USART2IE_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - USART3IE"] #[inline(always)] pub fn usart3ie(&self) -> USART3IE_R { USART3IE_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - UART4IE"] #[inline(always)] pub fn uart4ie(&self) -> UART4IE_R { UART4IE_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - UART5IE"] #[inline(always)] pub fn uart5ie(&self) -> UART5IE_R { UART5IE_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - I2C1IE"] #[inline(always)] pub fn i2c1ie(&self) -> I2C1IE_R { I2C1IE_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - I2C2IE"] #[inline(always)] pub fn i2c2ie(&self) -> I2C2IE_R { I2C2IE_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - I2C3IE"] #[inline(always)] pub fn i2c3ie(&self) -> I2C3IE_R { I2C3IE_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - CRSIE"] #[inline(always)] pub fn crsie(&self) -> CRSIE_R { CRSIE_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - DACIE"] #[inline(always)] pub fn dacie(&self) -> DACIE_R { DACIE_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - OPAMPIE"] #[inline(always)] pub fn opampie(&self) -> OPAMPIE_R { OPAMPIE_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - LPTIM1IE"] #[inline(always)] pub fn lptim1ie(&self) -> LPTIM1IE_R { LPTIM1IE_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - LPUART1IE"] #[inline(always)] pub fn lpuart1ie(&self) -> LPUART1IE_R { LPUART1IE_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - I2C4IE"] #[inline(always)] pub fn i2c4ie(&self) -> I2C4IE_R { I2C4IE_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - LPTIM2IE"] #[inline(always)] pub fn lptim2ie(&self) -> LPTIM2IE_R { LPTIM2IE_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - LPTIM3IE"] #[inline(always)] pub fn lptim3ie(&self) -> LPTIM3IE_R { LPTIM3IE_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - FDCAN1IE"] #[inline(always)] pub fn fdcan1ie(&self) -> FDCAN1IE_R { FDCAN1IE_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - USBFSIE"] #[inline(always)] pub fn usbfsie(&self) -> USBFSIE_R { USBFSIE_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - UCPD1IE"] #[inline(always)] pub fn ucpd1ie(&self) -> UCPD1IE_R { UCPD1IE_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - VREFBUFIE"] #[inline(always)] pub fn vrefbufie(&self) -> VREFBUFIE_R { VREFBUFIE_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - COMPIE"] #[inline(always)] pub fn compie(&self) -> COMPIE_R { COMPIE_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - TIM1IE"] #[inline(always)] pub fn tim1ie(&self) -> TIM1IE_R { TIM1IE_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - SPI1IE"] #[inline(always)] pub fn spi1ie(&self) -> SPI1IE_R { SPI1IE_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - TIM2IE"] #[inline(always)] pub fn tim2ie(&mut self) -> TIM2IE_W { TIM2IE_W { w: self } } #[doc = "Bit 1 - TIM3IE"] #[inline(always)] pub fn tim3ie(&mut self) -> TIM3IE_W { TIM3IE_W { w: self } } #[doc = "Bit 2 - TIM4IE"] #[inline(always)] pub fn tim4ie(&mut self) -> TIM4IE_W { TIM4IE_W { w: self } } #[doc = "Bit 3 - TIM5IE"] #[inline(always)] pub fn tim5ie(&mut self) -> TIM5IE_W { TIM5IE_W { w: self } } #[doc = "Bit 4 - TIM6IE"] #[inline(always)] pub fn tim6ie(&mut self) -> TIM6IE_W { TIM6IE_W { w: self } } #[doc = "Bit 5 - TIM7IE"] #[inline(always)] pub fn tim7ie(&mut self) -> TIM7IE_W { TIM7IE_W { w: self } } #[doc = "Bit 6 - WWDGIE"] #[inline(always)] pub fn wwdgie(&mut self) -> WWDGIE_W { WWDGIE_W { w: self } } #[doc = "Bit 7 - IWDGIE"] #[inline(always)] pub fn iwdgie(&mut self) -> IWDGIE_W { IWDGIE_W { w: self } } #[doc = "Bit 8 - SPI2IE"] #[inline(always)] pub fn spi2ie(&mut self) -> SPI2IE_W { SPI2IE_W { w: self } } #[doc = "Bit 9 - SPI3IE"] #[inline(always)] pub fn spi3ie(&mut self) -> SPI3IE_W { SPI3IE_W { w: self } } #[doc = "Bit 10 - USART2IE"] #[inline(always)] pub fn usart2ie(&mut self) -> USART2IE_W { USART2IE_W { w: self } } #[doc = "Bit 11 - USART3IE"] #[inline(always)] pub fn usart3ie(&mut self) -> USART3IE_W { USART3IE_W { w: self } } #[doc = "Bit 12 - UART4IE"] #[inline(always)] pub fn uart4ie(&mut self) -> UART4IE_W { UART4IE_W { w: self } } #[doc = "Bit 13 - UART5IE"] #[inline(always)] pub fn uart5ie(&mut self) -> UART5IE_W { UART5IE_W { w: self } } #[doc = "Bit 14 - I2C1IE"] #[inline(always)] pub fn i2c1ie(&mut self) -> I2C1IE_W { I2C1IE_W { w: self } } #[doc = "Bit 15 - I2C2IE"] #[inline(always)] pub fn i2c2ie(&mut self) -> I2C2IE_W { I2C2IE_W { w: self } } #[doc = "Bit 16 - I2C3IE"] #[inline(always)] pub fn i2c3ie(&mut self) -> I2C3IE_W { I2C3IE_W { w: self } } #[doc = "Bit 17 - CRSIE"] #[inline(always)] pub fn crsie(&mut self) -> CRSIE_W { CRSIE_W { w: self } } #[doc = "Bit 18 - DACIE"] #[inline(always)] pub fn dacie(&mut self) -> DACIE_W { DACIE_W { w: self } } #[doc = "Bit 19 - OPAMPIE"] #[inline(always)] pub fn opampie(&mut self) -> OPAMPIE_W { OPAMPIE_W { w: self } } #[doc = "Bit 20 - LPTIM1IE"] #[inline(always)] pub fn lptim1ie(&mut self) -> LPTIM1IE_W { LPTIM1IE_W { w: self } } #[doc = "Bit 21 - LPUART1IE"] #[inline(always)] pub fn lpuart1ie(&mut self) -> LPUART1IE_W { LPUART1IE_W { w: self } } #[doc = "Bit 22 - I2C4IE"] #[inline(always)] pub fn i2c4ie(&mut self) -> I2C4IE_W { I2C4IE_W { w: self } } #[doc = "Bit 23 - LPTIM2IE"] #[inline(always)] pub fn lptim2ie(&mut self) -> LPTIM2IE_W { LPTIM2IE_W { w: self } } #[doc = "Bit 24 - LPTIM3IE"] #[inline(always)] pub fn lptim3ie(&mut self) -> LPTIM3IE_W { LPTIM3IE_W { w: self } } #[doc = "Bit 25 - FDCAN1IE"] #[inline(always)] pub fn fdcan1ie(&mut self) -> FDCAN1IE_W { FDCAN1IE_W { w: self } } #[doc = "Bit 26 - USBFSIE"] #[inline(always)] pub fn usbfsie(&mut self) -> USBFSIE_W { USBFSIE_W { w: self } } #[doc = "Bit 27 - UCPD1IE"] #[inline(always)] pub fn ucpd1ie(&mut self) -> UCPD1IE_W { UCPD1IE_W { w: self } } #[doc = "Bit 28 - VREFBUFIE"] #[inline(always)] pub fn vrefbufie(&mut self) -> VREFBUFIE_W { VREFBUFIE_W { w: self } } #[doc = "Bit 29 - COMPIE"] #[inline(always)] pub fn compie(&mut self) -> COMPIE_W { COMPIE_W { w: self } } #[doc = "Bit 30 - TIM1IE"] #[inline(always)] pub fn tim1ie(&mut self) -> TIM1IE_W { TIM1IE_W { w: self } } #[doc = "Bit 31 - SPI1IE"] #[inline(always)] pub fn spi1ie(&mut self) -> SPI1IE_W { SPI1IE_W { w: self } } }
use std::fs; use crate::cli; #[cfg(test)] mod test; pub fn run() { let filename = cli::aoc_filename("aoc_2019_08.txt"); let digits = fs::read_to_string(filename).unwrap(); let img = parse(25, 6, digits.trim()); println!("Part One: {}", part_one(&img)); println!("Part Two:\n{}", part_two(&img)); } fn part_one(img: &Image) -> usize { let zeroy_layer = img .layers() .fold((usize::max_value(), None), |(min, prev), l| { let n = l.count_of(0); if n < min { (n, Some(l)) } else { (min, prev) } }) .1 .unwrap(); zeroy_layer.count_of(1) * zeroy_layer.count_of(2) } fn part_two(img: &Image) -> String { // the text is drawn white-on-black, which is hard to read in ASCII Art let flat = img.flatten().invert(); let layer = flat.get_layer(0); render_layer(&layer) } fn render_layer(layer: &Layer) -> String { let mut start_end = "-".repeat(layer.width + 2); start_end.insert(0, '+'); start_end.push('+'); start_end.push('\n'); let mut s = String::from(&start_end); for r in 0..layer.height { s += "| "; for c in 0..layer.width { s.push(match layer.data[r * layer.width + c] { BLACK => '#', WHITE => ' ', TRANSPARENT => 'O', _ => '?', }) } s += " |\n"; } s += &start_end; s } #[derive(Debug)] struct Image { width: usize, height: usize, digits: Vec<u8>, } const BLACK: u8 = 0; const WHITE: u8 = 1; const TRANSPARENT: u8 = 2; impl Image { pub fn layer_count(&self) -> usize { self.digits.len() / self.layer_size() } pub fn get_layer(&self, i: usize) -> Layer { let layer_size = self.layer_size(); Layer { width: self.width, height: self.height, data: &self.digits[(i * layer_size)..((i + 1) * layer_size)], } } pub fn layers(&self) -> Layers { Layers { image: self, curr: 0, } } #[inline] fn layer_size(&self) -> usize { self.width * self.height } pub fn flatten(&self) -> Image { let digits = self.get_layer(0).data.to_vec(); let digits = self.layers().skip(1).fold(digits, |ds, l| { ds.iter() .zip(l.data) .map(|(&bg, &d)| { if d != TRANSPARENT && bg == TRANSPARENT { d } else { bg } }) .collect() }); Image { width: self.width, height: self.height, digits, } } pub fn invert(&self) -> Image { let digits = self .digits .iter() .map(|&d| match d { BLACK => WHITE, WHITE => BLACK, _ => d, }) .collect(); Image { width: self.width, height: self.height, digits, } } } struct Layers<'a> { image: &'a Image, curr: usize, } impl<'a> Iterator for Layers<'a> { type Item = Layer<'a>; fn next(&mut self) -> Option<Self::Item> { if self.curr >= self.image.layer_count() { return None; } let i = self.curr; self.curr += 1; Some(self.image.get_layer(i)) } fn size_hint(&self) -> (usize, Option<usize>) { let r = self.image.layer_count() - self.curr; (r, Some(r)) } fn nth(&mut self, n: usize) -> Option<Self::Item> { self.curr += n; self.next() } } #[derive(Debug)] struct Layer<'a> { width: usize, height: usize, data: &'a [u8], } impl Layer<'_> { pub fn count_of(&self, digit: u8) -> usize { self.data.iter().filter(|&&d| d == digit).count() } } fn parse(width: usize, height: usize, data: &str) -> Image { println!( "parse {}x{} w/ {} digits: {}...{}", width, height, data.len(), &data[0..5], &data[(data.len() - 5)..data.len()] ); assert_eq!(0, data.len() % (width * height)); let mut digits: Vec<u8> = Vec::new(); digits.reserve(data.len()); for c in data.chars() { digits.push(parse_digit(c)) } Image { width, height, digits, } } fn parse_digit(c: char) -> u8 { match c { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, _ => panic!("unrecognized character '{}'", c), } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - DBGMCU_IDCODE"] pub idcode: IDCODE, #[doc = "0x04 - Debug MCU configuration register"] pub cr: CR, #[doc = "0x08 - Debug MCU APB1 freeze register1"] pub apb1lfzr: APB1LFZR, #[doc = "0x0c - Debug MCU APB1 freeze register 2"] pub apb1hfzr: APB1HFZR, #[doc = "0x10 - Debug MCU APB2 freeze register"] pub apb2fzr: APB2FZR, } #[doc = "DBGMCU_IDCODE\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [idcode](idcode) module"] pub type IDCODE = crate::Reg<u32, _IDCODE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IDCODE; #[doc = "`read()` method returns [idcode::R](idcode::R) reader structure"] impl crate::Readable for IDCODE {} #[doc = "DBGMCU_IDCODE"] pub mod idcode; #[doc = "Debug MCU configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"] pub type CR = crate::Reg<u32, _CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CR; #[doc = "`read()` method returns [cr::R](cr::R) reader structure"] impl crate::Readable for CR {} #[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"] impl crate::Writable for CR {} #[doc = "Debug MCU configuration register"] pub mod cr; #[doc = "Debug MCU APB1 freeze register1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb1lfzr](apb1lfzr) module"] pub type APB1LFZR = crate::Reg<u32, _APB1LFZR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _APB1LFZR; #[doc = "`read()` method returns [apb1lfzr::R](apb1lfzr::R) reader structure"] impl crate::Readable for APB1LFZR {} #[doc = "`write(|w| ..)` method takes [apb1lfzr::W](apb1lfzr::W) writer structure"] impl crate::Writable for APB1LFZR {} #[doc = "Debug MCU APB1 freeze register1"] pub mod apb1lfzr; #[doc = "Debug MCU APB1 freeze register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb1hfzr](apb1hfzr) module"] pub type APB1HFZR = crate::Reg<u32, _APB1HFZR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _APB1HFZR; #[doc = "`read()` method returns [apb1hfzr::R](apb1hfzr::R) reader structure"] impl crate::Readable for APB1HFZR {} #[doc = "`write(|w| ..)` method takes [apb1hfzr::W](apb1hfzr::W) writer structure"] impl crate::Writable for APB1HFZR {} #[doc = "Debug MCU APB1 freeze register 2"] pub mod apb1hfzr; #[doc = "Debug MCU APB2 freeze register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb2fzr](apb2fzr) module"] pub type APB2FZR = crate::Reg<u32, _APB2FZR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _APB2FZR; #[doc = "`read()` method returns [apb2fzr::R](apb2fzr::R) reader structure"] impl crate::Readable for APB2FZR {} #[doc = "`write(|w| ..)` method takes [apb2fzr::W](apb2fzr::W) writer structure"] impl crate::Writable for APB2FZR {} #[doc = "Debug MCU APB2 freeze register"] pub mod apb2fzr;
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:issue-42708.rs // ignore-stage1 #![feature(decl_macro, proc_macro_path_invoc)] #![allow(unused)] extern crate issue_42708; macro m() { #[derive(issue_42708::Test)] struct S { x: () } #[issue_42708::attr_test] struct S2 { x: () } #[derive(Clone)] struct S3 { x: () } fn g(s: S, s2: S2, s3: S3) { (s.x, s2.x, s3.x); } } m!(); fn main() {}
use super::*; #[derive(Clone)] pub struct NestedClass(pub Row); impl NestedClass { pub fn nested_type(&self) -> TypeDef { Row::new(self.0.u32(0) - 1, TableIndex::TypeDef, self.0.file).into() } pub fn enclosing_type(&self) -> TypeDef { Row::new(self.0.u32(1) - 1, TableIndex::TypeDef, self.0.file).into() } }
#[cfg(not(feature = "lib"))] use std::{cell::RefCell, collections::{HashMap, HashSet}, convert::TryFrom, mem, ptr, rc::Rc, slice}; mod composition; mod path_builder; mod raster_builder; mod styling; #[cfg(not(feature = "lib"))] use composition::Composition; #[cfg(not(feature = "lib"))] use path_builder::PathBuilder; #[cfg(not(feature = "lib"))] use raster_builder::RasterBuilder; #[cfg(not(feature = "lib"))] use styling::Styling; #[cfg(feature = "lib")] pub use composition::Composition; #[cfg(feature = "lib")] pub use path_builder::PathBuilder; #[cfg(feature = "lib")] pub use raster_builder::RasterBuilder; #[cfg(feature = "lib")] pub use styling::Styling; #[cfg(not(feature = "lib"))] use mold::{ColorBuffer, PixelFormat, tile::Map, Path, Point, RasterInner}; #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum SpnResult { SpnSuccess, SpnErrorNotImplemented, SpnErrorContextLost, SpnErrorPathBuilderLost, SpnErrorRasterBuilderLost, SpnErrorRasterBuilderSealed, SpnErrorRasterBuilderTooManyRasters, SpnErrorRenderExtensionInvalid, SpnErrorRenderExtensionVkSubmitInfoWaitCountExceeded, SpnErrorLayerIdInvalid, SpnErrorLayerNotEmpty, SpnErrorPoolEmpty, SpnErrorCondvarWait, SpnErrorTransformWeakrefInvalid, SpnErrorStrokeStyleWeakrefInvalid, SpnErrorCommandNotReady, SpnErrorCommandNotCompleted, SpnErrorCommandNotStarted, SpnErrorCommandNotReadyOrCompleted, SpnErrorCompositionSealed, SpnErrorStylingSealed, SpnErrorHandleInvalid, SpnErrorHandleOverflow, } pub const SPN_STYLING_OPCODE_NOOP: u32 = 0; pub const SPN_STYLING_OPCODE_COVER_NONZERO: u32 = 1; pub const SPN_STYLING_OPCODE_COVER_EVENODD: u32 = 2; pub const SPN_STYLING_OPCODE_COVER_ACCUMULATE: u32 = 3; pub const SPN_STYLING_OPCODE_COVER_MASK: u32 = 4; pub const SPN_STYLING_OPCODE_COVER_WIP_ZERO: u32 = 5; pub const SPN_STYLING_OPCODE_COVER_ACC_ZERO: u32 = 6; pub const SPN_STYLING_OPCODE_COVER_MASK_ZERO: u32 = 7; pub const SPN_STYLING_OPCODE_COVER_MASK_ONE: u32 = 8; pub const SPN_STYLING_OPCODE_COVER_MASK_INVERT: u32 = 9; pub const SPN_STYLING_OPCODE_COLOR_FILL_SOLID: u32 = 10; pub const SPN_STYLING_OPCODE_COLOR_FILL_GRADIENT_LINEAR: u32 = 11; pub const SPN_STYLING_OPCODE_COLOR_WIP_ZERO: u32 = 12; pub const SPN_STYLING_OPCODE_COLOR_ACC_ZERO: u32 = 13; pub const SPN_STYLING_OPCODE_BLEND_OVER: u32 = 14; pub const SPN_STYLING_OPCODE_BLEND_PLUS: u32 = 15; pub const SPN_STYLING_OPCODE_BLEND_MULTIPLY: u32 = 16; pub const SPN_STYLING_OPCODE_BLEND_KNOCKOUT: u32 = 17; pub const SPN_STYLING_OPCODE_COVER_WIP_MOVE_TO_MASK: u32 = 18; pub const SPN_STYLING_OPCODE_COVER_ACC_MOVE_TO_MASK: u32 = 19; pub const SPN_STYLING_OPCODE_COLOR_ACC_OVER_BACKGROUND: u32 = 20; pub const SPN_STYLING_OPCODE_COLOR_ACC_STORE_TO_SURFACE: u32 = 21; pub const SPN_STYLING_OPCODE_COLOR_ACC_TEST_OPACITY: u32 = 22; pub const SPN_STYLING_OPCODE_COLOR_ILL_ZERO: u32 = 23; pub const SPN_STYLING_OPCODE_COLOR_ILL_COPY_ACC: u32 = 24; pub const SPN_STYLING_OPCODE_COLOR_ACC_MULTIPLY_ILL: u32 = 25; #[cfg(not(feature = "lib"))] unsafe fn retain_from_ptr<T>(ptr: *const T) { let object = Rc::from_raw(ptr); Rc::into_raw(Rc::clone(&object)); Rc::into_raw(object); } #[cfg(not(feature = "lib"))] unsafe fn clone_from_ptr<T>(ptr: *const T) -> Rc<T> { let original = Rc::from_raw(ptr); let clone = Rc::clone(&original); Rc::into_raw(original); clone } #[cfg(not(feature = "lib"))] #[repr(C)] #[derive(Clone, Debug)] pub struct RawBuffer { pub buffer_ptr: *const *mut u8, pub stride: usize, pub format: PixelFormat, } #[cfg(not(feature = "lib"))] unsafe impl Send for RawBuffer {} #[cfg(not(feature = "lib"))] unsafe impl Sync for RawBuffer {} #[cfg(not(feature = "lib"))] impl ColorBuffer for RawBuffer { fn pixel_format(&self) -> PixelFormat { self.format } fn stride(&self) -> usize { self.stride } unsafe fn write_at(&mut self, offset: usize, src: *const u8, len: usize) { let dst = (*self.buffer_ptr).add(offset); ptr::copy_nonoverlapping(src, dst, len); } } #[cfg(not(feature = "lib"))] #[repr(C)] #[derive(Debug)] pub struct Context { map: Option<Map>, paths: HashMap<u32, (Path, usize)>, path_index: u32, rasters: HashMap<u32, (Rc<RasterInner>, usize)>, raster_index: u32, raw_buffer: RawBuffer, old_prints: HashSet<u32>, new_prints: HashSet<u32>, } #[cfg(not(feature = "lib"))] impl Context { pub fn get_path(&self, id: PathId) -> &Path { &self.paths[&id].0 } pub fn insert_path(&mut self, path: Path) -> PathId { if self.paths.len() == u32::max_value() as usize { panic!("cannot store more than {} spn_path_t", u32::max_value()); } while self.paths.contains_key(&self.path_index) { self.path_index = self.path_index.wrapping_add(1); } self.paths.insert(self.path_index, (path, 1)); self.path_index } pub unsafe fn retain_path(&mut self, id: PathId) { self.paths.entry(id).and_modify(|(_, rc)| *rc += 1); } pub unsafe fn release_path(&mut self, id: PathId) { self.paths.entry(id).and_modify(|(_, rc)| *rc -= 1); if self.paths[&id].1 == 0 { self.paths.remove(&id); } } pub fn get_raster(&self, id: RasterId) -> &Rc<RasterInner> { &self.rasters[&id].0 } pub fn insert_raster(&mut self, raster: Rc<RasterInner>) -> RasterId { if self.rasters.len() == u32::max_value() as usize { panic!("cannot store more than {} spn_path_t", u32::max_value()); } while self.rasters.contains_key(&self.raster_index) { self.raster_index = self.raster_index.wrapping_add(1); } self.rasters.insert(self.raster_index, (raster, 1)); self.raster_index } pub fn retain_raster(&mut self, id: RasterId) { self.rasters.entry(id).and_modify(|(_, rc)| *rc += 1); } pub fn release_raster(&mut self, id: RasterId) { self.rasters.entry(id).and_modify(|(_, rc)| *rc -= 1); if self.rasters[&id].1 == 0 { self.rasters.remove(&id); } } pub fn swap_prints(&mut self) { mem::swap(&mut self.old_prints, &mut self.new_prints); } } #[cfg(not(feature = "lib"))] #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct RenderSubmit { pub ext: *mut (), pub styling: StylingPtr, pub composition: CompositionPtr, pub tile_clip: [u32; 4], } #[cfg(not(feature = "lib"))] pub type ContextPtr = *const RefCell<Context>; #[cfg(not(feature = "lib"))] pub type PathBuilderPtr = *const RefCell<PathBuilder>; #[cfg(not(feature = "lib"))] pub type PathId = u32; #[cfg(not(feature = "lib"))] pub type RasterId = u32; #[cfg(not(feature = "lib"))] pub type RasterPtr = *const RasterInner; #[cfg(not(feature = "lib"))] pub type RasterBuilderPtr = *const RefCell<RasterBuilder>; #[cfg(not(feature = "lib"))] pub type CompositionPtr = *const RefCell<Composition>; #[cfg(not(feature = "lib"))] pub type StylingPtr = *const RefCell<Styling>; #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn mold_context_create( context_ptr: *mut ContextPtr, raw_buffer: *const RawBuffer, ) { let context = Context { map: None, paths: HashMap::new(), path_index: 0, rasters: HashMap::new(), raster_index: 0, raw_buffer: (*raw_buffer).clone(), old_prints: HashSet::new(), new_prints: HashSet::new(), }; *context_ptr = Rc::into_raw(Rc::new(RefCell::new(context))); } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_context_retain(context: ContextPtr) -> SpnResult { retain_from_ptr(context); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_context_release(context: ContextPtr) -> SpnResult { Rc::from_raw(context); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_context_reset(context: ContextPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_context_status(context: ContextPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_create( context: ContextPtr, path_builder_ptr: *mut PathBuilderPtr, ) -> SpnResult { let path_builder = PathBuilder::new(clone_from_ptr(context)); *path_builder_ptr = Rc::into_raw(Rc::new(RefCell::new(path_builder))); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_retain(path_builder: PathBuilderPtr) -> SpnResult { retain_from_ptr(path_builder); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_release(path_builder: PathBuilderPtr) -> SpnResult { Rc::from_raw(path_builder); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_path_builder_flush(path_builder: PathBuilderPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_path_builder_begin(path_builder: PathBuilderPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_end( path_builder: PathBuilderPtr, path_ptr: *mut PathId, ) -> SpnResult { *path_ptr = (*path_builder).borrow_mut().build(); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_move_to( path_builder: PathBuilderPtr, x0: f32, y0: f32, ) -> SpnResult { (*path_builder).borrow_mut().move_to(x0, y0); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_line_to( path_builder: PathBuilderPtr, x1: f32, y1: f32, ) -> SpnResult { (*path_builder).borrow_mut().line_to(x1, y1); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_quad_to( path_builder: PathBuilderPtr, x1: f32, y1: f32, x2: f32, y2: f32, ) -> SpnResult { (*path_builder).borrow_mut().quad_to(x1, y1, x2, y2); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_quad_smooth_to( path_builder: PathBuilderPtr, x2: f32, y2: f32, ) -> SpnResult { (*path_builder).borrow_mut().quad_smooth_to(x2, y2); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_cubic_to( path_builder: PathBuilderPtr, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, ) -> SpnResult { (*path_builder) .borrow_mut() .cubic_to(x1, y1, x2, y2, x3, y3); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_cubic_smooth_to( path_builder: PathBuilderPtr, x2: f32, y2: f32, x3: f32, y3: f32, ) -> SpnResult { (*path_builder).borrow_mut().cubic_smooth_to(x2, y2, x3, y3); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_rat_quad_to( path_builder: PathBuilderPtr, x1: f32, y1: f32, x2: f32, y2: f32, w0: f32, ) -> SpnResult { (*path_builder).borrow_mut().rat_quad_to(x1, y1, x2, y2, w0); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_path_builder_rat_cubic_to( path_builder: PathBuilderPtr, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, w0: f32, w1: f32, ) -> SpnResult { (*path_builder) .borrow_mut() .rat_cubic_to(x1, y1, x2, y2, x3, y3, w0, w1); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_path_retain( context: ContextPtr, paths: *const PathId, count: u32, ) -> SpnResult { for &path in slice::from_raw_parts(paths, count as usize) { (*context).borrow_mut().retain_path(path); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_path_release( context: ContextPtr, paths: *const PathId, count: u32, ) -> SpnResult { for &path in slice::from_raw_parts(paths, count as usize) { (*context).borrow_mut().release_path(path); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_raster_builder_create( context: ContextPtr, raster_builder_ptr: *mut RasterBuilderPtr, ) -> SpnResult { let raster_builder = RasterBuilder::new(clone_from_ptr(context)); *raster_builder_ptr = Rc::into_raw(Rc::new(RefCell::new(raster_builder))); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_raster_builder_retain(raster_builder: RasterBuilderPtr) -> SpnResult { retain_from_ptr(raster_builder); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_raster_builder_release(raster_builder: RasterBuilderPtr) -> SpnResult { Rc::from_raw(raster_builder); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_raster_builder_flush(raster_builder: RasterBuilderPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_raster_builder_begin(raster_builder: RasterBuilderPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_raster_builder_end( raster_builder: RasterBuilderPtr, raster_ptr: *mut RasterId, ) -> SpnResult { *raster_ptr = (*raster_builder).borrow_mut().build(); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_raster_builder_add( raster_builder: RasterBuilderPtr, paths: *const PathId, _transform_weakrefs: *const (), mut transforms: *const f32, _clip_weakrefs: *const (), _clips: *const f32, count: u32, ) -> SpnResult { // TODO(dragostis): Implement Path clipping for Rasters. for &path in slice::from_raw_parts(paths, count as usize) { let mut transform = [1.0; 9]; for slot in transform.iter_mut().take(8) { *slot = transforms.read() / 32.0; transforms = transforms.add(1); } (*raster_builder) .borrow_mut() .push_path(path, &transform); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_raster_retain( context: ContextPtr, rasters: *const RasterId, count: u32, ) -> SpnResult { for &raster in slice::from_raw_parts(rasters, count as usize) { (*context).borrow_mut().retain_raster(raster); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_raster_release( context: ContextPtr, rasters: *const RasterId, count: u32, ) -> SpnResult { for &raster in slice::from_raw_parts(rasters, count as usize) { (*context).borrow_mut().release_raster(raster); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_composition_create( context: ContextPtr, composition_ptr: *mut CompositionPtr, ) -> SpnResult { let composition = Composition::new(clone_from_ptr(context)); *composition_ptr = Rc::into_raw(Rc::new(RefCell::new(composition))); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_composition_clone( context: ContextPtr, composition: CompositionPtr, clone_ptr: *mut CompositionPtr, ) -> SpnResult { *clone_ptr = Rc::into_raw(clone_from_ptr(composition)); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_composition_retain(composition: CompositionPtr) -> SpnResult { retain_from_ptr(composition); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_composition_release(composition: CompositionPtr) -> SpnResult { Rc::from_raw(composition); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_composition_place( composition: CompositionPtr, rasters: *const RasterId, layer_ids: *const u32, mut txtys: *const i32, count: u32, ) -> SpnResult { let rasters = slice::from_raw_parts(rasters, count as usize) .iter() .zip(slice::from_raw_parts(layer_ids, count as usize)); for (&raster, &layer_id) in rasters { let mut translation = Point::new(0, 0); if !txtys.is_null() { translation.x = txtys.read(); txtys = txtys.add(1); translation.y = txtys.read(); txtys = txtys.add(1); } let raster = { let borrow = (*composition).borrow(); let context = borrow.context.borrow(); RasterInner::translated(&context.get_raster(raster), translation) }; (*composition).borrow_mut().place(layer_id, raster); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_composition_seal(composition: CompositionPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_composition_unseal(composition: CompositionPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_composition_reset(composition: CompositionPtr) -> SpnResult { (*composition).borrow_mut().reset(); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_composition_get_bounds( composition: CompositionPtr, bounds: *mut i32, ) -> SpnResult { unimplemented!() } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_styling_create( context: ContextPtr, styling_ptr: *mut StylingPtr, layers_count: u32, cmds_count: u32, ) -> SpnResult { let styling = Styling::new(); *styling_ptr = Rc::into_raw(Rc::new(RefCell::new(styling))); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_retain(styling: StylingPtr) -> SpnResult { retain_from_ptr(styling); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_release(styling: StylingPtr) -> SpnResult { Rc::from_raw(styling); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_styling_seal(styling: StylingPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] #[allow(unused_variables)] pub unsafe extern "C" fn spn_styling_unseal(styling: StylingPtr) -> SpnResult { SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_reset(styling: StylingPtr) -> SpnResult { (*styling).borrow_mut().reset(); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_group_alloc(styling: StylingPtr, group_id: *mut u32) -> SpnResult { *group_id = (*styling).borrow_mut().group_alloc(); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_group_enter( styling: StylingPtr, group_id: u32, count: u32, cmds: *mut *mut u32, ) -> SpnResult { if count > 0 { *cmds = (*styling).borrow_mut().group_enter(group_id, count); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_group_leave( styling: StylingPtr, group_id: u32, count: u32, cmds: *mut *mut u32, ) -> SpnResult { if count > 0 { *cmds = (*styling).borrow_mut().group_leave(group_id, count); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_group_parents( styling: StylingPtr, group_id: u32, count: u32, parents: *mut *mut u32, ) -> SpnResult { if count > 0 { *parents = (*styling).borrow_mut().group_parents(group_id, count); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_group_range_lo( styling: StylingPtr, group_id: u32, layer_lo: u32, ) -> SpnResult { (*styling).borrow_mut().group_range_lo(group_id, layer_lo); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_group_range_hi( styling: StylingPtr, group_id: u32, layer_hi: u32, ) -> SpnResult { (*styling).borrow_mut().group_range_hi(group_id, layer_hi); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_group_layer( styling: StylingPtr, group_id: u32, layer_id: u32, count: u32, cmds: *mut *mut u32, ) -> SpnResult { if count > 0 { *cmds = (*styling).borrow_mut().layer(group_id, layer_id, count); } SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_layer_fill_rgba_encoder(mut cmds: *mut u32, rgba: &[f32; 4]) { let mut bytes = [0u8; 4]; for i in 0..4 { bytes[i] = u8::try_from((rgba[i] * 255.0).round() as u32) .expect("RGBA colors must be between 0.0 and 1.0"); } cmds.write(SPN_STYLING_OPCODE_COLOR_FILL_SOLID); cmds = cmds.add(1); cmds.write(u32::from_be_bytes(bytes)); cmds = cmds.add(1); cmds.write(0); } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_styling_background_over_encoder(mut cmds: *mut u32, rgba: &[f32; 4]) { let mut bytes = [0u8; 4]; for i in 0..4 { bytes[i] = u8::try_from((rgba[i] * 255.0).round() as u32) .expect("RGBA colors must be between 0.0 and 1.0"); } cmds.write(SPN_STYLING_OPCODE_COLOR_ACC_OVER_BACKGROUND); cmds = cmds.add(1); cmds.write(u32::from_be_bytes(bytes)); cmds = cmds.add(1); cmds.write(0); } #[cfg(not(feature = "lib"))] #[no_mangle] pub unsafe extern "C" fn spn_render(context: ContextPtr, submit: *const RenderSubmit) -> SpnResult { let submit = *submit; let width = (submit.tile_clip[2] - submit.tile_clip[0]) as usize; let height = (submit.tile_clip[3] - submit.tile_clip[1]) as usize; let mut context = (*context).borrow_mut(); let mut map = context .map .take() .filter(|map| map.width() != width || map.height() != height) .unwrap_or_else(|| Map::new(width, height)); let mut styling = (*submit.styling).borrow_mut(); let mut composition = (*submit.composition).borrow_mut(); styling.prints(&mut composition, &mut map, &mut context.new_prints); for &id in context.old_prints.difference(&context.new_prints) { map.remove(id); } context.old_prints.clear(); context.swap_prints(); map.render(context.raw_buffer.clone()); context.map = Some(map); SpnResult::SpnSuccess } #[cfg(not(feature = "lib"))] #[cfg(test)] mod tests { use super::*; use std::mem::MaybeUninit; unsafe fn init<T, U>(f: impl FnOnce(*mut T) -> U) -> T { let mut value = MaybeUninit::uninit(); f(value.as_mut_ptr()); value.assume_init() } unsafe fn band(path_builder: PathBuilderPtr, x: f32, y: f32, width: f32, height: f32) -> PathId { spn_path_builder_begin(path_builder); spn_path_builder_move_to(path_builder, x, y); spn_path_builder_line_to(path_builder, x + width, y); spn_path_builder_line_to(path_builder, x + width, y - height); spn_path_builder_line_to(path_builder, x, y - height); spn_path_builder_line_to(path_builder, x, y); init(|ptr| spn_path_builder_end(path_builder, ptr)) } unsafe fn raster(raster_builder: RasterBuilderPtr, path: PathId) -> RasterId { spn_raster_builder_begin(raster_builder); spn_raster_builder_add( raster_builder, &path, ptr::null(), [32.0, 0.0, 0.0, 0.0, 32.0, 0.0, 0.0, 0.0, 1.0].as_ptr(), ptr::null(), ptr::null(), 1, ); init(|ptr| spn_raster_builder_end(raster_builder, ptr)) } #[test] fn end_to_end() { unsafe { let width = 3; let height = 3; let buffer_size = width * height; let mut buffer: Vec<u32> = Vec::with_capacity(buffer_size); let buffer_ptr: *mut u8 = mem::transmute(buffer.as_mut_ptr()); let raw_buffer = RawBuffer { buffer_ptr: &buffer_ptr, stride: 3, format: PixelFormat::RGBA8888, }; let context = init(move |ptr| mold_context_create(ptr, &raw_buffer)); let path_builder = init(|ptr| spn_path_builder_create(context, ptr)); let band_top = band(path_builder, 1.0, 3.0, 1.0, 3.0); let band_bottom = band(path_builder, 0.0, 2.0, 3.0, 1.0); let raster_builder = init(|ptr| spn_raster_builder_create(context, ptr)); let raster_top = raster(raster_builder, band_top); let raster_bottom = raster(raster_builder, band_bottom); let composition = init(|ptr| spn_composition_create(context, ptr)); let rasters = [raster_top, raster_bottom]; spn_composition_place( composition, rasters.as_ptr(), [1, 0].as_ptr(), [0, 0, 0, 0].as_ptr(), rasters.len() as u32, ); let styling = init(|ptr| spn_styling_create(context, ptr, 2, 32)); let top_group = init(|ptr| spn_styling_group_alloc(styling, ptr)); spn_styling_group_range_lo(styling, top_group, 0); spn_styling_group_range_hi(styling, top_group, 1); let enter_cmds = init(|ptr| spn_styling_group_enter(styling, top_group, 1, ptr)); enter_cmds.write(SPN_STYLING_OPCODE_COLOR_ACC_ZERO); let mut leave_cmds = init(|ptr| spn_styling_group_leave(styling, top_group, 4, ptr)); spn_styling_background_over_encoder(leave_cmds, &[0.0, 0.0, 1.0, 1.0]); leave_cmds = leave_cmds.add(3); leave_cmds.write(SPN_STYLING_OPCODE_COLOR_ACC_STORE_TO_SURFACE); let mut layer_cmds = init(|ptr| spn_styling_group_layer(styling, top_group, 0, 6, ptr)); layer_cmds.write(SPN_STYLING_OPCODE_COVER_WIP_ZERO); layer_cmds = layer_cmds.add(1); layer_cmds.write(SPN_STYLING_OPCODE_COVER_NONZERO); layer_cmds = layer_cmds.add(1); spn_styling_layer_fill_rgba_encoder(layer_cmds, &[0.0, 1.0, 0.0, 1.0]); layer_cmds = layer_cmds.add(3); layer_cmds.write(SPN_STYLING_OPCODE_BLEND_OVER); let mut layer_cmds = init(|ptr| spn_styling_group_layer(styling, top_group, 1, 6, ptr)); layer_cmds.write(SPN_STYLING_OPCODE_COVER_WIP_ZERO); layer_cmds = layer_cmds.add(1); layer_cmds.write(SPN_STYLING_OPCODE_COVER_NONZERO); layer_cmds = layer_cmds.add(1); spn_styling_layer_fill_rgba_encoder(layer_cmds, &[1.0, 0.0, 0.0, 1.0]); layer_cmds = layer_cmds.add(3); layer_cmds.write(SPN_STYLING_OPCODE_BLEND_OVER); let submit = RenderSubmit { ext: ptr::null_mut(), styling, composition, tile_clip: [0, 0, width as u32, height as u32], }; spn_render(context, &submit); spn_styling_release(styling); spn_composition_release(composition); spn_raster_release(context, rasters.as_ptr(), rasters.len() as u32); spn_raster_builder_release(raster_builder); let paths = [band_top, band_bottom]; spn_path_release(context, paths.as_ptr(), paths.len() as u32); spn_path_builder_release(path_builder); spn_context_release(context); buffer.set_len(buffer_size); assert_eq!(buffer, vec![ 0xffff_0000, 0x0000_00ff, 0xffff_0000, 0x0000_ff00, 0x0000_ff00, 0x0000_ff00, 0xffff_0000, 0x0000_00ff, 0xffff_0000, ]); } } }
//TODO : Finish refactoring. // - Move config to it's own module // - Consider moving command out // - Do stuff and things use std::io::*; use std::net::*; use std::sync::mpsc::*; use std::thread; use regex::Regex; use irc::message::*; pub struct Config { pub nick: String, pub server_address: String, pub channels_to_join: Vec<String>, } pub enum Command { Initialize, Ping(String), ProcessLine(String), } pub struct Server { pub stream: TcpStream, pub tx: Sender<Command>, pub rx: Receiver<Command>, pub settings: Config, } impl Server { pub fn connect(config: Config) -> Server { println!("Trying to connect to: {}", config.server_address); let connection = match TcpStream::connect(&*config.server_address) { Ok(s) => s, Err(e) => panic!("Tcp Connection Error: {}", e), }; let (tx, rx) = channel(); Server { stream: connection, tx: tx, rx: rx, settings: config, } } pub fn spawn_reader(&self, tx: Sender<Command>) { let mut reader = BufReader::new(self.stream.try_clone().unwrap()); thread::spawn(move || { let mut line = String::new(); reader.read_line(&mut line) .ok() .expect("Shazbot!"); for line in reader.lines() { let value = match line { Ok(l) => l, Err(e) => panic!("Error {}", e), }; println!("Output: {}", value); if value.contains("No Ident response") { tx.send(Command::Initialize).unwrap(); } else if value.starts_with("PING") { tx.send(Command::Ping(value)).unwrap(); } else { tx.send(Command::ProcessLine(value)).unwrap(); } } }); } pub fn spawn_writer(&self) { let mut writer = self.stream.try_clone().unwrap(); for x in self.rx.iter() { match x { Command::ProcessLine(ref s) => { match Message::parse(s) { Some(x) => { let response = format!("PRIVMSG {} :Hello, {}. You said: {}\r\n", x.channel, x.from_nick, x.message); println!("{}", response); writer.write(response.as_bytes()).unwrap(); }, None => {} } }, Command::Ping(ref s) => { let ping = Regex::new(r"PING :(.*)").unwrap(); for c in ping.captures_iter(s) { let pong = format!("PONG :{}", c.at(1).unwrap_or("")); println!("RESPONSE: {}", pong); writer.write(pong.as_bytes()).unwrap(); } }, Command::Initialize => { let user_handshake = format!("USER {} 0 * :rusty bot\r\n", self.settings.nick); let nick_handshake = format!("NICK :{}\r\n", self.settings.nick); writer.write(user_handshake.as_bytes()) .ok() .expect("User failed"); // Note: Will not pass ident without nick command writer.write(nick_handshake.as_bytes()) .ok() .expect("Nick failed"); for c in &self.settings.channels_to_join { writer.write(format!("JOIN {}\r\n", c).as_bytes()) .ok() .expect("Join failed"); } } } } } }
use std::fs::File; use std::io::Read; struct Param { mode: u8, value: i64, } impl Param { fn new(vec: &Vec<i64>, index: usize, param_index: usize) -> Param { let mode = ((vec[index] / 10i64.pow((param_index + 1) as u32)) % 10) as u8; let value = vec[index + param_index]; assert!(mode == 0 || mode == 1); Param { mode, value } } fn get_value(&self, vec: &Vec<i64>) -> i64 { match self.mode { 0 => vec[self.value as usize], 1 => self.value, u => panic!("Unimplemented mode: {}", u), } } } fn get_params(vec: &Vec<i64>, index: usize, num_params: usize) -> Vec<Param> { let mut params = Vec::new(); for i in 1..num_params+1 { params.push(Param::new(vec, index, i)); } params } fn op_add(vec: &mut Vec<i64>, index: usize) -> usize { let params = get_params(vec, index, 3); assert!(params[2].mode == 0); vec[params[2].value as usize] = params[0].get_value(vec) + params[1].get_value(vec); index + 4 } fn op_mul(vec: &mut Vec<i64>, index: usize) -> usize { let params = get_params(vec, index, 3); vec[params[2].value as usize] = params[0].get_value(vec) * params[1].get_value(vec); index + 4 } fn op_input(vec: &mut Vec<i64>, index: usize) -> usize { let params = get_params(vec, index, 1); assert!(params[0].mode == 0); vec[params[0].value as usize] = 5; index + 2 } fn op_output(vec: &Vec<i64>, index: usize) -> usize { let params = get_params(vec, index, 1); println!("Output command: {}", params[0].get_value(vec)); index + 2 } fn op_jump_if_true(vec: &Vec<i64>, index: usize) -> usize { let params = get_params(vec, index, 2); if params[0].get_value(vec) != 0 { params[1].get_value(vec) as usize } else { index + 3 } } fn op_jump_if_false(vec: &Vec<i64>, index: usize) -> usize { let params = get_params(vec, index, 2); if params[0].get_value(vec) == 0 { params[1].get_value(vec) as usize } else { index + 3 } } fn op_lessthan(vec: &mut Vec<i64>, index: usize) -> usize { let params = get_params(vec, index, 3); assert!(params[2].mode == 0); let to_store; if params[0].get_value(vec) < params[1].get_value(vec) { to_store = 1; } else { to_store = 0; } vec[params[2].value as usize] = to_store; index + 4 } fn op_equal(vec: &mut Vec<i64>, index: usize) -> usize { let params = get_params(vec, index, 3); assert!(params[2].mode == 0); let to_store; if params[0].get_value(vec) == params[1].get_value(vec) { to_store = 1; } else { to_store = 0; } vec[params[2].value as usize] = to_store; index + 4 } fn run_program(mut vec: Vec<i64>) { let mut op_index = 0; while op_index < vec.len() { match vec[op_index] % 100 { 1 => op_index = op_add(&mut vec, op_index), 2 => op_index = op_mul(&mut vec, op_index), 3 => op_index = op_input(&mut vec, op_index), 4 => op_index = op_output(&vec, op_index), 5 => op_index = op_jump_if_true(&vec, op_index), 6 => op_index = op_jump_if_false(&vec, op_index), 7 => op_index = op_lessthan(&mut vec, op_index), 8 => op_index = op_equal(&mut vec, op_index), 99 => break, _ => panic!("Invalid opcode!"), } } } pub fn run_puzzle() { let mut file = File::open("input_day5.txt").expect("Failed to open input_day5.txt"); let mut ops_string = String::new(); file.read_to_string(&mut ops_string).unwrap(); let vec: Vec<i64> = ops_string.split(',').map(|text| text.trim().parse().unwrap()).collect(); run_program(vec); }
// Export these crates publicly so we can have a single reference pub use tracing; pub use tracing::instrument;
use borsh::{BorshDeserialize, BorshSerialize}; use near_sdk::{ // callback, // callback_vec, env, ext_contract, near_bindgen, Promise, PromiseOrValue, }; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; // Prepaid gas for making a single simple call. const SINGLE_CALL_GAS: u64 = 200000000000000; #[near_bindgen] #[derive(Default, BorshDeserialize, BorshSerialize)] pub struct CrossContract {} // One can provide a name, e.g. `ext` to use for generated methods. #[ext_contract(ext)] pub trait ExtCrossContract { fn merge_sort(&self, arr: Vec<u8>) -> PromiseOrValue<Vec<u8>>; fn merge( &self, #[callback] #[serializer(borsh)] data0: Vec<u8>, #[callback] #[serializer(borsh)] data1: Vec<u8>, ) -> Vec<u8>; } // If the name is not provided, the namespace for generated methods in derived by applying snake // case to the trait name, e.g. ext_status_message. #[ext_contract] pub trait ExtStatusMessage { fn set_status(&mut self, message: String); fn get_status(&self, account_id: String) -> Option<String>; } #[near_bindgen] impl CrossContract { pub fn deploy_status_message(&self, account_id: String, amount: u64) { Promise::new(account_id) .create_account() .transfer(amount as u128) .add_full_access_key(env::signer_account_pk()) .deploy_contract( include_bytes!("../status-message-contract/status_message.wasm").to_vec(), ); } #[result_serializer(borsh)] pub fn merge_sort(&self, arr: Vec<u8>) -> PromiseOrValue<Vec<u8>> { if arr.len() <= 1 { return PromiseOrValue::Value(arr); } let pivot = arr.len() / 2; let arr0 = arr[..pivot].to_vec(); let arr1 = arr[pivot..].to_vec(); let prepaid_gas = env::prepaid_gas(); let account_id = env::current_account_id(); ext::merge_sort(arr0, &account_id, 0, prepaid_gas / 4) .and(ext::merge_sort(arr1, &account_id, 0, prepaid_gas / 4)) .then(ext::merge(&account_id, 0, prepaid_gas / 4)) .into() } fn internal_merge(&self, arr0: Vec<u8>, arr1: Vec<u8>) -> Vec<u8> { let mut i = 0usize; let mut j = 0usize; let mut result = vec![]; loop { if i == arr0.len() { result.extend(&arr1[j..]); break; } if j == arr1.len() { result.extend(&arr0[i..]); break; } if arr0[i] < arr1[j] { result.push(arr0[i]); i += 1; } else { result.push(arr1[j]); j += 1; } } result } /// Used for callbacks only. Merges two sorted arrays into one. Panics if it is not called by /// the contract itself. #[result_serializer(borsh)] pub fn merge( &self, #[callback] #[serializer(borsh)] data0: Vec<u8>, #[callback] #[serializer(borsh)] data1: Vec<u8>, ) -> Vec<u8> { env::log(format!("Received {:?} and {:?}", data0, data1).as_bytes()); assert_eq!(env::current_account_id(), env::predecessor_account_id()); let result = self.internal_merge(data0, data1); env::log(format!("Merged {:?}", result).as_bytes()); result } // /// Alternative implementation of merge that demonstrates usage of callback_vec. Uncomment // /// to use. // pub fn merge(&self, #[callback_vec] #[serializer(borsh)] arrs: &mut Vec<Vec<u8>>) -> Vec<u8> { // assert_eq!(env::current_account_id(), env::predecessor_account_id()); // self.internal_merge(arrs.pop().unwrap(), arrs.pop().unwrap()) // } pub fn simple_call(&mut self, account_id: String, message: String) { ext_status_message::set_status(message, &account_id, 0, SINGLE_CALL_GAS); } pub fn complex_call(&mut self, account_id: String, message: String) -> Promise { // 1) call status_message to record a message from the signer. // 2) call status_message to retrieve the message of the signer. // 3) return that message as its own result. // Note, for a contract to simply call another contract (1) is sufficient. ext_status_message::set_status(message, &account_id, 0, SINGLE_CALL_GAS).then( ext_status_message::get_status( env::signer_account_id(), &account_id, 0, SINGLE_CALL_GAS, ), ) } pub fn transfer_money(&mut self, account_id: String, amount: u64) { Promise::new(account_id).transfer(amount as u128); } }
use std::ops::{Deref, DerefMut}; use crate::font::Font; use nannou::wgpu::Texture; use utopia_animations::{ widgets::{animated::Animated as AnimatedWidget, AnimationExt}, CanTween, Linear, }; use utopia_core::{ controllers::TypedController, lens::{Lens, NoLens}, widgets::{ controlled::Controlled as ControlledWidget, lens::LensWrap as LensWrapWidget, pod::WidgetPod, styled::Styled as StyledWidget, CoreExt, TypedWidget, }, }; use utopia_decorations::widgets::{ background::Background as BackgroundWidget, border::Border as BorderWidget, scale::Scale as ScaleWidget, DecorationsExt, }; use utopia_image::widgets::image::Image as ImageWidget; use utopia_layout::{ widgets::{ align::Align as AlignWidget, flex::Flex as FlexWidget, max_size::MaxSize as MaxSizeWidget, min_size::MinSize as MinSizeWidget, padding::Padding as PaddingWidget, stack::Stack as StackWidget, LayoutExt, }, SizeConstraint, }; use utopia_scroll::widgets::scrollview::ScrollView as ScrollViewWidget; use utopia_text::widgets::{label::Label as LabelWidget, text::Text as TextWidget}; use crate::NannouBackend; pub type Align<T> = AlignWidget<T, NannouBackend>; pub type Color = nannou::color::Srgb<u8>; pub type Controlled<T, W, C> = ControlledWidget<T, W, C, NannouBackend>; pub type Image = ImageWidget<Texture>; pub type NannouWidgetPod<T> = WidgetPod<T, NannouBackend>; pub type Flex<T> = FlexWidget<T, NannouBackend>; pub type Text = TextWidget<Font, Color>; pub type Label = LabelWidget<Font, Color>; pub type Border<T> = BorderWidget<T, Color, NannouBackend>; pub type Background<T> = BackgroundWidget<T, Color, NannouBackend>; pub type LensWrap<T, U, L, W> = LensWrapWidget<T, U, L, W, NannouBackend>; pub type Padding<T> = PaddingWidget<T, NannouBackend>; pub type MinSize<T> = MinSizeWidget<T, NannouBackend>; pub type MaxSize<T> = MaxSizeWidget<T, NannouBackend>; pub type Styled<U, L, LW, W, TW> = StyledWidget<U, L, LW, W, TW, NannouBackend>; pub type ScrollView<T> = ScrollViewWidget<T, NannouBackend>; pub type Stack<T> = StackWidget<T, NannouBackend>; pub type Scale<T> = ScaleWidget<T, NannouBackend>; pub type Animated<T, U, L, EF, TW, W, LTU = NoLens> = AnimatedWidget<T, U, L, EF, TW, W, NannouBackend, LTU>; pub trait WidgetExt<T>: TypedWidget<T, NannouBackend> + Sized + 'static { // ---- // LayoutExt // ---- fn padding(self) -> Padding<T> { LayoutExt::<T, NannouBackend>::padding(self) } fn align(self) -> Align<T> { LayoutExt::<T, NannouBackend>::align(self) } fn centered(self) -> Align<T> { LayoutExt::<T, NannouBackend>::centered(self) } fn min_size(self, constraint: SizeConstraint) -> MinSize<T> { MinSize::new(self, constraint) } fn max_size(self, constraint: SizeConstraint) -> MaxSize<T> { MaxSize::new(self, constraint) } // ---- // ScrollExt // ---- fn scroll(self) -> ScrollView<T> { ScrollView::new(self) } // ---- // DecorationsExt // ---- fn border(self) -> Border<T> { DecorationsExt::<T, NannouBackend>::border(self) } fn background(self) -> Background<T> { DecorationsExt::<T, NannouBackend>::background(self) } fn scaled(self) -> Scale<T> { DecorationsExt::<T, NannouBackend>::scaled(self) } // ---- // CoreExt // ---- fn boxed(self) -> Box<Self> { Box::new(self) } fn controlled<C: TypedController<T, Self, NannouBackend>>( self, controller: C, ) -> Controlled<T, Self, C> { CoreExt::<T, NannouBackend>::controlled(self, controller) } fn styled<U: Clone, W, L: Lens<T, U>, LW: Lens<W, U>>( self, lens: L, lens_widget: LW, ) -> Styled<U, L, LW, W, Self> where Self: Deref<Target = W> + DerefMut, { Styled::new::<T>(self, lens, lens_widget) } // ---- // AnimationExt // ---- fn animate<L: Lens<<Self as Deref>::Target, U>, U: Clone + CanTween>( self, lens: L, target: U, ) -> Animated<T, U, L, Linear, Self, <Self as Deref>::Target> where Self: Deref + DerefMut, <Self as Deref>::Target: Sized, { AnimationExt::animate(self, lens, target) } fn animate_from_data< L: Lens<<Self as Deref>::Target, U>, LTU: Lens<T, U>, U: Clone + CanTween, >( self, lens: L, target: LTU, ) -> Animated<T, U, L, Linear, Self, <Self as Deref>::Target, LTU> where Self: Deref + DerefMut, <Self as Deref>::Target: Sized, { AnimationExt::animate_from_data(self, lens, target) } } pub trait LensExt<T>: Sized + 'static { fn lens<U, L: Lens<T, U>>(self, lens: L) -> LensWrap<T, U, L, Self> where Self: TypedWidget<U, NannouBackend>, { LensWrap::new(self, lens) } } impl<T, W: 'static> LensExt<T> for W {} impl<T, W: TypedWidget<T, NannouBackend> + Sized + 'static> WidgetExt<T> for W {}
mod extensions; mod language_client; mod language_server_protocol; mod logger; mod rpcclient; mod rpchandler; mod sign; mod types; mod utils; mod viewport; mod vim; mod vimext; mod watcher; use anyhow::Result; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use types::State; #[macro_use] extern crate clap; #[macro_use] extern crate lazy_static; fn main() -> Result<()> { let _ = clap::app_from_crate!().get_matches(); let (tx, rx) = crossbeam::channel::unbounded(); let language_client = language_client::LanguageClient { version: env!("CARGO_PKG_VERSION").into(), state_mutex: Arc::new(Mutex::new(State::new(tx)?)), clients_mutex: Arc::new(Mutex::new(HashMap::new())), }; language_client.loop_call(&rx) }
use serde::{Deserialize}; use web_view::*; use sdl2::audio::{AudioCallback, AudioSpec, AudioSpecDesired}; use std::sync::{Arc,Mutex}; pub const SAMPLE_FREQUENCY: i32 = 44_100; pub const SAMPLE_COUNT: u16 = 256; pub const CHANNEL_COUNT: u8 = 2; pub const SAMPLE_BUFFER_SIZE: usize = SAMPLE_COUNT as usize * CHANNEL_COUNT as usize; pub static ZERO_BUFFER: [f32; SAMPLE_BUFFER_SIZE] = [0f32; SAMPLE_BUFFER_SIZE]; pub struct AudioState { clicky: bool, } pub struct Device { audio_spec: Option<AudioSpec>, audio_state: Arc<Mutex<AudioState>>, } impl Device { pub fn new(state: Arc<Mutex<AudioState>>) -> Device { Device { audio_spec: None, audio_state: state, } } pub fn receive_spec(&mut self, spec: AudioSpec) { self.audio_spec = Some(spec); } } impl AudioCallback for Device { type Channel = f32; fn callback(&mut self, out: &mut [f32]) { out.clone_from_slice(&ZERO_BUFFER); let state = self.audio_state.lock().unwrap(); if !state.clicky { return; } for i in 0..out.len() { out[i] += (i as f32 * 0.01f32).sin(); } } } #[derive(Deserialize)] #[serde(tag = "command", rename_all = "camelCase")] pub enum CommandFromJS { Message { message: String }, Click, Unclick, } fn main() { let html = format!(r#" <!doctype html> <html> <head> <style type="text/css">{css}</style> </head> <body> <script type="text/javascript">{js}</script> </body> </html> "#, css = include_str!("../view/styles.css"), js = include_str!("../view_build/bundle.js") ); let audio_state = Arc::new(Mutex::new(AudioState { clicky: false })); let mut audio_device = Device::new(audio_state.clone()); let sdl_context = sdl2::init().unwrap(); let audio = sdl_context.audio().unwrap(); let desired_spec = AudioSpecDesired { freq: Some(SAMPLE_FREQUENCY), channels: Some(CHANNEL_COUNT), samples: Some(SAMPLE_COUNT), }; let device = audio .open_playback(None, &desired_spec, |spec| { audio_device.receive_spec(spec); audio_device }) .unwrap(); device.resume(); web_view::builder() .title("rsynth") .content(Content::Html(html)) .size(800, 600) .resizable(true) .debug(true) .user_data(()) .invoke_handler(|_webview, arg| { use CommandFromJS::*; match serde_json::from_str(arg).unwrap() { Message { message } => { println!("JS said: {}", message); }, Click => { let mut state = audio_state.lock().unwrap(); state.clicky = true; }, Unclick => { let mut state = audio_state.lock().unwrap(); state.clicky = false; }, }; Ok(()) // webview.eval("setTimeout(() => document.body.innerHTML = '<h1>Hello from Rust</h1>', 1000);") }) .build() .unwrap() .run() .unwrap(); }
use super::*; #[test] fn with_different_process_sends_message_when_timer_expires() { run!( |arc_process| { ( Just(arc_process.clone()), milliseconds(), strategy::term(arc_process.clone()), ) }, |(arc_process, milliseconds, message)| { let time = arc_process.integer(milliseconds); let destination_arc_process = test::process::child(&arc_process); let destination = destination_arc_process.pid_term(); let start_monotonic = freeze_timeout(); let result = result(arc_process.clone(), time, destination, message); prop_assert!( result.is_ok(), "Timer reference not returned. Got {:?}", result ); let timer_reference = result.unwrap(); prop_assert!(timer_reference.is_boxed_local_reference()); prop_assert!(!has_message(&destination_arc_process, message)); freeze_at_timeout(start_monotonic + milliseconds + Milliseconds(1)); prop_assert!(has_message(&destination_arc_process, message)); Ok(()) }, ); } #[test] fn with_same_process_sends_message_when_timer_expires() { run!( |arc_process| { ( Just(arc_process.clone()), milliseconds(), strategy::term(arc_process), ) }, |(arc_process, milliseconds, message)| { let time = arc_process.integer(milliseconds); let destination = arc_process.pid_term(); let start_monotonic = freeze_timeout(); let result = result(arc_process.clone(), time, destination, message); prop_assert!( result.is_ok(), "Timer reference not returned. Got {:?}", result ); let timer_reference = result.unwrap(); prop_assert!(timer_reference.is_boxed_local_reference()); prop_assert!(!has_message(&arc_process, message)); freeze_at_timeout(start_monotonic + milliseconds + Milliseconds(1)); prop_assert!(has_message(&arc_process, message)); Ok(()) }, ); } #[test] fn without_process_sends_nothing_when_timer_expires() { run!( |arc_process| { ( Just(arc_process.clone()), milliseconds(), strategy::term(arc_process.clone()), ) }, |(arc_process, milliseconds, message)| { let time = arc_process.integer(milliseconds); let destination = Pid::next_term(); let start_monotonic = freeze_timeout(); let result = result(arc_process.clone(), time, destination, message); prop_assert!( result.is_ok(), "Timer reference not returned. Got {:?}", result ); let timer_reference = result.unwrap(); prop_assert!(timer_reference.is_boxed_local_reference()); freeze_at_timeout(start_monotonic + milliseconds + Milliseconds(1)); // does not send to original process either prop_assert!(!has_message(&arc_process, message)); Ok(()) }, ); }
/* * NOTE: headers are stored in a BTreeMap. It would be faster to use a HashMap * instead but the order in which they are displayed would become * non-deterministic. */ use std::collections::BTreeMap; use std::collections::btree_map::IntoIter; #[derive(Clone)] pub struct Headers { headers: BTreeMap<String, String> } impl Headers { pub fn new() -> Headers { Headers { headers: BTreeMap::new() } } pub fn get(&self, name: &str) -> Option<&String> { self.headers.get(&name.to_lowercase()) } pub fn set(&mut self, name: &str, value: &str) { self.headers.insert(name.to_lowercase(), value.into()); } pub fn contains_key(&self, name: &str) -> bool { self.headers.contains_key(&name.to_lowercase()) } } impl<'a> IntoIterator for &'a Headers { type Item = (String, String); type IntoIter = IntoIter<String, String>; fn into_iter(self) -> Self::IntoIter { self.headers.clone().into_iter() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_set() { let mut headers = Headers::new(); headers.set("content-type".into(), "text/html".into()); assert_eq!(headers.get("content-type"), Some(&"text/html".into())); // The name of the header is case insensitive headers.set("Content-Type".into(), "text/plain".into()); assert_eq!(headers.get("content-type"), Some(&"text/plain".into())); } #[test] fn test_get() { let mut headers = Headers::new(); assert_eq!(headers.get("not-set"), None); headers.set("content-type".into(), "text/html".into()); assert_eq!(headers.get("content-type"), Some(&"text/html".into())); // The name of the header is case insensitive assert_eq!(headers.get("Content-Type"), Some(&"text/html".into())); } }
#[doc = "Reader of register ITLINE26"] pub type R = crate::R<u32, super::ITLINE26>; #[doc = "Reader of field `SPI2`"] pub type SPI2_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - SPI2"] #[inline(always)] pub fn spi2(&self) -> SPI2_R { SPI2_R::new((self.bits & 0x01) != 0) } }
mod systems; mod components; mod models; mod rpops_instance; pub use crate::prelude::*; pub mod prelude { pub use crate::systems::*; pub use crate::components::*; pub use crate::models::*; pub use crate::rpops_instance::*; pub use vermarine_engine::prelude::*; }