hexsha
stringlengths
40
40
size
int64
4
1.05M
content
stringlengths
4
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
565862bb4b2095eae009185d0fcbe14e675aa680
158
// Copyright 2020-2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 mod ask; pub mod test_utils; pub use ask::ask; pub use utils_derive::GuardDebug;
19.75
38
0.759494
7127a2224fb40602d194edfdb22f262283e0188d
116
#[cfg(feature = "Win32_Data_Xml_MsXml")] pub mod MsXml; #[cfg(feature = "Win32_Data_Xml_XmlLite")] pub mod XmlLite;
23.2
42
0.741379
90b6674ab20cef5881300d5bd42db5f0ec49b8de
4,738
//! Low level directory entry iterator. use crate::cluster::Cluster; use crate::filesystem::FatFileSystem; use crate::offset_iter::ClusterOffsetIter; use crate::FatError; use crate::FatFileSystemResult; use storage_device::StorageDevice; use super::raw_dir_entry::FatDirEntry; use super::FatFsType; use crate::utils::FileSystemIterator; /// Represent a raw FAT directory entries iterator. pub struct FatDirEntryIterator { /// The cluster iterator. pub(crate) cluster_iter: Option<ClusterOffsetIter>, /// The last cluster used. pub last_cluster: Option<Cluster>, /// The initial offset of the iterator in the first cluster. pub cluster_offset: u64, /// The current iteration point in the block. pub counter: u8, /// Used at the first iteration to init the counter. pub is_first: bool, } impl FatDirEntryIterator { /// Create a new iterator from a cluster, a block index and an offset (representing the starting point of the iterator). pub fn new<S: StorageDevice>( fs: &FatFileSystem<S>, start_cluster: Cluster, cluster_offset: u64, offset: u64, in_root_directory: bool, ) -> Self { let cluster_iter = if in_root_directory { match fs.boot_record.fat_type { FatFsType::Fat12 | FatFsType::Fat16 => None, FatFsType::Fat32 => Some(ClusterOffsetIter::new( fs, start_cluster, Some(cluster_offset), )), _ => unimplemented!(), } } else { Some(ClusterOffsetIter::new( fs, start_cluster, Some(cluster_offset), )) }; FatDirEntryIterator { counter: (offset / FatDirEntry::LEN as u64) as u8, cluster_offset, is_first: true, cluster_iter, last_cluster: None, } } } impl<S: StorageDevice> FileSystemIterator<S> for FatDirEntryIterator { type Item = FatFileSystemResult<FatDirEntry>; fn next(&mut self, filesystem: &FatFileSystem<S>) -> Option<FatFileSystemResult<FatDirEntry>> { let block_size = filesystem.boot_record.bytes_per_block() as usize; let entry_per_block_count = (block_size / FatDirEntry::LEN) as u8; let cluster_opt = if self.counter == entry_per_block_count || self.is_first { if !self.is_first { self.counter = 0; self.cluster_offset += block_size as u64; } self.is_first = false; if let Some(cluster_iter) = &mut self.cluster_iter { self.cluster_offset %= u64::from(filesystem.boot_record.blocks_per_cluster()) * block_size as u64; self.last_cluster = cluster_iter.next(filesystem); } else { self.last_cluster = Some(Cluster(0)); } self.last_cluster } else { self.last_cluster }; let cluster = cluster_opt?; let mut raw_data = [0x0u8; FatDirEntry::LEN]; let entry_index = (self.counter % entry_per_block_count) as usize; let cluster_position_opt = if self.cluster_iter.is_none() { let root_dir_blocks = ((u32::from(filesystem.boot_record.root_dir_childs_count()) * 32) + (u32::from(filesystem.boot_record.bytes_per_block()) - 1)) / u32::from(filesystem.boot_record.bytes_per_block()); let root_dir_offset = root_dir_blocks * u32::from(filesystem.boot_record.bytes_per_block()); if self.cluster_offset > u64::from(root_dir_offset) { None } else { Some( filesystem.first_data_offset - u64::from(root_dir_offset) + self.cluster_offset, ) } } else { Some(cluster.to_data_bytes_offset(filesystem) + self.cluster_offset) }; let entry_start: u64 = (entry_index * FatDirEntry::LEN) as u64; let read_res = filesystem .storage_device .lock() .read( filesystem.partition_start + cluster_position_opt? + entry_start, &mut raw_data, ) .or(Err(FatError::ReadFailed)); if let Err(error) = read_res { return Some(Err(error)); } let dir_entry = FatDirEntry::from_raw(&raw_data, cluster, self.cluster_offset, entry_start); // The entry isn't a valid one but this doesn't mark the end of the directory self.counter += 1; Some(Ok(dir_entry)) } }
32.902778
126
0.586323
5d58dd2d9377741271656235d90fb65108560259
3,795
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Lock Bits Word 0"] pub lockbit_word0: LOCKBIT_WORD0, #[doc = "0x04 - Lock Bits Word 1"] pub lockbit_word1: LOCKBIT_WORD1, #[doc = "0x08 - Lock Bits Word 2"] pub lockbit_word2: LOCKBIT_WORD2, #[doc = "0x0c - Lock Bits Word 3"] pub lockbit_word3: LOCKBIT_WORD3, } #[doc = "Lock Bits Word 0\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 [lockbit_word0](lockbit_word0) module"] pub type LOCKBIT_WORD0 = crate::Reg<u32, _LOCKBIT_WORD0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _LOCKBIT_WORD0; #[doc = "`read()` method returns [lockbit_word0::R](lockbit_word0::R) reader structure"] impl crate::Readable for LOCKBIT_WORD0 {} #[doc = "`write(|w| ..)` method takes [lockbit_word0::W](lockbit_word0::W) writer structure"] impl crate::Writable for LOCKBIT_WORD0 {} #[doc = "Lock Bits Word 0"] pub mod lockbit_word0; #[doc = "Lock Bits Word 1\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 [lockbit_word1](lockbit_word1) module"] pub type LOCKBIT_WORD1 = crate::Reg<u32, _LOCKBIT_WORD1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _LOCKBIT_WORD1; #[doc = "`read()` method returns [lockbit_word1::R](lockbit_word1::R) reader structure"] impl crate::Readable for LOCKBIT_WORD1 {} #[doc = "`write(|w| ..)` method takes [lockbit_word1::W](lockbit_word1::W) writer structure"] impl crate::Writable for LOCKBIT_WORD1 {} #[doc = "Lock Bits Word 1"] pub mod lockbit_word1; #[doc = "Lock Bits Word 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 [lockbit_word2](lockbit_word2) module"] pub type LOCKBIT_WORD2 = crate::Reg<u32, _LOCKBIT_WORD2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _LOCKBIT_WORD2; #[doc = "`read()` method returns [lockbit_word2::R](lockbit_word2::R) reader structure"] impl crate::Readable for LOCKBIT_WORD2 {} #[doc = "`write(|w| ..)` method takes [lockbit_word2::W](lockbit_word2::W) writer structure"] impl crate::Writable for LOCKBIT_WORD2 {} #[doc = "Lock Bits Word 2"] pub mod lockbit_word2; #[doc = "Lock Bits Word 3\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 [lockbit_word3](lockbit_word3) module"] pub type LOCKBIT_WORD3 = crate::Reg<u32, _LOCKBIT_WORD3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _LOCKBIT_WORD3; #[doc = "`read()` method returns [lockbit_word3::R](lockbit_word3::R) reader structure"] impl crate::Readable for LOCKBIT_WORD3 {} #[doc = "`write(|w| ..)` method takes [lockbit_word3::W](lockbit_word3::W) writer structure"] impl crate::Writable for LOCKBIT_WORD3 {} #[doc = "Lock Bits Word 3"] pub mod lockbit_word3;
66.578947
413
0.712516
230bf150a1c468d80659ac3e7fde042787216377
558
type ctxt = { v: uint }; iface get_ctxt { // Here the `&` is bound in the method definition: fn get_ctxt() -> &ctxt; } type has_ctxt = { c: &ctxt }; impl of get_ctxt for has_ctxt { // Here an error occurs because we used `&self` but // the definition used `&`: fn get_ctxt() -> &self/ctxt { //~ ERROR method `get_ctxt` has an incompatible type self.c } } fn get_v(gc: get_ctxt) -> uint { gc.get_ctxt().v } fn main() { let ctxt = { v: 22u }; let hc = { c: &ctxt }; assert get_v(hc as get_ctxt) == 22u; }
19.241379
86
0.571685
bf254e4988870867b9ae9cf1be5e6e9f73c42303
24,136
//! Code for building the graph used by `cargo tree`. use super::TreeOptions; use crate::core::compiler::{CompileKind, RustcTargetData}; use crate::core::dependency::DepKind; use crate::core::resolver::features::{CliFeatures, FeaturesFor, ResolvedFeatures}; use crate::core::resolver::Resolve; use crate::core::{FeatureMap, FeatureValue, Package, PackageId, PackageIdSpec, Workspace}; use crate::util::interning::InternedString; use crate::util::CargoResult; use std::collections::{HashMap, HashSet}; #[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)] pub enum Node { Package { package_id: PackageId, /// Features that are enabled on this package. features: Vec<InternedString>, kind: CompileKind, }, Feature { /// Index of the package node this feature is for. node_index: usize, /// Name of the feature. name: InternedString, }, } /// The kind of edge, for separating dependencies into different sections. #[derive(Debug, Copy, Hash, Eq, Clone, PartialEq)] pub enum EdgeKind { Dep(DepKind), Feature, } /// Set of outgoing edges for a single node. /// /// Edges are separated by the edge kind (`DepKind` or `Feature`). This is /// primarily done so that the output can easily display separate sections /// like `[build-dependencies]`. /// /// The value is a `Vec` because each edge kind can have multiple outgoing /// edges. For example, package "foo" can have multiple normal dependencies. #[derive(Clone)] struct Edges(HashMap<EdgeKind, Vec<usize>>); impl Edges { fn new() -> Edges { Edges(HashMap::new()) } /// Adds an edge pointing to the given node. fn add_edge(&mut self, kind: EdgeKind, index: usize) { let indexes = self.0.entry(kind).or_default(); if !indexes.contains(&index) { indexes.push(index) } } } /// A graph of dependencies. pub struct Graph<'a> { nodes: Vec<Node>, /// The indexes of `edges` correspond to the `nodes`. That is, `edges[0]` /// is the set of outgoing edges for `nodes[0]`. They should always be in /// sync. edges: Vec<Edges>, /// Index maps a node to an index, for fast lookup. index: HashMap<Node, usize>, /// Map for looking up packages. package_map: HashMap<PackageId, &'a Package>, /// Set of indexes of feature nodes that were added via the command-line. /// /// For example `--features foo` will mark the "foo" node here. cli_features: HashSet<usize>, /// Map of dependency names, used for building internal feature map for /// dep_name/feat_name syntax. /// /// Key is the index of a package node, value is a map of dep_name to a /// set of `(pkg_node_index, is_optional)`. dep_name_map: HashMap<usize, HashMap<InternedString, HashSet<(usize, bool)>>>, } impl<'a> Graph<'a> { fn new(package_map: HashMap<PackageId, &'a Package>) -> Graph<'a> { Graph { nodes: Vec::new(), edges: Vec::new(), index: HashMap::new(), package_map, cli_features: HashSet::new(), dep_name_map: HashMap::new(), } } /// Adds a new node to the graph, returning its new index. fn add_node(&mut self, node: Node) -> usize { let from_index = self.nodes.len(); self.nodes.push(node); self.edges.push(Edges::new()); self.index .insert(self.nodes[from_index].clone(), from_index); from_index } /// Returns a list of nodes the given node index points to for the given kind. pub fn connected_nodes(&self, from: usize, kind: &EdgeKind) -> Vec<usize> { match self.edges[from].0.get(kind) { Some(indexes) => { // Created a sorted list for consistent output. let mut indexes = indexes.clone(); indexes.sort_unstable_by(|a, b| self.nodes[*a].cmp(&self.nodes[*b])); indexes } None => Vec::new(), } } /// Returns `true` if the given node has any outgoing edges. pub fn has_outgoing_edges(&self, index: usize) -> bool { !self.edges[index].0.is_empty() } /// Gets a node by index. pub fn node(&self, index: usize) -> &Node { &self.nodes[index] } /// Given a slice of PackageIds, returns the indexes of all nodes that match. pub fn indexes_from_ids(&self, package_ids: &[PackageId]) -> Vec<usize> { let mut result: Vec<(&Node, usize)> = self .nodes .iter() .enumerate() .filter(|(_i, node)| match node { Node::Package { package_id, .. } => package_ids.contains(package_id), _ => false, }) .map(|(i, node)| (node, i)) .collect(); // Sort for consistent output (the same command should always return // the same output). "unstable" since nodes should always be unique. result.sort_unstable(); result.into_iter().map(|(_node, i)| i).collect() } pub fn package_for_id(&self, id: PackageId) -> &Package { self.package_map[&id] } fn package_id_for_index(&self, index: usize) -> PackageId { match self.nodes[index] { Node::Package { package_id, .. } => package_id, Node::Feature { .. } => panic!("unexpected feature node"), } } /// Returns `true` if the given feature node index is a feature enabled /// via the command-line. pub fn is_cli_feature(&self, index: usize) -> bool { self.cli_features.contains(&index) } /// Returns a new graph by removing all nodes not reachable from the /// given nodes. pub fn from_reachable(&self, roots: &[usize]) -> Graph<'a> { // Graph built with features does not (yet) support --duplicates. assert!(self.dep_name_map.is_empty()); let mut new_graph = Graph::new(self.package_map.clone()); // Maps old index to new index. None if not yet visited. let mut remap: Vec<Option<usize>> = vec![None; self.nodes.len()]; fn visit( graph: &Graph<'_>, new_graph: &mut Graph<'_>, remap: &mut Vec<Option<usize>>, index: usize, ) -> usize { if let Some(new_index) = remap[index] { // Already visited. return new_index; } let node = graph.node(index).clone(); let new_from = new_graph.add_node(node); remap[index] = Some(new_from); // Visit dependencies. for (edge_kind, edge_indexes) in &graph.edges[index].0 { for edge_index in edge_indexes { let new_to_index = visit(graph, new_graph, remap, *edge_index); new_graph.edges[new_from].add_edge(*edge_kind, new_to_index); } } new_from } // Walk the roots, generating a new graph as it goes along. for root in roots { visit(self, &mut new_graph, &mut remap, *root); } new_graph } /// Inverts the direction of all edges. pub fn invert(&mut self) { let mut new_edges = vec![Edges::new(); self.edges.len()]; for (from_idx, node_edges) in self.edges.iter().enumerate() { for (kind, edges) in &node_edges.0 { for edge_idx in edges { new_edges[*edge_idx].add_edge(*kind, from_idx); } } } self.edges = new_edges; } /// Returns a list of nodes that are considered "duplicates" (same package /// name, with different versions/features/source/etc.). pub fn find_duplicates(&self) -> Vec<usize> { // Graph built with features does not (yet) support --duplicates. assert!(self.dep_name_map.is_empty()); // Collect a map of package name to Vec<(&Node, usize)>. let mut packages = HashMap::new(); for (i, node) in self.nodes.iter().enumerate() { if let Node::Package { package_id, .. } = node { packages .entry(package_id.name()) .or_insert_with(Vec::new) .push((node, i)); } } let mut dupes: Vec<(&Node, usize)> = packages .into_iter() .filter(|(_name, indexes)| indexes.len() > 1) .flat_map(|(_name, indexes)| indexes) .collect(); // For consistent output. dupes.sort_unstable(); dupes.into_iter().map(|(_node, i)| i).collect() } } /// Builds the graph. pub fn build<'a>( ws: &Workspace<'_>, resolve: &Resolve, resolved_features: &ResolvedFeatures, specs: &[PackageIdSpec], cli_features: &CliFeatures, target_data: &RustcTargetData<'_>, requested_kinds: &[CompileKind], package_map: HashMap<PackageId, &'a Package>, opts: &TreeOptions, ) -> CargoResult<Graph<'a>> { let mut graph = Graph::new(package_map); let mut members_with_features = ws.members_with_features(specs, cli_features)?; members_with_features.sort_unstable_by_key(|e| e.0.package_id()); for (member, cli_features) in members_with_features { let member_id = member.package_id(); let features_for = FeaturesFor::from_for_host(member.proc_macro()); for kind in requested_kinds { let member_index = add_pkg( &mut graph, resolve, resolved_features, member_id, features_for, target_data, *kind, opts, ); if opts.graph_features { let fmap = resolve.summary(member_id).features(); add_cli_features(&mut graph, member_index, &cli_features, fmap); } } } if opts.graph_features { add_internal_features(&mut graph, resolve); } Ok(graph) } /// Adds a single package node (if it does not already exist). /// /// This will also recursively add all of its dependencies. /// /// Returns the index to the package node. fn add_pkg( graph: &mut Graph<'_>, resolve: &Resolve, resolved_features: &ResolvedFeatures, package_id: PackageId, features_for: FeaturesFor, target_data: &RustcTargetData<'_>, requested_kind: CompileKind, opts: &TreeOptions, ) -> usize { let node_features = resolved_features.activated_features(package_id, features_for); let node_kind = match features_for { FeaturesFor::HostDep => CompileKind::Host, FeaturesFor::NormalOrDevOrArtifactTarget(Some(target)) => CompileKind::Target(target), FeaturesFor::NormalOrDevOrArtifactTarget(None) => requested_kind, }; let node = Node::Package { package_id, features: node_features, kind: node_kind, }; if let Some(idx) = graph.index.get(&node) { return *idx; } let from_index = graph.add_node(node); // Compute the dep name map which is later used for foo/bar feature lookups. let mut dep_name_map: HashMap<InternedString, HashSet<(usize, bool)>> = HashMap::new(); let mut deps: Vec<_> = resolve.deps(package_id).collect(); deps.sort_unstable_by_key(|(dep_id, _)| *dep_id); let show_all_targets = opts.target == super::Target::All; for (dep_id, deps) in deps { let mut deps: Vec<_> = deps .iter() // This filter is *similar* to the one found in `unit_dependencies::compute_deps`. // Try to keep them in sync! .filter(|dep| { let kind = match (node_kind, dep.kind()) { (CompileKind::Host, _) => CompileKind::Host, (_, DepKind::Build) => CompileKind::Host, (_, DepKind::Normal) => node_kind, (_, DepKind::Development) => node_kind, }; // Filter out inactivated targets. if !show_all_targets && !target_data.dep_platform_activated(dep, kind) { return false; } // Filter out dev-dependencies if requested. if !opts.edge_kinds.contains(&EdgeKind::Dep(dep.kind())) { return false; } if dep.is_optional() { // If the new feature resolver does not enable this // optional dep, then don't use it. if !resolved_features.is_dep_activated( package_id, features_for, dep.name_in_toml(), ) { return false; } } true }) .collect(); // This dependency is eliminated from the dependency tree under // the current target and feature set. if deps.is_empty() { continue; } deps.sort_unstable_by_key(|dep| dep.name_in_toml()); let dep_pkg = graph.package_map[&dep_id]; for dep in deps { let dep_features_for = if dep.is_build() || dep_pkg.proc_macro() { FeaturesFor::HostDep } else { features_for }; let dep_index = add_pkg( graph, resolve, resolved_features, dep_id, dep_features_for, target_data, requested_kind, opts, ); if opts.graph_features { // Add the dependency node with feature nodes in-between. dep_name_map .entry(dep.name_in_toml()) .or_default() .insert((dep_index, dep.is_optional())); if dep.uses_default_features() { add_feature( graph, InternedString::new("default"), Some(from_index), dep_index, EdgeKind::Dep(dep.kind()), ); } for feature in dep.features().iter() { add_feature( graph, *feature, Some(from_index), dep_index, EdgeKind::Dep(dep.kind()), ); } if !dep.uses_default_features() && dep.features().is_empty() { // No features, use a direct connection. graph.edges[from_index].add_edge(EdgeKind::Dep(dep.kind()), dep_index); } } else { graph.edges[from_index].add_edge(EdgeKind::Dep(dep.kind()), dep_index); } } } if opts.graph_features { assert!(graph .dep_name_map .insert(from_index, dep_name_map) .is_none()); } from_index } /// Adds a feature node between two nodes. /// /// That is, it adds the following: /// /// ```text /// from -Edge-> featname -Edge::Feature-> to /// ``` /// /// Returns a tuple `(missing, index)`. /// `missing` is true if this feature edge was already added. /// `index` is the index of the index in the graph of the `Feature` node. fn add_feature( graph: &mut Graph<'_>, name: InternedString, from: Option<usize>, to: usize, kind: EdgeKind, ) -> (bool, usize) { // `to` *must* point to a package node. assert!(matches! {graph.nodes[to], Node::Package{..}}); let node = Node::Feature { node_index: to, name, }; let (missing, node_index) = match graph.index.get(&node) { Some(idx) => (false, *idx), None => (true, graph.add_node(node)), }; if let Some(from) = from { graph.edges[from].add_edge(kind, node_index); } graph.edges[node_index].add_edge(EdgeKind::Feature, to); (missing, node_index) } /// Adds nodes for features requested on the command-line for the given member. /// /// Feature nodes are added as "roots" (i.e., they have no "from" index), /// because they come from the outside world. They usually only appear with /// `--invert`. fn add_cli_features( graph: &mut Graph<'_>, package_index: usize, cli_features: &CliFeatures, feature_map: &FeatureMap, ) { // NOTE: Recursive enabling of features will be handled by // add_internal_features. // Create a set of feature names requested on the command-line. let mut to_add: HashSet<FeatureValue> = HashSet::new(); if cli_features.all_features { to_add.extend(feature_map.keys().map(|feat| FeatureValue::Feature(*feat))); } if cli_features.uses_default_features { to_add.insert(FeatureValue::Feature(InternedString::new("default"))); } to_add.extend(cli_features.features.iter().cloned()); // Add each feature as a node, and mark as "from command-line" in graph.cli_features. for fv in to_add { match fv { FeatureValue::Feature(feature) => { let index = add_feature(graph, feature, None, package_index, EdgeKind::Feature).1; graph.cli_features.insert(index); } // This is enforced by CliFeatures. FeatureValue::Dep { .. } => panic!("unexpected cli dep feature {}", fv), FeatureValue::DepFeature { dep_name, dep_feature, weak, } => { let dep_connections = match graph.dep_name_map[&package_index].get(&dep_name) { // Clone to deal with immutable borrow of `graph`. :( Some(dep_connections) => dep_connections.clone(), None => { // --features bar?/feat where `bar` is not activated should be ignored. // If this wasn't weak, then this is a bug. if weak { continue; } panic!( "missing dep graph connection for CLI feature `{}` for member {:?}\n\ Please file a bug report at https://github.com/rust-lang/cargo/issues", fv, graph.nodes.get(package_index) ); } }; for (dep_index, is_optional) in dep_connections { if is_optional { // Activate the optional dep on self. let index = add_feature(graph, dep_name, None, package_index, EdgeKind::Feature).1; graph.cli_features.insert(index); } let index = add_feature(graph, dep_feature, None, dep_index, EdgeKind::Feature).1; graph.cli_features.insert(index); } } } } } /// Recursively adds connections between features in the `[features]` table /// for every package. fn add_internal_features(graph: &mut Graph<'_>, resolve: &Resolve) { // Collect features already activated by dependencies or command-line. let feature_nodes: Vec<(PackageId, usize, usize, InternedString)> = graph .nodes .iter() .enumerate() .filter_map(|(i, node)| match node { Node::Package { .. } => None, Node::Feature { node_index, name } => { let package_id = graph.package_id_for_index(*node_index); Some((package_id, *node_index, i, *name)) } }) .collect(); for (package_id, package_index, feature_index, feature_name) in feature_nodes { add_feature_rec( graph, resolve, feature_name, package_id, feature_index, package_index, ); } } /// Recursively add feature nodes for all features enabled by the given feature. /// /// `from` is the index of the node that enables this feature. /// `package_index` is the index of the package node for the feature. fn add_feature_rec( graph: &mut Graph<'_>, resolve: &Resolve, feature_name: InternedString, package_id: PackageId, from: usize, package_index: usize, ) { let feature_map = resolve.summary(package_id).features(); let fvs = match feature_map.get(&feature_name) { Some(fvs) => fvs, None => return, }; for fv in fvs { match fv { FeatureValue::Feature(dep_name) => { let (missing, feat_index) = add_feature( graph, *dep_name, Some(from), package_index, EdgeKind::Feature, ); // Don't recursive if the edge already exists to deal with cycles. if missing { add_feature_rec( graph, resolve, *dep_name, package_id, feat_index, package_index, ); } } // Dependencies are already shown in the graph as dep edges. I'm // uncertain whether or not this might be confusing in some cases // (like feature `"somefeat" = ["dep:somedep"]`), so maybe in the // future consider explicitly showing this? FeatureValue::Dep { .. } => {} FeatureValue::DepFeature { dep_name, dep_feature, // Note: `weak` is mostly handled when the graph is built in // `is_dep_activated` which is responsible for skipping // unactivated weak dependencies. Here it is only used to // determine if the feature of the dependency name is // activated on self. weak, } => { let dep_indexes = match graph.dep_name_map[&package_index].get(dep_name) { Some(indexes) => indexes.clone(), None => { log::debug!( "enabling feature {} on {}, found {}/{}, \ dep appears to not be enabled", feature_name, package_id, dep_name, dep_feature ); continue; } }; for (dep_index, is_optional) in dep_indexes { let dep_pkg_id = graph.package_id_for_index(dep_index); if is_optional && !weak { // Activate the optional dep on self. add_feature( graph, *dep_name, Some(from), package_index, EdgeKind::Feature, ); } let (missing, feat_index) = add_feature( graph, *dep_feature, Some(from), dep_index, EdgeKind::Feature, ); if missing { add_feature_rec( graph, resolve, *dep_feature, dep_pkg_id, feat_index, dep_index, ); } } } } } }
36.459215
100
0.526806
d96c485dc47e5346a9a46b73c2731781c6c4a500
3,316
use eframe::{ egui::{self, CentralPanel, Vec2}, epi::App, run_native, }; use std::process::Command; struct Menu { pass: String, } impl Menu { fn new() -> Menu { Menu { pass: String::new(), } } } impl App for Menu { fn update(&mut self, _ctx: &egui::CtxRef, _frame: &mut eframe::epi::Frame<'_>) { println!("Setup ready!"); } fn setup( &mut self, ctx: &egui::CtxRef, frame: &mut eframe::epi::Frame<'_>, _storage: Option<&dyn eframe::epi::Storage>, ) { let wifis = get_interfaces(); CentralPanel::default().show(ctx, |ui| { ui.with_layout( egui::Layout::top_down_justified(egui::Align::Center), |ui| { ui.heading("Connect to WIFI!"); ui.add_space(10_f32); ui.group(|ui| { for wifi in &wifis { if ui.button(&wifi.name).clicked() { let status = wifi.connect(&self.pass); if status { println!("Connected to wifi: {}", wifi.name); self.pass = String::from(""); } else { println!("Something went wrong!"); } } } }); ui.add_space(30_f32); ui.text_edit_singleline(&mut self.pass).request_focus(); }, ); ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| { if ui.button("Quit").clicked() { frame.quit(); } }) }); } fn name(&self) -> &str { "wifi_menu" } } struct Wifi { name: String, } impl Wifi { // TODO: another thread? fn connect(&self, pass: &str) -> bool { println!("About to connect to: {}", self.name); Command::new("nmcli") .args(&["d", "wifi", "connect", &self.name, "password", pass]) .status() .is_ok() } } fn get_interfaces() -> Vec<Wifi> { let output = Command::new("nmcli") .args(&["d", "wifi", "list"]) .output() .unwrap() .stdout; let lines = String::from_utf8(output).unwrap(); let vec_lines: Vec<&str> = lines.lines().collect(); let valid_lines = &vec_lines[1..&vec_lines.len() - 1]; let mut wifi_list = vec![]; for i in valid_lines { let mut current_wifi: Wifi = Wifi { name: String::new(), }; let parts: Vec<&str> = i.split_whitespace().collect(); let length = parts.len(); match length { 10 => current_wifi.name = parts[2].to_string(), 9 => current_wifi.name = parts[1].to_string(), _ => panic!("Couldnt get wifi name: {:?}", parts), } wifi_list.push(current_wifi); } wifi_list } fn main() { let opts = eframe::NativeOptions { initial_window_size: Some(Vec2::new(250_f32, 350_f32)), ..Default::default() }; run_native(Box::new(Menu::new()), opts); }
26.95935
84
0.450543
b9e6a64f0116a376b96ca590f9c3cd5bf5284ce9
2,831
#![allow(unknown_lints)] #![deny(unused_variables)] #![deny(unused_mut)] #![deny(clippy)] #![deny(clippy_pedantic)] #![allow(stutter)] #![recursion_limit = "128"] //! //! Neon-serde //! ========== //! //! This crate is a utility to easily convert values between //! //! A `Handle<JsValue>` from the `neon` crate //! and any value implementing `serde::{Serialize, Deserialize}` //! //! ## Usage //! //! #### `neon_serde::from_value` //! Convert a `Handle<js::JsValue>` to //! a type implementing `serde::Deserialize` //! //! #### `neon_serde::to_value` //! Convert a value implementing `serde::Serialize` to //! a `Handle<JsValue>` //! //! //! ## Example //! //! ```rust,no_run //! # #![allow(dead_code)] //! extern crate neon_serde; //! extern crate neon; //! #[macro_use] //! extern crate serde_derive; //! //! use neon::prelude::*; //! //! #[derive(Serialize, Debug, Deserialize)] //! struct AnObject { //! a: u32, //! b: Vec<f64>, //! c: String, //! } //! //! fn deserialize_something(mut cx: FunctionContext) -> JsResult<JsValue> { //! let arg0 = cx.argument::<JsValue>(0)?; //! //! let arg0_value :AnObject = neon_serde::from_value(&mut cx, arg0)?; //! println!("{:?}", arg0_value); //! //! Ok(JsUndefined::new().upcast()) //! } //! //! fn serialize_something(mut cx: FunctionContext) -> JsResult<JsValue> { //! let value = AnObject { //! a: 1, //! b: vec![2f64, 3f64, 4f64], //! c: "a string".into() //! }; //! //! let js_value = neon_serde::to_value(&mut cx, &value)?; //! Ok(js_value) //! } //! //! # fn main () { //! # } //! //! ``` //! #[macro_use] extern crate error_chain; extern crate neon; extern crate num; #[macro_use] extern crate serde; pub mod ser; pub mod de; pub mod errors; mod macros; pub use de::from_value; pub use de::from_value_opt; pub use ser::to_value; #[cfg(test)] mod tests { use super::*; use neon::prelude::*; #[test] fn test_it_compiles() { fn check<'j>(mut cx: FunctionContext<'j>) -> JsResult<'j, JsValue> { let result: () = { let arg: Handle<'j, JsValue> = cx.argument::<JsValue>(0)?; let () = from_value(&mut cx, arg)?; () }; let result: Handle<'j, JsValue> = to_value(&mut cx, &result)?; Ok(result) } let _ = check; } #[test] fn test_it_compiles_2() { fn check<'j>(mut cx: FunctionContext<'j>) -> JsResult<'j, JsValue> { let result: () = { let arg: Option<Handle<'j, JsValue>> = cx.argument_opt(0); let () = from_value_opt(&mut cx, arg)?; () }; let result: Handle<'j, JsValue> = to_value(&mut cx, &result)?; Ok(result) } let _ = check; } }
22.468254
76
0.536913
5b177d05bb862f6a7b215e3d76a02a5cbb3323ba
36,239
//! The memory subsystem. //! //! Generally, we use `Pointer` to denote memory addresses. However, some operations //! have a "size"-like parameter, and they take `Scalar` for the address because //! if the size is 0, then the pointer can also be a (properly aligned, non-NULL) //! integer. It is crucial that these operations call `check_align` *before* //! short-circuiting the empty case! use std::collections::VecDeque; use std::ptr; use std::borrow::Cow; use rustc::ty::{self, Instance, ParamEnv, query::TyCtxtAt}; use rustc::ty::layout::{Align, TargetDataLayout, Size, HasDataLayout}; use rustc_data_structures::fx::{FxHashSet, FxHashMap}; use syntax::ast::Mutability; use super::{ Pointer, AllocId, Allocation, GlobalId, AllocationExtra, InterpResult, Scalar, InterpError, GlobalAlloc, PointerArithmetic, Machine, AllocMap, MayLeak, ErrorHandled, CheckInAllocMsg, }; #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)] pub enum MemoryKind<T> { /// Error if deallocated except during a stack pop Stack, /// Error if ever deallocated Vtable, /// Additional memory kinds a machine wishes to distinguish from the builtin ones Machine(T), } impl<T: MayLeak> MayLeak for MemoryKind<T> { #[inline] fn may_leak(self) -> bool { match self { MemoryKind::Stack => false, MemoryKind::Vtable => true, MemoryKind::Machine(k) => k.may_leak() } } } /// Used by `get_size_and_align` to indicate whether the allocation needs to be live. #[derive(Debug, Copy, Clone)] pub enum AllocCheck { /// Allocation must be live and not a function pointer. Dereferencable, /// Allocations needs to be live, but may be a function pointer. Live, /// Allocation may be dead. MaybeDead, } // `Memory` has to depend on the `Machine` because some of its operations // (e.g., `get`) call a `Machine` hook. pub struct Memory<'mir, 'tcx, M: Machine<'mir, 'tcx>> { /// Allocations local to this instance of the miri engine. The kind /// helps ensure that the same mechanism is used for allocation and /// deallocation. When an allocation is not found here, it is a /// static and looked up in the `tcx` for read access. Some machines may /// have to mutate this map even on a read-only access to a static (because /// they do pointer provenance tracking and the allocations in `tcx` have /// the wrong type), so we let the machine override this type. /// Either way, if the machine allows writing to a static, doing so will /// create a copy of the static allocation here. // FIXME: this should not be public, but interning currently needs access to it pub(super) alloc_map: M::MemoryMap, /// To be able to compare pointers with NULL, and to check alignment for accesses /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations /// that do not exist any more. pub(super) dead_alloc_map: FxHashMap<AllocId, (Size, Align)>, /// Extra data added by the machine. pub extra: M::MemoryExtra, /// Lets us implement `HasDataLayout`, which is awfully convenient. pub(super) tcx: TyCtxtAt<'tcx>, } impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> { #[inline] fn data_layout(&self) -> &TargetDataLayout { &self.tcx.data_layout } } // FIXME: Really we shouldn't clone memory, ever. Snapshot machinery should instead // carefully copy only the reachable parts. impl<'mir, 'tcx, M> Clone for Memory<'mir, 'tcx, M> where M: Machine<'mir, 'tcx, PointerTag = (), AllocExtra = (), MemoryExtra = ()>, M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>, { fn clone(&self) -> Self { Memory { alloc_map: self.alloc_map.clone(), dead_alloc_map: self.dead_alloc_map.clone(), extra: (), tcx: self.tcx, } } } impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { pub fn new(tcx: TyCtxtAt<'tcx>) -> Self { Memory { alloc_map: M::MemoryMap::default(), dead_alloc_map: FxHashMap::default(), extra: M::MemoryExtra::default(), tcx, } } #[inline] pub fn tag_static_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> { ptr.with_tag(M::tag_static_base_pointer(ptr.alloc_id, &self)) } pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> Pointer<M::PointerTag> { let id = self.tcx.alloc_map.lock().create_fn_alloc(instance); self.tag_static_base_pointer(Pointer::from(id)) } pub fn allocate( &mut self, size: Size, align: Align, kind: MemoryKind<M::MemoryKinds>, ) -> Pointer<M::PointerTag> { let alloc = Allocation::undef(size, align); self.allocate_with(alloc, kind) } pub fn allocate_static_bytes( &mut self, bytes: &[u8], kind: MemoryKind<M::MemoryKinds>, ) -> Pointer<M::PointerTag> { let alloc = Allocation::from_byte_aligned_bytes(bytes); self.allocate_with(alloc, kind) } pub fn allocate_with( &mut self, alloc: Allocation, kind: MemoryKind<M::MemoryKinds>, ) -> Pointer<M::PointerTag> { let id = self.tcx.alloc_map.lock().reserve(); let (alloc, tag) = M::tag_allocation(id, Cow::Owned(alloc), Some(kind), &self); self.alloc_map.insert(id, (kind, alloc.into_owned())); Pointer::from(id).with_tag(tag) } pub fn reallocate( &mut self, ptr: Pointer<M::PointerTag>, old_size_and_align: Option<(Size, Align)>, new_size: Size, new_align: Align, kind: MemoryKind<M::MemoryKinds>, ) -> InterpResult<'tcx, Pointer<M::PointerTag>> { if ptr.offset.bytes() != 0 { return err!(ReallocateNonBasePtr); } // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc". // This happens so rarely, the perf advantage is outweighed by the maintenance cost. let new_ptr = self.allocate(new_size, new_align, kind); let old_size = match old_size_and_align { Some((size, _align)) => size, None => Size::from_bytes(self.get(ptr.alloc_id)?.bytes.len() as u64), }; self.copy( ptr.into(), Align::from_bytes(1).unwrap(), // old_align anyway gets checked below by `deallocate` new_ptr.into(), new_align, old_size.min(new_size), /*nonoverlapping*/ true, )?; self.deallocate(ptr, old_size_and_align, kind)?; Ok(new_ptr) } /// Deallocate a local, or do nothing if that local has been made into a static pub fn deallocate_local(&mut self, ptr: Pointer<M::PointerTag>) -> InterpResult<'tcx> { // The allocation might be already removed by static interning. // This can only really happen in the CTFE instance, not in miri. if self.alloc_map.contains_key(&ptr.alloc_id) { self.deallocate(ptr, None, MemoryKind::Stack) } else { Ok(()) } } pub fn deallocate( &mut self, ptr: Pointer<M::PointerTag>, old_size_and_align: Option<(Size, Align)>, kind: MemoryKind<M::MemoryKinds>, ) -> InterpResult<'tcx> { trace!("deallocating: {}", ptr.alloc_id); if ptr.offset.bytes() != 0 { return err!(DeallocateNonBasePtr); } let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) { Some(alloc) => alloc, None => { // Deallocating static memory -- always an error return match self.tcx.alloc_map.lock().get(ptr.alloc_id) { Some(GlobalAlloc::Function(..)) => err!(DeallocatedWrongMemoryKind( "function".to_string(), format!("{:?}", kind), )), Some(GlobalAlloc::Static(..)) | Some(GlobalAlloc::Memory(..)) => err!(DeallocatedWrongMemoryKind( "static".to_string(), format!("{:?}", kind), )), None => err!(DoubleFree) } } }; if alloc_kind != kind { return err!(DeallocatedWrongMemoryKind( format!("{:?}", alloc_kind), format!("{:?}", kind), )); } if let Some((size, align)) = old_size_and_align { if size.bytes() != alloc.bytes.len() as u64 || align != alloc.align { let bytes = Size::from_bytes(alloc.bytes.len() as u64); return err!(IncorrectAllocationInformation(size, bytes, align, alloc.align)); } } // Let the machine take some extra action let size = Size::from_bytes(alloc.bytes.len() as u64); AllocationExtra::memory_deallocated(&mut alloc, ptr, size)?; // Don't forget to remember size and align of this now-dead allocation let old = self.dead_alloc_map.insert( ptr.alloc_id, (Size::from_bytes(alloc.bytes.len() as u64), alloc.align) ); if old.is_some() { bug!("Nothing can be deallocated twice"); } Ok(()) } /// Check if the given scalar is allowed to do a memory access of given `size` /// and `align`. On success, returns `None` for zero-sized accesses (where /// nothing else is left to do) and a `Pointer` to use for the actual access otherwise. /// Crucially, if the input is a `Pointer`, we will test it for liveness /// *even of* the size is 0. /// /// Everyone accessing memory based on a `Scalar` should use this method to get the /// `Pointer` they need. And even if you already have a `Pointer`, call this method /// to make sure it is sufficiently aligned and not dangling. Not doing that may /// cause ICEs. pub fn check_ptr_access( &self, sptr: Scalar<M::PointerTag>, size: Size, align: Align, ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> { fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> { if offset % align.bytes() == 0 { Ok(()) } else { // The biggest power of two through which `offset` is divisible. let offset_pow2 = 1 << offset.trailing_zeros(); err!(AlignmentCheckFailed { has: Align::from_bytes(offset_pow2).unwrap(), required: align, }) } } // Normalize to a `Pointer` if we definitely need one. let normalized = if size.bytes() == 0 { // Can be an integer, just take what we got. We do NOT `force_bits` here; // if this is already a `Pointer` we want to do the bounds checks! sptr } else { // A "real" access, we must get a pointer. Scalar::Ptr(self.force_ptr(sptr)?) }; Ok(match normalized.to_bits_or_ptr(self.pointer_size(), self) { Ok(bits) => { let bits = bits as u64; // it's ptr-sized assert!(size.bytes() == 0); // Must be non-NULL and aligned. if bits == 0 { return err!(InvalidNullPointerUsage); } check_offset_align(bits, align)?; None } Err(ptr) => { let (allocation_size, alloc_align) = self.get_size_and_align(ptr.alloc_id, AllocCheck::Dereferencable)?; // Test bounds. This also ensures non-NULL. // It is sufficient to check this for the end pointer. The addition // checks for overflow. let end_ptr = ptr.offset(size, self)?; end_ptr.check_in_alloc(allocation_size, CheckInAllocMsg::MemoryAccessTest)?; // Test align. Check this last; if both bounds and alignment are violated // we want the error to be about the bounds. if alloc_align.bytes() < align.bytes() { // The allocation itself is not aligned enough. // FIXME: Alignment check is too strict, depending on the base address that // got picked we might be aligned even if this check fails. // We instead have to fall back to converting to an integer and checking // the "real" alignment. return err!(AlignmentCheckFailed { has: alloc_align, required: align, }); } check_offset_align(ptr.offset.bytes(), align)?; // We can still be zero-sized in this branch, in which case we have to // return `None`. if size.bytes() == 0 { None } else { Some(ptr) } } }) } /// Test if the pointer might be NULL. pub fn ptr_may_be_null( &self, ptr: Pointer<M::PointerTag>, ) -> bool { let (size, _align) = self.get_size_and_align(ptr.alloc_id, AllocCheck::MaybeDead) .expect("alloc info with MaybeDead cannot fail"); ptr.check_in_alloc(size, CheckInAllocMsg::NullPointerTest).is_err() } } /// Allocation accessors impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { /// Helper function to obtain the global (tcx) allocation for a static. /// This attempts to return a reference to an existing allocation if /// one can be found in `tcx`. That, however, is only possible if `tcx` and /// this machine use the same pointer tag, so it is indirected through /// `M::tag_allocation`. /// /// Notice that every static has two `AllocId` that will resolve to the same /// thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID, /// and the other one is maps to `GlobalAlloc::Memory`, this is returned by /// `const_eval_raw` and it is the "resolved" ID. /// The resolved ID is never used by the interpreted progrma, it is hidden. /// The `GlobalAlloc::Memory` branch here is still reachable though; when a static /// contains a reference to memory that was created during its evaluation (i.e., not to /// another static), those inner references only exist in "resolved" form. fn get_static_alloc( id: AllocId, tcx: TyCtxtAt<'tcx>, memory: &Memory<'mir, 'tcx, M>, ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> { let alloc = tcx.alloc_map.lock().get(id); let alloc = match alloc { Some(GlobalAlloc::Memory(mem)) => Cow::Borrowed(mem), Some(GlobalAlloc::Function(..)) => return err!(DerefFunctionPointer), None => return err!(DanglingPointerDeref), Some(GlobalAlloc::Static(def_id)) => { // We got a "lazy" static that has not been computed yet. if tcx.is_foreign_item(def_id) { trace!("static_alloc: foreign item {:?}", def_id); M::find_foreign_static(def_id, tcx)? } else { trace!("static_alloc: Need to compute {:?}", def_id); let instance = Instance::mono(tcx.tcx, def_id); let gid = GlobalId { instance, promoted: None, }; // use the raw query here to break validation cycles. Later uses of the static // will call the full query anyway let raw_const = tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)) .map_err(|err| { // no need to report anything, the const_eval call takes care of that // for statics assert!(tcx.is_static(def_id)); match err { ErrorHandled::Reported => InterpError::ReferencedConstant, ErrorHandled::TooGeneric => InterpError::TooGeneric, } })?; // Make sure we use the ID of the resolved memory, not the lazy one! let id = raw_const.alloc_id; let allocation = tcx.alloc_map.lock().unwrap_memory(id); Cow::Borrowed(allocation) } } }; // We got tcx memory. Let the machine figure out whether and how to // turn that into memory with the right pointer tag. Ok(M::tag_allocation( id, // always use the ID we got as input, not the "hidden" one. alloc, M::STATIC_KIND.map(MemoryKind::Machine), memory ).0) } pub fn get( &self, id: AllocId, ) -> InterpResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> { // The error type of the inner closure here is somewhat funny. We have two // ways of "erroring": An actual error, or because we got a reference from // `get_static_alloc` that we can actually use directly without inserting anything anywhere. // So the error type is `InterpResult<'tcx, &Allocation<M::PointerTag>>`. let a = self.alloc_map.get_or(id, || { let alloc = Self::get_static_alloc(id, self.tcx, &self).map_err(Err)?; match alloc { Cow::Borrowed(alloc) => { // We got a ref, cheaply return that as an "error" so that the // map does not get mutated. Err(Ok(alloc)) } Cow::Owned(alloc) => { // Need to put it into the map and return a ref to that let kind = M::STATIC_KIND.expect( "I got an owned allocation that I have to copy but the machine does \ not expect that to happen" ); Ok((MemoryKind::Machine(kind), alloc)) } } }); // Now unpack that funny error type match a { Ok(a) => Ok(&a.1), Err(a) => a } } pub fn get_mut( &mut self, id: AllocId, ) -> InterpResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> { let tcx = self.tcx; let alloc = Self::get_static_alloc(id, tcx, &self); let a = self.alloc_map.get_mut_or(id, || { // Need to make a copy, even if `get_static_alloc` is able // to give us a cheap reference. let alloc = alloc?; if alloc.mutability == Mutability::Immutable { return err!(ModifiedConstantMemory); } match M::STATIC_KIND { Some(kind) => Ok((MemoryKind::Machine(kind), alloc.into_owned())), None => err!(ModifiedStatic), } }); // Unpack the error type manually because type inference doesn't // work otherwise (and we cannot help it because `impl Trait`) match a { Err(e) => Err(e), Ok(a) => { let a = &mut a.1; if a.mutability == Mutability::Immutable { return err!(ModifiedConstantMemory); } Ok(a) } } } /// Obtain the size and alignment of an allocation, even if that allocation has /// been deallocated. /// /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`. pub fn get_size_and_align( &self, id: AllocId, liveness: AllocCheck, ) -> InterpResult<'static, (Size, Align)> { if let Ok(alloc) = self.get(id) { return Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align)); } // can't do this in the match argument, we may get cycle errors since the lock would get // dropped after the match. let alloc = self.tcx.alloc_map.lock().get(id); // Could also be a fn ptr or extern static match alloc { Some(GlobalAlloc::Function(..)) => { if let AllocCheck::Dereferencable = liveness { // The caller requested no function pointers. err!(DerefFunctionPointer) } else { Ok((Size::ZERO, Align::from_bytes(1).unwrap())) } } // `self.get` would also work, but can cause cycles if a static refers to itself Some(GlobalAlloc::Static(did)) => { // The only way `get` couldn't have worked here is if this is an extern static assert!(self.tcx.is_foreign_item(did)); // Use size and align of the type let ty = self.tcx.type_of(did); let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap(); Ok((layout.size, layout.align.abi)) } _ => { if let Ok(alloc) = self.get(id) { Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align)) } else if let AllocCheck::MaybeDead = liveness { // Deallocated pointers are allowed, we should be able to find // them in the map. Ok(*self.dead_alloc_map.get(&id) .expect("deallocated pointers should all be recorded in `dead_alloc_map`")) } else { err!(DanglingPointerDeref) } }, } } pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> InterpResult<'tcx, Instance<'tcx>> { if ptr.offset.bytes() != 0 { return err!(InvalidFunctionPointer); } trace!("reading fn ptr: {}", ptr.alloc_id); match self.tcx.alloc_map.lock().get(ptr.alloc_id) { Some(GlobalAlloc::Function(instance)) => Ok(instance), _ => Err(InterpError::ExecuteMemory.into()), } } pub fn mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> { self.get_mut(id)?.mutability = Mutability::Immutable; Ok(()) } /// For debugging, print an allocation and all allocations it points to, recursively. pub fn dump_alloc(&self, id: AllocId) { self.dump_allocs(vec![id]); } fn dump_alloc_helper<Tag, Extra>( &self, allocs_seen: &mut FxHashSet<AllocId>, allocs_to_print: &mut VecDeque<AllocId>, mut msg: String, alloc: &Allocation<Tag, Extra>, extra: String, ) { use std::fmt::Write; let prefix_len = msg.len(); let mut relocations = vec![]; for i in 0..(alloc.bytes.len() as u64) { let i = Size::from_bytes(i); if let Some(&(_, target_id)) = alloc.relocations.get(&i) { if allocs_seen.insert(target_id) { allocs_to_print.push_back(target_id); } relocations.push((i, target_id)); } if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() { // this `as usize` is fine, since `i` came from a `usize` write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap(); } else { msg.push_str("__ "); } } trace!( "{}({} bytes, alignment {}){}", msg, alloc.bytes.len(), alloc.align.bytes(), extra ); if !relocations.is_empty() { msg.clear(); write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces. let mut pos = Size::ZERO; let relocation_width = (self.pointer_size().bytes() - 1) * 3; for (i, target_id) in relocations { // this `as usize` is fine, since we can't print more chars than `usize::MAX` write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap(); let target = format!("({})", target_id); // this `as usize` is fine, since we can't print more chars than `usize::MAX` write!(msg, "└{0:─^1$}┘ ", target, relocation_width as usize).unwrap(); pos = i + self.pointer_size(); } trace!("{}", msg); } } /// For debugging, print a list of allocations and all allocations they point to, recursively. pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) { if !log_enabled!(::log::Level::Trace) { return; } allocs.sort(); allocs.dedup(); let mut allocs_to_print = VecDeque::from(allocs); let mut allocs_seen = FxHashSet::default(); while let Some(id) = allocs_to_print.pop_front() { let msg = format!("Alloc {:<5} ", format!("{}:", id)); // normal alloc? match self.alloc_map.get_or(id, || Err(())) { Ok((kind, alloc)) => { let extra = match kind { MemoryKind::Stack => " (stack)".to_owned(), MemoryKind::Vtable => " (vtable)".to_owned(), MemoryKind::Machine(m) => format!(" ({:?})", m), }; self.dump_alloc_helper( &mut allocs_seen, &mut allocs_to_print, msg, alloc, extra ); }, Err(()) => { // static alloc? match self.tcx.alloc_map.lock().get(id) { Some(GlobalAlloc::Memory(alloc)) => { self.dump_alloc_helper( &mut allocs_seen, &mut allocs_to_print, msg, alloc, " (immutable)".to_owned() ); } Some(GlobalAlloc::Function(func)) => { trace!("{} {}", msg, func); } Some(GlobalAlloc::Static(did)) => { trace!("{} {:?}", msg, did); } None => { trace!("{} (deallocated)", msg); } } }, }; } } pub fn leak_report(&self) -> usize { trace!("### LEAK REPORT ###"); let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| { if kind.may_leak() { None } else { Some(id) } }); let n = leaks.len(); self.dump_allocs(leaks); n } /// This is used by [priroda](https://github.com/oli-obk/priroda) pub fn alloc_map(&self) -> &M::MemoryMap { &self.alloc_map } } /// Reading and writing. impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { /// Performs appropriate bounds checks. pub fn read_bytes( &self, ptr: Scalar<M::PointerTag>, size: Size, ) -> InterpResult<'tcx, &[u8]> { let ptr = match self.check_ptr_access(ptr, size, Align::from_bytes(1).unwrap())? { Some(ptr) => ptr, None => return Ok(&[]), // zero-sized access }; self.get(ptr.alloc_id)?.get_bytes(self, ptr, size) } /// Performs appropriate bounds checks. pub fn copy( &mut self, src: Scalar<M::PointerTag>, src_align: Align, dest: Scalar<M::PointerTag>, dest_align: Align, size: Size, nonoverlapping: bool, ) -> InterpResult<'tcx> { self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping) } /// Performs appropriate bounds checks. pub fn copy_repeatedly( &mut self, src: Scalar<M::PointerTag>, src_align: Align, dest: Scalar<M::PointerTag>, dest_align: Align, size: Size, length: u64, nonoverlapping: bool, ) -> InterpResult<'tcx> { // We need to check *both* before early-aborting due to the size being 0. let (src, dest) = match (self.check_ptr_access(src, size, src_align)?, self.check_ptr_access(dest, size * length, dest_align)?) { (Some(src), Some(dest)) => (src, dest), // One of the two sizes is 0. _ => return Ok(()), }; // first copy the relocations to a temporary buffer, because // `get_bytes_mut` will clear the relocations, which is correct, // since we don't want to keep any relocations at the target. // (`get_bytes_with_undef_and_ptr` below checks that there are no // relocations overlapping the edges; those would not be handled correctly). let relocations = { let relocations = self.get(src.alloc_id)?.relocations(self, src, size); if relocations.is_empty() { // nothing to copy, ignore even the `length` loop Vec::new() } else { let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize)); for i in 0..length { new_relocations.extend( relocations .iter() .map(|&(offset, reloc)| { // compute offset for current repetition let dest_offset = dest.offset + (i * size); ( // shift offsets from source allocation to destination allocation offset + dest_offset - src.offset, reloc, ) }) ); } new_relocations } }; let tcx = self.tcx.tcx; // This checks relocation edges on the src. let src_bytes = self.get(src.alloc_id)? .get_bytes_with_undef_and_ptr(&tcx, src, size)? .as_ptr(); let dest_bytes = self.get_mut(dest.alloc_id)? .get_bytes_mut(&tcx, dest, size * length)? .as_mut_ptr(); // SAFE: The above indexing would have panicked if there weren't at least `size` bytes // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and // `dest` could possibly overlap. // The pointers above remain valid even if the `HashMap` table is moved around because they // point into the `Vec` storing the bytes. unsafe { assert_eq!(size.bytes() as usize as u64, size.bytes()); if src.alloc_id == dest.alloc_id { if nonoverlapping { if (src.offset <= dest.offset && src.offset + size > dest.offset) || (dest.offset <= src.offset && dest.offset + size > src.offset) { return err!(Intrinsic( "copy_nonoverlapping called on overlapping ranges".to_string(), )); } } for i in 0..length { ptr::copy(src_bytes, dest_bytes.offset((size.bytes() * i) as isize), size.bytes() as usize); } } else { for i in 0..length { ptr::copy_nonoverlapping(src_bytes, dest_bytes.offset((size.bytes() * i) as isize), size.bytes() as usize); } } } // copy definedness to the destination self.copy_undef_mask(src, dest, size, length)?; // copy the relocations to the destination self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations); Ok(()) } } /// Undefined bytes impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { // FIXME: Add a fast version for the common, nonoverlapping case fn copy_undef_mask( &mut self, src: Pointer<M::PointerTag>, dest: Pointer<M::PointerTag>, size: Size, repeat: u64, ) -> InterpResult<'tcx> { // The bits have to be saved locally before writing to dest in case src and dest overlap. assert_eq!(size.bytes() as usize as u64, size.bytes()); let undef_mask = &self.get(src.alloc_id)?.undef_mask; // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`), // a naive undef mask copying algorithm would repeatedly have to read the undef mask from // the source and write it to the destination. Even if we optimized the memory accesses, // we'd be doing all of this `repeat` times. // Therefor we precompute a compressed version of the undef mask of the source value and // then write it back `repeat` times without computing any more information from the source. // a precomputed cache for ranges of defined/undefined bits // 0000010010001110 will become // [5, 1, 2, 1, 3, 3, 1] // where each element toggles the state let mut ranges = smallvec::SmallVec::<[u64; 1]>::new(); let first = undef_mask.get(src.offset); let mut cur_len = 1; let mut cur = first; for i in 1..size.bytes() { // FIXME: optimize to bitshift the current undef block's bits and read the top bit if undef_mask.get(src.offset + Size::from_bytes(i)) == cur { cur_len += 1; } else { ranges.push(cur_len); cur_len = 1; cur = !cur; } } // now fill in all the data let dest_allocation = self.get_mut(dest.alloc_id)?; // an optimization where we can just overwrite an entire range of definedness bits if // they are going to be uniformly `1` or `0`. if ranges.is_empty() { dest_allocation.undef_mask.set_range_inbounds( dest.offset, dest.offset + size * repeat, first, ); return Ok(()) } // remember to fill in the trailing bits ranges.push(cur_len); for mut j in 0..repeat { j *= size.bytes(); j += dest.offset.bytes(); let mut cur = first; for range in &ranges { let old_j = j; j += range; dest_allocation.undef_mask.set_range_inbounds( Size::from_bytes(old_j), Size::from_bytes(j), cur, ); cur = !cur; } } Ok(()) } pub fn force_ptr( &self, scalar: Scalar<M::PointerTag>, ) -> InterpResult<'tcx, Pointer<M::PointerTag>> { match scalar { Scalar::Ptr(ptr) => Ok(ptr), _ => M::int_to_ptr(scalar.to_usize(self)?, self) } } pub fn force_bits( &self, scalar: Scalar<M::PointerTag>, size: Size ) -> InterpResult<'tcx, u128> { match scalar.to_bits_or_ptr(size, self) { Ok(bits) => Ok(bits), Err(ptr) => Ok(M::ptr_to_int(ptr, self)? as u128) } } }
39.910793
100
0.528905
50d5cadd1a3751ff5abc9e2dfc949700d7c1d127
4,429
use crate::ast::{self, WithName}; use crate::ValueValidator; use crate::{DatamodelError, Diagnostics}; use std::collections::HashMap; /// Represents a list of arguments. #[derive(Debug, Default)] pub(crate) struct Arguments<'a> { attribute: Option<&'a ast::Attribute>, args: HashMap<&'a str, &'a ast::Argument>, // the _remaining_ arguments } impl<'a> Arguments<'a> { /// Starts validating the arguments for an attribute, checking for duplicate arguments in the process. pub(super) fn set_attribute(&mut self, attribute: &'a ast::Attribute) -> Result<(), Diagnostics> { let arguments = &attribute.arguments; self.attribute = Some(attribute); self.args.clear(); self.args.reserve(arguments.len()); let mut errors = Diagnostics::new(); let mut unnamed_arguments = Vec::new(); for arg in arguments { if let Some(existing_argument) = self.args.insert(arg.name.name.as_str(), arg) { if arg.is_unnamed() { if unnamed_arguments.is_empty() { let rendered = schema_ast::renderer::Renderer::render_value_to_string(&existing_argument.value); unnamed_arguments.push(rendered) } let rendered = schema_ast::renderer::Renderer::render_value_to_string(&arg.value); unnamed_arguments.push(rendered) } else { errors.push_error(DatamodelError::new_duplicate_argument_error(&arg.name.name, arg.span)); } } } if !unnamed_arguments.is_empty() { errors.push_error(DatamodelError::new_attribute_validation_error( &format!("You provided multiple unnamed arguments. This is not possible. Did you forget the brackets? Did you mean `[{}]`?", unnamed_arguments.join(", ")), attribute.name.name.as_str(), self.span(), )) } for arg in &attribute.empty_arguments { errors.push_error(DatamodelError::new_attribute_validation_error( &format!("The `{}` argument is missing a value.", arg.name.name), attribute.name(), arg.name.span, )) } if let Some(span) = attribute.trailing_comma { errors.push_error(DatamodelError::new_attribute_validation_error( "Trailing commas are not valid in attribute arguments, please remove the comma.", attribute.name(), span, )) } errors.to_result() } pub(crate) fn attribute(&self) -> &'a ast::Attribute { self.attribute.unwrap() } /// Call this at the end of validation. It will report errors for each argument that was not used by the validators. pub(crate) fn check_for_unused_arguments(&self, errors: &mut Diagnostics) { for arg in self.args.values() { errors.push_error(DatamodelError::new_unused_argument_error(&arg.name.name, arg.span)); } } /// Gets the span of all arguments wrapped by this instance. pub(crate) fn span(&self) -> ast::Span { self.attribute().span } pub(crate) fn optional_arg(&mut self, name: &str) -> Option<ValueValidator<'a>> { self.args.remove(name).map(|arg| ValueValidator::new(&arg.value)) } /// Gets the arg with the given name, or if it is not found, the first unnamed argument. /// /// Use this to implement unnamed argument behavior. pub(crate) fn default_arg(&mut self, name: &str) -> Result<ValueValidator<'a>, DatamodelError> { match (self.args.remove(name), self.args.remove("")) { (Some(arg), None) => Ok(ValueValidator::new(&arg.value)), (None, Some(arg)) => Ok(ValueValidator::new(&arg.value)), (Some(arg), Some(_)) => Err(DatamodelError::new_duplicate_default_argument_error(name, arg.span)), (None, None) => Err(DatamodelError::new_argument_not_found_error(name, self.span())), } } pub(crate) fn new_attribute_validation_error(&self, message: &str) -> DatamodelError { DatamodelError::new_attribute_validation_error(message, self.attribute().name(), self.span()) } pub(crate) fn optional_default_arg(&mut self, name: &str) -> Option<ValueValidator<'a>> { self.default_arg(name).ok() } }
41.783019
171
0.611199
bbed9a8907929c7c72b16a539be09b59aa9733f9
7,349
use criterion::measurement::WallTime; use criterion::{ criterion_group, criterion_main, BatchSize, BenchmarkGroup, BenchmarkId, Criterion, Throughput, }; use rustpython_compiler::Mode; use rustpython_vm::{ common::ascii, InitParameter, Interpreter, PyObjectWrap, PyResult, PySettings, }; use std::path::{Path, PathBuf}; use std::{ffi, fs, io}; pub struct MicroBenchmark { name: String, setup: String, code: String, iterate: bool, } fn bench_cpython_code(group: &mut BenchmarkGroup<WallTime>, bench: &MicroBenchmark) { let gil = cpython::Python::acquire_gil(); let py = gil.python(); let setup_code = ffi::CString::new(&*bench.setup).unwrap(); let setup_name = ffi::CString::new(format!("{}_setup", bench.name)).unwrap(); let setup_code = cpy_compile_code(py, &setup_code, &setup_name).unwrap(); let code = ffi::CString::new(&*bench.code).unwrap(); let name = ffi::CString::new(&*bench.name).unwrap(); let code = cpy_compile_code(py, &code, &name).unwrap(); let bench_func = |(globals, locals): &mut (cpython::PyDict, cpython::PyDict)| { let res = cpy_run_code(py, &code, globals, locals); if let Err(e) = res { e.print(py); panic!("Error running microbenchmark") } }; let bench_setup = |iterations| { let globals = cpython::PyDict::new(py); // setup the __builtins__ attribute - no other way to do this (other than manually) as far // as I can tell let _ = py.run("", Some(&globals), None); let locals = cpython::PyDict::new(py); if let Some(idx) = iterations { globals.set_item(py, "ITERATIONS", idx).unwrap(); } let res = cpy_run_code(py, &setup_code, &globals, &locals); if let Err(e) = res { e.print(py); panic!("Error running microbenchmark setup code") } (globals, locals) }; if bench.iterate { for idx in (100..=1_000).step_by(200) { group.throughput(Throughput::Elements(idx as u64)); group.bench_with_input(BenchmarkId::new("cpython", &bench.name), &idx, |b, idx| { b.iter_batched_ref( || bench_setup(Some(*idx)), bench_func, BatchSize::LargeInput, ); }); } } else { group.bench_function(BenchmarkId::new("cpython", &bench.name), move |b| { b.iter_batched_ref(|| bench_setup(None), bench_func, BatchSize::LargeInput); }); } } unsafe fn cpy_res( py: cpython::Python<'_>, x: *mut python3_sys::PyObject, ) -> cpython::PyResult<cpython::PyObject> { cpython::PyObject::from_owned_ptr_opt(py, x).ok_or_else(|| cpython::PyErr::fetch(py)) } fn cpy_compile_code( py: cpython::Python<'_>, s: &ffi::CStr, fname: &ffi::CStr, ) -> cpython::PyResult<cpython::PyObject> { unsafe { let res = python3_sys::Py_CompileString(s.as_ptr(), fname.as_ptr(), python3_sys::Py_file_input); cpy_res(py, res) } } fn cpy_run_code( py: cpython::Python<'_>, code: &cpython::PyObject, locals: &cpython::PyDict, globals: &cpython::PyDict, ) -> cpython::PyResult<cpython::PyObject> { use cpython::PythonObject; unsafe { let res = python3_sys::PyEval_EvalCode( code.as_ptr(), locals.as_object().as_ptr(), globals.as_object().as_ptr(), ); cpy_res(py, res) } } fn bench_rustpy_code(group: &mut BenchmarkGroup<WallTime>, bench: &MicroBenchmark) { let mut settings = PySettings::default(); settings.path_list.push("Lib/".to_string()); settings.dont_write_bytecode = true; settings.no_user_site = true; Interpreter::new_with_init(settings, |vm| { for (name, init) in rustpython_stdlib::get_module_inits().into_iter() { vm.add_native_module(name, init); } InitParameter::External }) .enter(|vm| { let setup_code = vm .compile(&bench.setup, Mode::Exec, bench.name.to_owned()) .expect("Error compiling setup code"); let bench_code = vm .compile(&bench.code, Mode::Exec, bench.name.to_owned()) .expect("Error compiling bench code"); let bench_func = |scope| { let res: PyResult = vm.run_code_obj(bench_code.clone(), scope); vm.unwrap_pyresult(res); }; let bench_setup = |iterations| { let scope = vm.new_scope_with_builtins(); if let Some(idx) = iterations { scope .locals .as_object() .set_item(vm.new_pyobj(ascii!("ITERATIONS")), vm.new_pyobj(idx), vm) .expect("Error adding ITERATIONS local variable"); } let setup_result = vm.run_code_obj(setup_code.clone(), scope.clone()); vm.unwrap_pyresult(setup_result); scope }; if bench.iterate { for idx in (100..=1_000).step_by(200) { group.throughput(Throughput::Elements(idx as u64)); group.bench_with_input( BenchmarkId::new("rustpython", &bench.name), &idx, |b, idx| { b.iter_batched( || bench_setup(Some(*idx)), bench_func, BatchSize::LargeInput, ); }, ); } } else { group.bench_function(BenchmarkId::new("rustpython", &bench.name), move |b| { b.iter_batched(|| bench_setup(None), bench_func, BatchSize::LargeInput); }); } }) } pub fn run_micro_benchmark(c: &mut Criterion, benchmark: MicroBenchmark) { let mut group = c.benchmark_group("microbenchmarks"); bench_cpython_code(&mut group, &benchmark); bench_rustpy_code(&mut group, &benchmark); group.finish(); } pub fn criterion_benchmark(c: &mut Criterion) { let benchmark_dir = Path::new("./benches/microbenchmarks/"); let dirs: Vec<fs::DirEntry> = benchmark_dir .read_dir() .unwrap() .collect::<io::Result<_>>() .unwrap(); let paths: Vec<PathBuf> = dirs.iter().map(|p| p.path()).collect(); let benchmarks: Vec<MicroBenchmark> = paths .into_iter() .map(|p| { let name = p.file_name().unwrap().to_os_string(); let contents = fs::read_to_string(p).unwrap(); let iterate = contents.contains("ITERATIONS"); let (setup, code) = if contents.contains("# ---") { let split: Vec<&str> = contents.splitn(2, "# ---").collect(); (split[0].to_string(), split[1].to_string()) } else { ("".to_string(), contents) }; let name = name.into_string().unwrap(); MicroBenchmark { name, setup, code, iterate, } }) .collect(); for benchmark in benchmarks { run_micro_benchmark(c, benchmark); } } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
33.253394
99
0.559124
d70361d2a915f2a710c112931ccfbd913da4595f
2,447
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::T2CKR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct T2CKRR { bits: u8, } impl T2CKRR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Proxy"] pub struct _T2CKRW<'a> { w: &'a mut W, } impl<'a> _T2CKRW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:3"] #[inline] pub fn t2ckr(&self) -> T2CKRR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; T2CKRR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:3"] #[inline] pub fn t2ckr(&mut self) -> _T2CKRW { _T2CKRW { w: self } } }
23.084906
59
0.487127
167f06c4ca42393e43fa0307039ac889ffa08025
3,744
use bevy::prelude::*; use bevy_inspector_egui::bevy_egui::EguiContext; use bevy_inspector_egui::plugin::InspectorWindows; use bevy_mod_picking::{PickingPluginsState, Selection}; use heron::prelude::*; use crate::controller::Player; use bevy_inspector_egui::widgets::InspectorQuery; use bevy_inspector_egui::Inspectable; #[derive(Component, Reflect)] pub struct FrozenRigidBody(RigidBody); #[derive(Component)] pub struct Inspected; #[derive(Inspectable, Default)] pub struct Inspection { player: InspectorQuery<Entity, With<Player>>, selected: InspectorQuery<Entity, With<Inspected>>, } pub fn selection_inspector( mut commands: Commands, query: Query<(Entity, &Selection), (Without<Inspected>, Changed<Selection>)>, ) { for (entity, selection) in query.iter() { if selection.selected() { commands.entity(entity).insert(Inspected); } } } pub fn selection_kill_inspector( mut commands: Commands, query: Query<(Entity, &Selection), (With<Inspected>, Changed<Selection>)>, ) { for (entity, selection) in query.iter() { if !selection.selected() { commands.entity(entity).remove::<Inspected>(); } } } pub fn selection_freeze_rigid_body( mut commands: Commands, query: Query<(Entity, &RigidBody, &Selection), Changed<Selection>>, ) { for (entity, body, selection) in query.iter() { if selection.selected() && body.can_have_velocity() { commands .entity(entity) .remove::<RigidBody>() .insert(RigidBody::Static) .insert(FrozenRigidBody(*body)); } } } pub fn selection_unfreeze_rigid_body( mut commands: Commands, query: Query<(Entity, &FrozenRigidBody, &Selection), Changed<Selection>>, ) { for (entity, body, selection) in query.iter() { if !selection.selected() { commands .entity(entity) .remove::<FrozenRigidBody>() .remove::<RigidBody>() .insert(body.0); } } } #[derive(Default)] pub struct Modes { inspect: bool, profiler: bool, } impl Modes { pub fn gameplay(&self) -> bool { return !(self.inspect || self.profiler); } } pub fn toggle_modes(mut modes: ResMut<Modes>, key: Res<Input<KeyCode>>) { if key.just_pressed(KeyCode::F1) { modes.inspect = !modes.inspect; } if key.just_pressed(KeyCode::F2) { modes.profiler = !modes.profiler; } } #[system] pub fn cursor_grab(mut windows: ResMut<Windows>, modes: Res<Modes>) { if modes.is_changed() { let grab = modes.gameplay(); let window = windows.get_primary_mut().unwrap(); window.set_cursor_lock_mode(grab); window.set_cursor_visibility(!grab); } } #[system] pub fn inspect_cursor( egui: Res<EguiContext>, inspectors: Res<InspectorWindows>, mut picking: ResMut<PickingPluginsState>, modes: ResMut<Modes>, ) { let cursor_over_area = egui .ctx_for_window(inspectors.window_data::<Inspection>().window_id) .is_pointer_over_area(); picking.enable_picking = modes.inspect; // && !pointer_over_area; picking.enable_interacting = modes.inspect && !cursor_over_area; picking.enable_highlighting = modes.inspect; // && !pointer_over_area; } #[system] pub fn draw_profiler_ui(#[cfg(feature = "profiler")] egui: Res<EguiContext>, modes: Res<Modes>) { profiling::finish_frame!(); if modes.profiler { if modes.is_changed() { #[cfg(feature = "profiler")] profiling::puffin::set_scopes_on(true); } #[cfg(feature = "profiler")] puffin_egui::profiler_window(egui.ctx()); } }
27.733333
97
0.637553
6932f5fed7694d4d6e22bdf66b4007f801b443ee
4,373
use serde::ser::{SerializeStruct, Serializer}; use serde::Serialize; use super::*; use crate::documents::{BuildXML, HistoryId, Run}; use crate::xml_builder::*; #[derive(Debug, Clone, PartialEq)] pub enum InsertChild { Run(Box<Run>), Delete(Delete), CommentStart(Box<CommentRangeStart>), CommentEnd(CommentRangeEnd), } impl BuildXML for InsertChild { fn build(&self) -> Vec<u8> { match self { InsertChild::Run(v) => v.build(), InsertChild::Delete(v) => v.build(), InsertChild::CommentStart(v) => v.build(), InsertChild::CommentEnd(v) => v.build(), } } } impl Serialize for InsertChild { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { InsertChild::Run(ref r) => { let mut t = serializer.serialize_struct("Run", 2)?; t.serialize_field("type", "run")?; t.serialize_field("data", r)?; t.end() } InsertChild::Delete(ref r) => { let mut t = serializer.serialize_struct("Delete", 2)?; t.serialize_field("type", "delete")?; t.serialize_field("data", r)?; t.end() } InsertChild::CommentStart(ref r) => { let mut t = serializer.serialize_struct("CommentRangeStart", 2)?; t.serialize_field("type", "commentRangeStart")?; t.serialize_field("data", r)?; t.end() } InsertChild::CommentEnd(ref r) => { let mut t = serializer.serialize_struct("CommentRangeEnd", 2)?; t.serialize_field("type", "commentRangeEnd")?; t.serialize_field("data", r)?; t.end() } } } } #[derive(Serialize, Debug, Clone, PartialEq)] pub struct Insert { pub children: Vec<InsertChild>, pub author: String, pub date: String, } impl Default for Insert { fn default() -> Insert { Insert { author: "unnamed".to_owned(), date: "1970-01-01T00:00:00Z".to_owned(), children: vec![], } } } impl Insert { pub fn new(run: Run) -> Insert { Self { children: vec![InsertChild::Run(Box::new(run))], ..Default::default() } } pub fn new_with_empty() -> Insert { Self { ..Default::default() } } pub fn new_with_del(del: Delete) -> Insert { Self { children: vec![InsertChild::Delete(del)], ..Default::default() } } pub fn add_run(mut self, run: Run) -> Insert { self.children.push(InsertChild::Run(Box::new(run))); self } pub fn add_delete(mut self, del: Delete) -> Insert { self.children.push(InsertChild::Delete(del)); self } pub fn add_child(mut self, c: InsertChild) -> Insert { self.children.push(c); self } pub fn add_comment_start(mut self, comment: Comment) -> Self { self.children.push(InsertChild::CommentStart(Box::new( CommentRangeStart::new(comment), ))); self } pub fn add_comment_end(mut self, id: usize) -> Self { self.children .push(InsertChild::CommentEnd(CommentRangeEnd::new(id))); self } pub fn author(mut self, author: impl Into<String>) -> Insert { self.author = author.into(); self } pub fn date(mut self, date: impl Into<String>) -> Insert { self.date = date.into(); self } } impl HistoryId for Insert {} impl BuildXML for Insert { fn build(&self) -> Vec<u8> { XMLBuilder::new() .open_insert(&self.generate(), &self.author, &self.date) .add_children(&self.children) .close() .build() } } #[cfg(test)] mod tests { use super::*; #[cfg(test)] use pretty_assertions::assert_eq; use std::str; #[test] fn test_ins_default() { let b = Insert::new(Run::new()).build(); assert_eq!( str::from_utf8(&b).unwrap(), r#"<w:ins w:id="123" w:author="unnamed" w:date="1970-01-01T00:00:00Z"><w:r><w:rPr /></w:r></w:ins>"# ); } }
26.029762
112
0.524125
e2b4346c32133c586259ed2bc52e9fe924f11104
657
fn how_many(x:i32) -> &'static str{ match x{ 0 => "no", 1 | 2 => "one or two", _z @ 9..=11 => "lots of", 12 => "a dozen", _ if (x % 2 == 0) => "some", _ => "a few" } } pub fn pattern_matching() { for x in 0..13 { println!("{}: I have {} oranges",x,how_many(x)); } let point = (3,4); match(point) { (0,0) => println!("origin"), (0,y) => println!("x axis, y = {}",y), (x,0) => println!("y axis, x = {}",x), (_,y) => println!("x =?, y = {}",y), (x,y) => println!("x ={}, y = {}",x,y), } } fn main() { pattern_matching(); }
21.193548
56
0.378995
eb5b7f42e33001533ca093e6df1f5ed8d8fe6e74
196
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! FFI bindings to ahadmin. #![no_std] #![experimental] extern crate winapi; use winapi::*; extern "system" { }
19.6
46
0.69898
5dcdd2eb8018f01592e5a20352f2c2767c4e8cfa
8,646
//! Provides userspace control of buttons on a board. //! //! This allows for much more cross platform controlling of buttons without //! having to know which of the GPIO pins exposed across the syscall interface //! are buttons. //! //! Usage //! ----- //! //! ```rust //! let button_pins = static_init!( //! [&'static sam4l::gpio::GPIOPin; 1], //! [&sam4l::gpio::PA[16]]); //! let button = static_init!( //! capsules::button::Button<'static, sam4l::gpio::GPIOPin>, //! capsules::button::Button::new(button_pins, kernel::Grant::create())); //! for btn in button_pins.iter() { //! btn.set_client(button); //! } //! ``` //! //! Syscall Interface //! ----------------- //! //! - Stability: 2 - Stable //! //! ### Command //! //! Enable or disable button interrupts and read the current button state. //! //! #### `command_num` //! //! - `0`: Driver check and get number of buttons on the board. //! - `1`: Enable interrupts for a given button. This will enable both press //! and depress events. //! - `2`: Disable interrupts for a button. No affect or reliance on //! registered callback. //! - `3`: Read the current state of the button. //! //! ### Subscribe //! //! Setup a callback for button presses. //! //! #### `subscribe_num` //! //! - `0`: Set callback for pin interrupts. Note setting this callback has //! no reliance on individual pins being configured as interrupts. The //! interrupt will be called with two parameters: the index of the button //! that triggered the interrupt and the pressed (1) or not pressed (0) state //! of the button. use core::cell::Cell; use kernel::hil; use kernel::hil::gpio::{Client, InterruptMode}; use kernel::{AppId, Callback, Driver, Grant, ReturnCode}; /// Syscall driver number. pub const DRIVER_NUM: usize = 0x00000003; /// This capsule keeps track for each app of which buttons it has a registered /// interrupt for. `SubscribeMap` is a bit array where bits are set to one if /// that app has an interrupt registered for that button. pub type SubscribeMap = u32; /// Whether the GPIOs for the buttons on this platform are low when the button /// is pressed or high. #[derive(Clone, Copy)] pub enum GpioMode { LowWhenPressed, HighWhenPressed, } /// Values that are passed to userspace to identify if the button is pressed /// or not. #[derive(Clone, Copy)] pub enum ButtonState { NotPressed = 0, Pressed = 1, } /// Manages the list of GPIO pins that are connected to buttons and which apps /// are listening for interrupts from which buttons. pub struct Button<'a, G: hil::gpio::Pin> { pins: &'a [(&'a G, GpioMode)], apps: Grant<(Option<Callback>, SubscribeMap)>, } impl<G: hil::gpio::Pin + hil::gpio::PinCtl> Button<'a, G> { pub fn new( pins: &'a [(&'a G, GpioMode)], grant: Grant<(Option<Callback>, SubscribeMap)>, ) -> Button<'a, G> { for &(pin, _) in pins.iter() { pin.make_input(); } Button { pins: pins, apps: grant, } } fn get_button_state(&self, pin_num: usize) -> ButtonState { let pin_value = self.pins[pin_num].0.read(); match self.pins[pin_num].1 { GpioMode::LowWhenPressed => match pin_value { false => ButtonState::Pressed, true => ButtonState::NotPressed, }, GpioMode::HighWhenPressed => match pin_value { false => ButtonState::NotPressed, true => ButtonState::Pressed, }, } } } impl<G: hil::gpio::Pin + hil::gpio::PinCtl> Driver for Button<'a, G> { /// Set callbacks. /// /// ### `subscribe_num` /// /// - `0`: Set callback for pin interrupts. Note setting this callback has /// no reliance on individual pins being configured as interrupts. The /// interrupt will be called with two parameters: the index of the button /// that triggered the interrupt and the pressed/not pressed state of the /// button. fn subscribe( &self, subscribe_num: usize, callback: Option<Callback>, app_id: AppId, ) -> ReturnCode { match subscribe_num { 0 => self .apps .enter(app_id, |cntr, _| { cntr.0 = callback; ReturnCode::SUCCESS }).unwrap_or_else(|err| err.into()), // default _ => ReturnCode::ENOSUPPORT, } } /// Configure interrupts and read state for buttons. /// /// `data` is the index of the button in the button array as passed to /// `Button::new()`. /// /// All commands greater than zero return `EINVAL` if an invalid button /// number is passed in. /// /// ### `command_num` /// /// - `0`: Driver check and get number of buttons on the board. /// - `1`: Enable interrupts for a given button. This will enable both press /// and depress events. /// - `2`: Disable interrupts for a button. No affect or reliance on /// registered callback. /// - `3`: Read the current state of the button. fn command(&self, command_num: usize, data: usize, _: usize, appid: AppId) -> ReturnCode { let pins = self.pins; match command_num { // return button count 0 => ReturnCode::SuccessWithValue { value: pins.len() as usize, }, // enable interrupts for a button 1 => { if data < pins.len() { self.apps .enter(appid, |cntr, _| { cntr.1 |= 1 << data; pins[data] .0 .enable_interrupt(data, InterruptMode::EitherEdge); ReturnCode::SUCCESS }).unwrap_or_else(|err| err.into()) } else { ReturnCode::EINVAL /* impossible button */ } } // disable interrupts for a button 2 => { if data >= pins.len() { ReturnCode::EINVAL /* impossible button */ } else { let res = self .apps .enter(appid, |cntr, _| { cntr.1 &= !(1 << data); ReturnCode::SUCCESS }).unwrap_or_else(|err| err.into()); // are any processes waiting for this button? let interrupt_count = Cell::new(0); self.apps.each(|cntr| { cntr.0.map(|_| { if cntr.1 & (1 << data) != 0 { interrupt_count.set(interrupt_count.get() + 1); } }); }); // if not, disable the interrupt if interrupt_count.get() == 0 { self.pins[data].0.disable_interrupt(); } res } } // read input 3 => { if data >= pins.len() { ReturnCode::EINVAL /* impossible button */ } else { let button_state = self.get_button_state(data); ReturnCode::SuccessWithValue { value: button_state as usize, } } } // default _ => ReturnCode::ENOSUPPORT, } } } impl<G: hil::gpio::Pin + hil::gpio::PinCtl> Client for Button<'a, G> { fn fired(&self, pin_num: usize) { // Read the value of the pin and get the button state. let button_state = self.get_button_state(pin_num); let interrupt_count = Cell::new(0); // schedule callback with the pin number and value self.apps.each(|cntr| { cntr.0.map(|mut callback| { if cntr.1 & (1 << pin_num) != 0 { interrupt_count.set(interrupt_count.get() + 1); callback.schedule(pin_num, button_state as usize, 0); } }); }); // It's possible we got an interrupt for a process that has since died // (and didn't unregister the interrupt). Lazily disable interrupts for // this button if so. if interrupt_count.get() == 0 { self.pins[pin_num].0.disable_interrupt(); } } }
33.253846
94
0.523826
dd23a5d6d08d44885b37b214d30396aa63256b30
3,541
use std::{ collections::BTreeMap, fs::File, net::{IpAddr, Ipv4Addr, SocketAddr}, sync::{Arc, RwLock}, }; use clap::{App as ClapApp, Arg as ClapArg}; use serde::Deserialize; use crate::{ database::MemoryDb, plugin::{load_plugins, Plugin}, task::TaskState, }; #[derive(Clone, Debug, Deserialize)] #[serde(default)] pub(crate) struct AppConfig { pub plugins_path: String, pub bind_address: SocketAddr, } impl Default for AppConfig { fn default() -> Self { Self { plugins_path: "./".into(), bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8000), } } } fn load_config_from_file(path: String) -> Result<AppConfig, String> { let file = File::open(path).map_err(|e| e.to_string())?; serde_json::from_reader::<_, AppConfig>(file).map_err(|e| e.to_string()) } impl AppConfig { pub(crate) fn from_clap() -> Self { let cli = ClapApp::new("Task processing server") .version("1.0") .author("Andrey \"Flowneee\" Kononov. <[email protected]>") .about("Uploads image and generates preview") .arg( ClapArg::with_name("bind-address") .short("a") .long("bind-address") .value_name("ADDRESS") .help("Server bind address") .takes_value(true) .default_value("127.0.0.1:8000") .validator(|x| { x.parse::<SocketAddr>() .map(|_| ()) .map_err(|x| x.to_string()) }), ) .arg( ClapArg::with_name("plugins-path") .short("p") .long("plugins-path") .value_name("PATH") .help("Location of plugins") .takes_value(true) .default_value("./"), ) .arg( ClapArg::with_name("config-path") .short("c") .long("config-path") .value_name("PATH") .help("Path to configuration file (in JSON format)") .takes_value(true), ) .get_matches(); let mut base_config = match cli.value_of("config-path") { Some(x) => load_config_from_file(x.into()).unwrap(), None => AppConfig::default(), }; if let Some(x) = cli.value_of("bind-address") { base_config.bind_address = x.parse().unwrap_or_else(|_| { unimplemented!("'bind-address' should be validated inside clap") }); }; if let Some(x) = cli.value_of("plugins-path") { base_config.plugins_path = x.into() }; base_config } } #[derive(Clone)] pub(crate) struct App { pub plugins: Arc<RwLock<BTreeMap<String, Plugin>>>, pub database: Arc<MemoryDb<TaskState>>, pub stop_tasks_flag: Arc<RwLock<()>>, pub config: AppConfig, } impl App { pub(crate) fn from_config(config: AppConfig) -> Result<Self, ()> { let database = Arc::new(MemoryDb::new()); let plugins = Arc::new(RwLock::new( load_plugins(config.plugins_path.clone()).unwrap(), )); Ok(Self { plugins, database, stop_tasks_flag: Arc::new(RwLock::new(())), config, }) } }
30.264957
89
0.499012
f5ae65101fe18436908ac3bb3c79fead30a265c1
4,006
// Chariot: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use empires::resource::{ResourceCost, ReadResourceCost}; use error::{Result, ErrorKind}; use identifier::{LocalizationId, AgeId, UnitId, ResearchId}; use chariot_io_tools::{ReadExt, ReadArrayExt}; use std::io::prelude::{Seek, Read}; const MAX_REQUIRED_TECHS: usize = 4; const RESOURCE_COST_COUNT: usize = 3; pub type ResearchCost = ResourceCost<i16, u8>; #[derive(Default, Debug)] pub struct Research { pub id: ResearchId, pub required_techs: Vec<i16>, pub resource_costs: Vec<ResearchCost>, /// Unit id of the location this research can be performed pub location: Option<UnitId>, pub name_id: LocalizationId, pub description_id: LocalizationId, /// How much time the research takes to complete pub time_seconds: i16, pub age_id: Option<AgeId>, pub type_id: i16, /// Frame number in 50729.slp in interfac.drs to use for the button graphic pub icon_id: i16, /// Button slot position pub button_id: i8, pub help_id: Option<LocalizationId>, pub tech_tree_id: Option<LocalizationId>, pub name: String, } pub fn read_research<R: Read + Seek>(stream: &mut R) -> Result<Vec<Research>> { let research_count = try!(stream.read_u16()) as usize; let mut research = try!(stream.read_array(research_count, |c| read_single_research(c))); for i in 0..research.len() { research[i].id = i.into(); } Ok(research) } fn read_single_research<R: Read + Seek>(stream: &mut R) -> Result<Research> { let mut research: Research = Default::default(); research.required_techs = try!(stream.read_array(MAX_REQUIRED_TECHS, |c| c.read_i16())); research.resource_costs = read_resource_costs!(i16, u8, stream, RESOURCE_COST_COUNT); let actual_required_techs = try!(stream.read_u16()) as usize; if actual_required_techs > MAX_REQUIRED_TECHS { return Err(ErrorKind::BadFile("more required techs than possible").into()); } else { research.required_techs.resize(actual_required_techs, Default::default()); } research.location = optional_id!(try!(stream.read_i16())); research.name_id = required_id!(try!(stream.read_i16())); research.description_id = required_id!(try!(stream.read_i16())); research.time_seconds = try!(stream.read_i16()); research.age_id = optional_id!(try!(stream.read_i16())); research.type_id = try!(stream.read_i16()); research.icon_id = try!(stream.read_i16()); research.button_id = try!(stream.read_i8()); research.help_id = optional_id!(try!(stream.read_i32())); research.tech_tree_id = optional_id!(try!(stream.read_i32())); try!(stream.read_i32()); // Unknown let name_length = try!(stream.read_u16()) as usize; if name_length > 0 { research.name = try!(stream.read_sized_str(name_length)); } Ok(research) }
38.893204
92
0.714678
b92d343b4654a9c1b0c197d716051a2450bac6df
4,434
use crate::DERIVE_CDRS_PK; use cdrs_query_writer::{primary_key, Inf}; use proc_macro2::TokenStream; use quote::quote; /// Generates the primary key struct pub fn generate(inf: &Inf) -> TokenStream { if inf.partition_fields.is_empty() { return TokenStream::new(); } let name = inf.name; let pk_struct = &inf.pk_struct; let pk_parameter = &inf.pk_parameter; let pk_parameter_cloned = &inf.pk_parameter_cloned; let idents = inf .pk_fields .iter() .map(|p| p.ident.clone().unwrap()) .collect::<Vec<_>>(); let mut properties = TokenStream::new(); let mut mapping_with_self = TokenStream::new(); let mut mapping_without_self = TokenStream::new(); for pk in inf.pk_fields.iter() { let ident = pk.ident.clone().unwrap(); let ty = &pk.ty; if proc_macro2_helper::attributes_contains(&pk.attrs, "json_mapped") { properties.extend(quote! { #[json_mapped] }); } properties.extend(quote! { pub #ident: #ty, }); mapping_with_self.extend(quote! { #ident: self.#ident, }); mapping_without_self.extend(quote! { #ident: self.#ident.clone(), }); } let default_derives = vec![ "PartialEq", "Clone", "Debug", "serde::Serialize", "serde::Deserialize", "cdrs_db_mirror::DBJson", "cdrs_tokio_helpers_derive::TryFromRow", ]; let mut default_derives = default_derives .into_iter() .map(|d| d.parse().unwrap()) .collect(); let mut derives = extract_custom_derives(); derives.append(&mut default_derives); let where_clause_query = cdrs_query_writer::where_pk_query_from_idents(&idents); let where_clause_pk = primary_key(); let idents_len = idents.len(); quote! { #[derive(#(#derives),*)] pub struct #pk_struct { #properties } impl #name { pub fn #pk_parameter(self) -> #pk_struct { #pk_struct { #mapping_with_self } } pub fn #pk_parameter_cloned(&self) -> #pk_struct { #pk_struct { #mapping_without_self } } } impl #pk_struct { pub const #where_clause_pk: &'static str = #where_clause_query; pub fn where_clause(self) -> cdrs_tokio::query::QueryValues { cdrs_tokio::query::QueryValues::SimpleValues(self.where_clause_raw()) } pub fn where_clause_raw(self) -> Vec<cdrs_tokio::types::value::Value> { use std::iter::FromIterator; let mut query_values: Vec<cdrs_tokio::types::value::Value> = Vec::with_capacity(#idents_len); #( query_values.push(cdrs_tokio::types::value::Value::new_normal(self.#idents)); )* query_values } } } } fn extract_custom_derives() -> Vec<TokenStream> { match std::env::var(DERIVE_CDRS_PK) { Ok(value_string) => { if value_string.is_empty() { vec![] } else { let values = value_string.split(','); let mut values_vec = Vec::new(); for value in values { values_vec.push(value.parse().unwrap()); } values_vec } } _ => vec![], } } #[cfg(test)] mod test { use super::*; #[test] fn test_extract_custom_derives() { let current_val = std::env::var(DERIVE_CDRS_PK); assert!(extract_custom_derives().is_empty()); std::env::set_var(DERIVE_CDRS_PK, "Copy"); let result = extract_custom_derives(); assert_eq!(1, result.len()); assert_eq!("Copy", result[0].to_string().as_str()); std::env::set_var(DERIVE_CDRS_PK, "Copy,Clone,Something"); let result = extract_custom_derives(); assert_eq!(3, result.len()); assert_eq!("Copy", result[0].to_string().as_str()); assert_eq!("Clone", result[1].to_string().as_str()); assert_eq!("Something", result[2].to_string().as_str()); if let Ok(e) = current_val { std::env::set_var(DERIVE_CDRS_PK, e); } } }
27.7125
109
0.5424
d96969c99f3cac2d14a57654f15309ee32e39750
17,260
use core::fmt; use crate::{Error, Result}; enum_with_unknown! { /// IPv6 Extension Header Option Type pub doc enum Type(u8) { /// 1 byte of padding Pad1 = 0, /// Multiple bytes of padding PadN = 1 } } impl fmt::Display for Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Type::Pad1 => write!(f, "Pad1"), Type::PadN => write!(f, "PadN"), Type::Unknown(id) => write!(f, "{}", id) } } } enum_with_unknown! { /// Action required when parsing the given IPv6 Extension /// Header Option Type fails pub doc enum FailureType(u8) { /// Skip this option and continue processing the packet Skip = 0b00000000, /// Discard the containing packet Discard = 0b01000000, /// Discard the containing packet and notify the sender DiscardSendAll = 0b10000000, /// Discard the containing packet and only notify the sender /// if the sender is a unicast address DiscardSendUnicast = 0b11000000, } } impl fmt::Display for FailureType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { FailureType::Skip => write!(f, "skip"), FailureType::Discard => write!(f, "discard"), FailureType::DiscardSendAll => write!(f, "discard and send error"), FailureType::DiscardSendUnicast => write!(f, "discard and send error if unicast"), FailureType::Unknown(id) => write!(f, "Unknown({})", id), } } } impl From<Type> for FailureType { fn from(other: Type) -> FailureType { let raw: u8 = other.into(); Self::from(raw & 0b11000000u8) } } /// A read/write wrapper around an IPv6 Extension Header Option. #[derive(Debug, PartialEq)] pub struct Ipv6Option<T: AsRef<[u8]>> { buffer: T } // Format of Option // // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - // | Option Type | Opt Data Len | Option Data // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - // // // See https://tools.ietf.org/html/rfc8200#section-4.2 for details. mod field { #![allow(non_snake_case)] use crate::wire::field::*; // 8-bit identifier of the type of option. pub const TYPE: usize = 0; // 8-bit unsigned integer. Length of the DATA field of this option, in octets. pub const LENGTH: usize = 1; // Variable-length field. Option-Type-specific data. pub fn DATA(length: u8) -> Field { 2..length as usize + 2 } } impl<T: AsRef<[u8]>> Ipv6Option<T> { /// Create a raw octet buffer with an IPv6 Extension Header Option structure. pub fn new_unchecked(buffer: T) -> Ipv6Option<T> { Ipv6Option { buffer } } /// Shorthand for a combination of [new_unchecked] and [check_len]. /// /// [new_unchecked]: #method.new_unchecked /// [check_len]: #method.check_len pub fn new_checked(buffer: T) -> Result<Ipv6Option<T>> { let opt = Self::new_unchecked(buffer); opt.check_len()?; Ok(opt) } /// Ensure that no accessor method will panic if called. /// Returns `Err(Error::Truncated)` if the buffer is too short. /// /// The result of this check is invalidated by calling [set_data_len]. /// /// [set_data_len]: #method.set_data_len pub fn check_len(&self) -> Result<()> { let data = self.buffer.as_ref(); let len = data.len(); if len < field::LENGTH { return Err(Error::Truncated); } if self.option_type() == Type::Pad1 { return Ok(()); } if len == field::LENGTH { return Err(Error::Truncated); } let df = field::DATA(data[field::LENGTH]); if len < df.end { return Err(Error::Truncated); } Ok(()) } /// Consume the ipv6 option, returning the underlying buffer. pub fn into_inner(self) -> T { self.buffer } /// Return the option type. #[inline] pub fn option_type(&self) -> Type { let data = self.buffer.as_ref(); Type::from(data[field::TYPE]) } /// Return the length of the data. /// /// # Panics /// This function panics if this is an 1-byte padding option. #[inline] pub fn data_len(&self) -> u8 { let data = self.buffer.as_ref(); data[field::LENGTH] } } impl<'a, T: AsRef<[u8]> + ?Sized> Ipv6Option<&'a T> { /// Return the option data. /// /// # Panics /// This function panics if this is an 1-byte padding option. #[inline] pub fn data(&self) -> &'a [u8] { let len = self.data_len(); let data = self.buffer.as_ref(); &data[field::DATA(len)] } } impl<T: AsRef<[u8]> + AsMut<[u8]>> Ipv6Option<T> { /// Set the option type. #[inline] pub fn set_option_type(&mut self, value: Type) { let data = self.buffer.as_mut(); data[field::TYPE] = value.into(); } /// Set the option data length. /// /// # Panics /// This function panics if this is an 1-byte padding option. #[inline] pub fn set_data_len(&mut self, value: u8) { let data = self.buffer.as_mut(); data[field::LENGTH] = value; } } impl<'a, T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> Ipv6Option<&'a mut T> { /// Return a mutable pointer to the option data. /// /// # Panics /// This function panics if this is an 1-byte padding option. #[inline] pub fn data_mut(&mut self) -> &mut [u8] { let len = self.data_len(); let data = self.buffer.as_mut(); &mut data[field::DATA(len)] } } impl<'a, T: AsRef<[u8]> + ?Sized> fmt::Display for Ipv6Option<&'a T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match Repr::parse(self) { Ok(repr) => write!(f, "{}", repr), Err(err) => { write!(f, "IPv6 Extension Option ({})", err)?; Ok(()) } } } } /// A high-level representation of an IPv6 Extension Header Option. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Repr<'a> { Pad1, PadN(u8), Unknown { type_: Type, length: u8, data: &'a [u8] }, #[doc(hidden)] __Nonexhaustive } impl<'a> Repr<'a> { /// Parse an IPv6 Extension Header Option and return a high-level representation. pub fn parse<T>(opt: &Ipv6Option<&'a T>) -> Result<Repr<'a>> where T: AsRef<[u8]> + ?Sized { match opt.option_type() { Type::Pad1 => Ok(Repr::Pad1), Type::PadN => Ok(Repr::PadN(opt.data_len())), unknown_type @ Type::Unknown(_) => { Ok(Repr::Unknown { type_: unknown_type, length: opt.data_len(), data: opt.data(), }) } } } /// Return the length of a header that will be emitted from this high-level representation. pub fn buffer_len(&self) -> usize { match *self { Repr::Pad1 => 1, Repr::PadN(length) => field::DATA(length).end, Repr::Unknown{ length, .. } => field::DATA(length).end, Repr::__Nonexhaustive => unreachable!() } } /// Emit a high-level representation into an IPv6 Extension Header Option. pub fn emit<T: AsRef<[u8]> + AsMut<[u8]> + ?Sized>(&self, opt: &mut Ipv6Option<&'a mut T>) { match *self { Repr::Pad1 => opt.set_option_type(Type::Pad1), Repr::PadN(len) => { opt.set_option_type(Type::PadN); opt.set_data_len(len); // Ensure all padding bytes are set to zero. for x in opt.data_mut().iter_mut() { *x = 0 } } Repr::Unknown{ type_, length, data } => { opt.set_option_type(type_); opt.set_data_len(length); opt.data_mut().copy_from_slice(&data[..length as usize]); } Repr::__Nonexhaustive => unreachable!() } } } /// A iterator for IPv6 options. #[derive(Debug)] pub struct Ipv6OptionsIterator<'a> { pos: usize, length: usize, data: &'a [u8], hit_error: bool } impl<'a> Ipv6OptionsIterator<'a> { /// Create a new `Ipv6OptionsIterator`, used to iterate over the /// options contained in a IPv6 Extension Header (e.g. the Hop-by-Hop /// header). /// /// # Panics /// This function panics if the `length` provided is larger than the /// length of the `data` buffer. pub fn new(data: &'a [u8], length: usize) -> Ipv6OptionsIterator<'a> { assert!(length <= data.len()); Ipv6OptionsIterator { pos: 0, hit_error: false, length, data } } /// Helper function to return an error in the implementation /// of `Iterator`. #[inline] fn return_err(&mut self, err: Error) -> Option<Result<Repr<'a>>> { self.hit_error = true; Some(Err(err)) } } impl<'a> Iterator for Ipv6OptionsIterator<'a> { type Item = Result<Repr<'a>>; fn next(&mut self) -> Option<Self::Item> { if self.pos < self.length && !self.hit_error { // If we still have data to parse and we have not previously // hit an error, attempt to parse the next option. match Ipv6Option::new_checked(&self.data[self.pos..]) { Ok(hdr) => { match Repr::parse(&hdr) { Ok(repr) => { self.pos += repr.buffer_len(); Some(Ok(repr)) } Err(e) => { self.return_err(e) } } } Err(e) => { self.return_err(e) } } } else { // If we failed to parse a previous option or hit the end of the // buffer, we do not continue to iterate. None } } } impl<'a> fmt::Display for Repr<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "IPv6 Option ")?; match *self { Repr::Pad1 => write!(f, "{} ", Type::Pad1), Repr::PadN(len) => write!(f, "{} length={} ", Type::PadN, len), Repr::Unknown{ type_, length, .. } => write!(f, "{} length={} ", type_, length), Repr::__Nonexhaustive => unreachable!() } } } #[cfg(test)] mod test { use super::*; static IPV6OPTION_BYTES_PAD1: [u8; 1] = [0x0]; static IPV6OPTION_BYTES_PADN: [u8; 3] = [0x1, 0x1, 0x0]; static IPV6OPTION_BYTES_UNKNOWN: [u8; 5] = [0xff, 0x3, 0x0, 0x0, 0x0]; #[test] fn test_check_len() { let bytes = [0u8]; // zero byte buffer assert_eq!(Err(Error::Truncated), Ipv6Option::new_unchecked(&bytes[..0]).check_len()); // pad1 assert_eq!(Ok(()), Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_PAD1).check_len()); // padn with truncated data assert_eq!(Err(Error::Truncated), Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_PADN[..2]).check_len()); // padn assert_eq!(Ok(()), Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_PADN).check_len()); // unknown option type with truncated data assert_eq!(Err(Error::Truncated), Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_UNKNOWN[..4]).check_len()); assert_eq!(Err(Error::Truncated), Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_UNKNOWN[..1]).check_len()); // unknown type assert_eq!(Ok(()), Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_UNKNOWN).check_len()); } #[test] #[should_panic(expected = "index out of bounds")] fn test_data_len() { let opt = Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_PAD1); opt.data_len(); } #[test] fn test_option_deconstruct() { // one octet of padding let opt = Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_PAD1); assert_eq!(opt.option_type(), Type::Pad1); // two octets of padding let bytes: [u8; 2] = [0x1, 0x0]; let opt = Ipv6Option::new_unchecked(&bytes); assert_eq!(opt.option_type(), Type::PadN); assert_eq!(opt.data_len(), 0); // three octets of padding let opt = Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_PADN); assert_eq!(opt.option_type(), Type::PadN); assert_eq!(opt.data_len(), 1); assert_eq!(opt.data(), &[0]); // extra bytes in buffer let bytes: [u8; 10] = [0x1, 0x7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff]; let opt = Ipv6Option::new_unchecked(&bytes); assert_eq!(opt.option_type(), Type::PadN); assert_eq!(opt.data_len(), 7); assert_eq!(opt.data(), &[0, 0, 0, 0, 0, 0, 0]); // unrecognized option let bytes: [u8; 1] = [0xff]; let opt = Ipv6Option::new_unchecked(&bytes); assert_eq!(opt.option_type(), Type::Unknown(255)); // unrecognized option without length and data assert_eq!(Ipv6Option::new_checked(&bytes), Err(Error::Truncated)); } #[test] fn test_option_parse() { // one octet of padding let opt = Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_PAD1); let pad1 = Repr::parse(&opt).unwrap(); assert_eq!(pad1, Repr::Pad1); assert_eq!(pad1.buffer_len(), 1); // two or more octets of padding let opt = Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_PADN); let padn = Repr::parse(&opt).unwrap(); assert_eq!(padn, Repr::PadN(1)); assert_eq!(padn.buffer_len(), 3); // unrecognized option type let data = [0u8; 3]; let opt = Ipv6Option::new_unchecked(&IPV6OPTION_BYTES_UNKNOWN); let unknown = Repr::parse(&opt).unwrap(); assert_eq!(unknown, Repr::Unknown { type_: Type::Unknown(255), length: 3, data: &data }); } #[test] fn test_option_emit() { let repr = Repr::Pad1; let mut bytes = [255u8; 1]; // don't assume bytes are initialized to zero let mut opt = Ipv6Option::new_unchecked(&mut bytes); repr.emit(&mut opt); assert_eq!(opt.into_inner(), &IPV6OPTION_BYTES_PAD1); let repr = Repr::PadN(1); let mut bytes = [255u8; 3]; // don't assume bytes are initialized to zero let mut opt = Ipv6Option::new_unchecked(&mut bytes); repr.emit(&mut opt); assert_eq!(opt.into_inner(), &IPV6OPTION_BYTES_PADN); let data = [0u8; 3]; let repr = Repr::Unknown { type_: Type::Unknown(255), length: 3, data: &data }; let mut bytes = [254u8; 5]; // don't assume bytes are initialized to zero let mut opt = Ipv6Option::new_unchecked(&mut bytes); repr.emit(&mut opt); assert_eq!(opt.into_inner(), &IPV6OPTION_BYTES_UNKNOWN); } #[test] fn test_failure_type() { let mut failure_type: FailureType = Type::Pad1.into(); assert_eq!(failure_type, FailureType::Skip); failure_type = Type::PadN.into(); assert_eq!(failure_type, FailureType::Skip); failure_type = Type::Unknown(0b01000001).into(); assert_eq!(failure_type, FailureType::Discard); failure_type = Type::Unknown(0b10100000).into(); assert_eq!(failure_type, FailureType::DiscardSendAll); failure_type = Type::Unknown(0b11000100).into(); assert_eq!(failure_type, FailureType::DiscardSendUnicast); } #[test] fn test_options_iter() { let options = [0x00, 0x01, 0x01, 0x00, 0x01, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x11, 0x00, 0x01, 0x08, 0x00]; let mut iterator = Ipv6OptionsIterator::new(&options, 0); assert_eq!(iterator.next(), None); iterator = Ipv6OptionsIterator::new(&options, 16); for (i, opt) in iterator.enumerate() { match (i, opt) { (0, Ok(Repr::Pad1)) => continue, (1, Ok(Repr::PadN(1))) => continue, (2, Ok(Repr::PadN(2))) => continue, (3, Ok(Repr::PadN(0))) => continue, (4, Ok(Repr::Pad1)) => continue, (5, Ok(Repr::Unknown { type_: Type::Unknown(0x11), length: 0, .. })) => continue, (6, Err(Error::Truncated)) => continue, (i, res) => panic!("Unexpected option `{:?}` at index {}", res, i), } } } #[test] #[should_panic(expected = "length <= data.len()")] fn test_options_iter_truncated() { let options = [0x01, 0x02, 0x00, 0x00]; let _ = Ipv6OptionsIterator::new(&options, 5); } }
32.382739
97
0.535921
9b8c5c63beca9a8904bfe1ddaaa2114230f7940d
2,164
// Copyright 2020 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. use std::sync::Arc; use common_datavalues::DataSchema; use common_datavalues::DataSchemaRef; use common_meta_types::MetaId; use common_meta_types::MetaVersion; use crate::Expression; use crate::Extras; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct ScanPlan { // The name of the schema pub schema_name: String, pub table_id: MetaId, pub table_version: Option<MetaVersion>, // The schema of the source data pub table_schema: DataSchemaRef, pub table_args: Option<Expression>, pub projected_schema: DataSchemaRef, // Extras. pub push_downs: Extras, } impl ScanPlan { pub fn schema(&self) -> DataSchemaRef { self.projected_schema.clone() } pub fn with_table_id(table_id: u64, table_version: Option<u64>) -> ScanPlan { ScanPlan { schema_name: "".to_string(), table_id, table_version, table_schema: Arc::new(DataSchema::empty()), projected_schema: Arc::new(DataSchema::empty()), table_args: None, push_downs: Extras::default(), } } pub fn empty() -> Self { Self { schema_name: "".to_string(), table_id: 0, table_version: None, table_schema: Arc::new(DataSchema::empty()), projected_schema: Arc::new(DataSchema::empty()), table_args: None, push_downs: Extras::default(), } } } impl Default for ScanPlan { fn default() -> Self { Self::empty() } }
29.243243
81
0.646488
2fddda74a28e924bfd3e7db776bdc38e67a15933
28,585
//! Command-line interface of the rustbuild build system. //! //! This module implements the command-line parsing of the build system which //! has various flags to configure how it's run. use std::env; use std::path::PathBuf; use std::process; use build_helper::t; use getopts::Options; use crate::builder::Builder; use crate::config::{Config, TargetSelection}; use crate::setup::Profile; use crate::{Build, DocTests}; pub enum Color { Always, Never, Auto, } impl Default for Color { fn default() -> Self { Self::Auto } } impl std::str::FromStr for Color { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().as_str() { "always" => Ok(Self::Always), "never" => Ok(Self::Never), "auto" => Ok(Self::Auto), _ => Err(()), } } } /// Deserialized version of all flags for this compile. pub struct Flags { pub verbose: usize, // number of -v args; each extra -v after the first is passed to Cargo pub on_fail: Option<String>, pub stage: Option<u32>, pub keep_stage: Vec<u32>, pub keep_stage_std: Vec<u32>, pub host: Option<Vec<TargetSelection>>, pub target: Option<Vec<TargetSelection>>, pub config: Option<PathBuf>, pub jobs: Option<u32>, pub cmd: Subcommand, pub incremental: bool, pub exclude: Vec<PathBuf>, pub include_default_paths: bool, pub rustc_error_format: Option<String>, pub json_output: bool, pub dry_run: bool, pub color: Color, // This overrides the deny-warnings configuration option, // which passes -Dwarnings to the compiler invocations. // // true => deny, false => warn pub deny_warnings: Option<bool>, pub llvm_skip_rebuild: Option<bool>, pub rust_profile_use: Option<String>, pub rust_profile_generate: Option<String>, pub llvm_profile_use: Option<String>, // LLVM doesn't support a custom location for generating profile // information. // // llvm_out/build/profiles/ is the location this writes to. pub llvm_profile_generate: bool, } pub enum Subcommand { Build { paths: Vec<PathBuf>, }, Check { paths: Vec<PathBuf>, }, Clippy { fix: bool, paths: Vec<PathBuf>, }, Fix { paths: Vec<PathBuf>, }, Format { paths: Vec<PathBuf>, check: bool, }, Doc { paths: Vec<PathBuf>, open: bool, }, Test { paths: Vec<PathBuf>, /// Whether to automatically update stderr/stdout files bless: bool, force_rerun: bool, compare_mode: Option<String>, pass: Option<String>, run: Option<String>, test_args: Vec<String>, rustc_args: Vec<String>, fail_fast: bool, doc_tests: DocTests, rustfix_coverage: bool, }, Bench { paths: Vec<PathBuf>, test_args: Vec<String>, }, Clean { all: bool, }, Dist { paths: Vec<PathBuf>, }, Install { paths: Vec<PathBuf>, }, Run { paths: Vec<PathBuf>, }, Setup { profile: Profile, }, } impl Default for Subcommand { fn default() -> Subcommand { Subcommand::Build { paths: vec![PathBuf::from("nowhere")] } } } impl Flags { pub fn parse(args: &[String]) -> Flags { let mut subcommand_help = String::from( "\ Usage: x.py <subcommand> [options] [<paths>...] Subcommands: build, b Compile either the compiler or libraries check, c Compile either the compiler or libraries, using cargo check clippy Run clippy (uses rustup/cargo-installed clippy binary) fix Run cargo fix fmt Run rustfmt test, t Build and run some test suites bench Build and run some benchmarks doc, d Build documentation clean Clean out build directories dist Build distribution artifacts install Install distribution artifacts run, r Run tools contained in this repository setup Create a config.toml (making it easier to use `x.py` itself) To learn more about a subcommand, run `./x.py <subcommand> -h`", ); let mut opts = Options::new(); // Options common to all subcommands opts.optflagmulti("v", "verbose", "use verbose output (-vv for very verbose)"); opts.optflag("i", "incremental", "use incremental compilation"); opts.optopt("", "config", "TOML configuration file for build", "FILE"); opts.optopt("", "build", "build target of the stage0 compiler", "BUILD"); opts.optmulti("", "host", "host targets to build", "HOST"); opts.optmulti("", "target", "target targets to build", "TARGET"); opts.optmulti("", "exclude", "build paths to exclude", "PATH"); opts.optflag( "", "include-default-paths", "include default paths in addition to the provided ones", ); opts.optopt("", "on-fail", "command to run on failure", "CMD"); opts.optflag("", "dry-run", "dry run; don't build anything"); opts.optopt( "", "stage", "stage to build (indicates compiler to use/test, e.g., stage 0 uses the \ bootstrap compiler, stage 1 the stage 0 rustc artifacts, etc.)", "N", ); opts.optmulti( "", "keep-stage", "stage(s) to keep without recompiling \ (pass multiple times to keep e.g., both stages 0 and 1)", "N", ); opts.optmulti( "", "keep-stage-std", "stage(s) of the standard library to keep without recompiling \ (pass multiple times to keep e.g., both stages 0 and 1)", "N", ); opts.optopt("", "src", "path to the root of the rust checkout", "DIR"); let j_msg = format!( "number of jobs to run in parallel; \ defaults to {} (this host's logical CPU count)", num_cpus::get() ); opts.optopt("j", "jobs", &j_msg, "JOBS"); opts.optflag("h", "help", "print this help message"); opts.optopt( "", "warnings", "if value is deny, will deny warnings, otherwise use default", "VALUE", ); opts.optopt("", "error-format", "rustc error format", "FORMAT"); opts.optflag("", "json-output", "use message-format=json"); opts.optopt("", "color", "whether to use color in cargo and rustc output", "STYLE"); opts.optopt( "", "llvm-skip-rebuild", "whether rebuilding llvm should be skipped \ a VALUE of TRUE indicates that llvm will not be rebuilt \ VALUE overrides the skip-rebuild option in config.toml.", "VALUE", ); opts.optopt( "", "rust-profile-generate", "generate PGO profile with rustc build", "PROFILE", ); opts.optopt("", "rust-profile-use", "use PGO profile for rustc build", "PROFILE"); opts.optflag("", "llvm-profile-generate", "generate PGO profile with llvm built for rustc"); opts.optopt("", "llvm-profile-use", "use PGO profile for llvm build", "PROFILE"); // We can't use getopt to parse the options until we have completed specifying which // options are valid, but under the current implementation, some options are conditional on // the subcommand. Therefore we must manually identify the subcommand first, so that we can // complete the definition of the options. Then we can use the getopt::Matches object from // there on out. let subcommand = args.iter().find(|&s| { (s == "build") || (s == "b") || (s == "check") || (s == "c") || (s == "clippy") || (s == "fix") || (s == "fmt") || (s == "test") || (s == "t") || (s == "bench") || (s == "doc") || (s == "d") || (s == "clean") || (s == "dist") || (s == "install") || (s == "run") || (s == "r") || (s == "setup") }); let subcommand = match subcommand { Some(s) => s, None => { // No or an invalid subcommand -- show the general usage and subcommand help // An exit code will be 0 when no subcommand is given, and 1 in case of an invalid // subcommand. println!("{}\n", subcommand_help); let exit_code = if args.is_empty() { 0 } else { 1 }; process::exit(exit_code); } }; // Some subcommands get extra options match subcommand.as_str() { "test" | "t" => { opts.optflag("", "no-fail-fast", "Run all tests regardless of failure"); opts.optmulti( "", "test-args", "extra arguments to be passed for the test tool being used \ (e.g. libtest, compiletest or rustdoc)", "ARGS", ); opts.optmulti( "", "rustc-args", "extra options to pass the compiler when running tests", "ARGS", ); opts.optflag("", "no-doc", "do not run doc tests"); opts.optflag("", "doc", "only run doc tests"); opts.optflag("", "bless", "update all stderr/stdout files of failing ui tests"); opts.optflag("", "force-rerun", "rerun tests even if the inputs are unchanged"); opts.optopt( "", "compare-mode", "mode describing what file the actual ui output will be compared to", "COMPARE MODE", ); opts.optopt( "", "pass", "force {check,build,run}-pass tests to this mode.", "check | build | run", ); opts.optopt("", "run", "whether to execute run-* tests", "auto | always | never"); opts.optflag( "", "rustfix-coverage", "enable this to generate a Rustfix coverage file, which is saved in \ `/<build_base>/rustfix_missing_coverage.txt`", ); } "check" | "c" => { opts.optflag("", "all-targets", "Check all targets"); } "bench" => { opts.optmulti("", "test-args", "extra arguments", "ARGS"); } "clippy" => { opts.optflag("", "fix", "automatically apply lint suggestions"); } "doc" | "d" => { opts.optflag("", "open", "open the docs in a browser"); } "clean" => { opts.optflag("", "all", "clean all build artifacts"); } "fmt" => { opts.optflag("", "check", "check formatting instead of applying."); } _ => {} }; // fn usage() let usage = |exit_code: i32, opts: &Options, verbose: bool, subcommand_help: &str| -> ! { let mut extra_help = String::new(); // All subcommands except `clean` can have an optional "Available paths" section if verbose { let config = Config::parse(&["build".to_string()]); let build = Build::new(config); let maybe_rules_help = Builder::get_help(&build, subcommand.as_str()); extra_help.push_str(maybe_rules_help.unwrap_or_default().as_str()); } else if !(subcommand.as_str() == "clean" || subcommand.as_str() == "fmt") { extra_help.push_str( format!("Run `./x.py {} -h -v` to see a list of available paths.", subcommand) .as_str(), ); } println!("{}", opts.usage(subcommand_help)); if !extra_help.is_empty() { println!("{}", extra_help); } process::exit(exit_code); }; // Done specifying what options are possible, so do the getopts parsing let matches = opts.parse(args).unwrap_or_else(|e| { // Invalid argument/option format println!("\n{}\n", e); usage(1, &opts, false, &subcommand_help); }); // Extra sanity check to make sure we didn't hit this crazy corner case: // // ./x.py --frobulate clean build // ^-- option ^ ^- actual subcommand // \_ arg to option could be mistaken as subcommand let mut pass_sanity_check = true; match matches.free.get(0) { Some(check_subcommand) => { if check_subcommand != subcommand { pass_sanity_check = false; } } None => { pass_sanity_check = false; } } if !pass_sanity_check { println!("{}\n", subcommand_help); println!( "Sorry, I couldn't figure out which subcommand you were trying to specify.\n\ You may need to move some options to after the subcommand.\n" ); process::exit(1); } // Extra help text for some commands match subcommand.as_str() { "build" | "b" => { subcommand_help.push_str( "\n Arguments: This subcommand accepts a number of paths to directories to the crates and/or artifacts to compile. For example: ./x.py build library/core ./x.py build library/core library/proc_macro ./x.py build library/std --stage 1 If no arguments are passed then the complete artifacts for that stage are also compiled. ./x.py build ./x.py build --stage 1 For a quick build of a usable compiler, you can pass: ./x.py build --stage 1 library/test This will first build everything once (like `--stage 0` without further arguments would), and then use the compiler built in stage 0 to build library/test and its dependencies. Once this is done, build/$ARCH/stage1 contains a usable compiler.", ); } "check" | "c" => { subcommand_help.push_str( "\n Arguments: This subcommand accepts a number of paths to directories to the crates and/or artifacts to compile. For example: ./x.py check library/core ./x.py check library/core library/proc_macro If no arguments are passed then the complete artifacts are compiled: std, test, and rustc. Note also that since we use `cargo check`, by default this will automatically enable incremental compilation, so there's no need to pass it separately, though it won't hurt. We also completely ignore the stage passed, as there's no way to compile in non-stage 0 without actually building the compiler.", ); } "clippy" => { subcommand_help.push_str( "\n Arguments: This subcommand accepts a number of paths to directories to the crates and/or artifacts to run clippy against. For example: ./x.py clippy library/core ./x.py clippy library/core library/proc_macro", ); } "fix" => { subcommand_help.push_str( "\n Arguments: This subcommand accepts a number of paths to directories to the crates and/or artifacts to run `cargo fix` against. For example: ./x.py fix library/core ./x.py fix library/core library/proc_macro", ); } "fmt" => { subcommand_help.push_str( "\n Arguments: This subcommand optionally accepts a `--check` flag which succeeds if formatting is correct and fails if it is not. For example: ./x.py fmt ./x.py fmt --check", ); } "test" | "t" => { subcommand_help.push_str( "\n Arguments: This subcommand accepts a number of paths to test directories that should be compiled and run. For example: ./x.py test src/test/ui ./x.py test library/std --test-args hash_map ./x.py test library/std --stage 0 --no-doc ./x.py test src/test/ui --bless ./x.py test src/test/ui --compare-mode nll Note that `test src/test/* --stage N` does NOT depend on `build compiler/rustc --stage N`; just like `build library/std --stage N` it tests the compiler produced by the previous stage. Execute tool tests with a tool name argument: ./x.py test tidy If no arguments are passed then the complete artifacts for that stage are compiled and tested. ./x.py test ./x.py test --stage 1", ); } "doc" | "d" => { subcommand_help.push_str( "\n Arguments: This subcommand accepts a number of paths to directories of documentation to build. For example: ./x.py doc src/doc/book ./x.py doc src/doc/nomicon ./x.py doc src/doc/book library/std ./x.py doc library/std --open If no arguments are passed then everything is documented: ./x.py doc ./x.py doc --stage 1", ); } "run" | "r" => { subcommand_help.push_str( "\n Arguments: This subcommand accepts a number of paths to tools to build and run. For example: ./x.py run src/tools/expand-yaml-anchors At least a tool needs to be called.", ); } "setup" => { subcommand_help.push_str(&format!( "\n x.py setup creates a `config.toml` which changes the defaults for x.py itself. Arguments: This subcommand accepts a 'profile' to use for builds. For example: ./x.py setup library The profile is optional and you will be prompted interactively if it is not given. The following profiles are available: {}", Profile::all_for_help(" ").trim_end() )); } _ => {} }; // Get any optional paths which occur after the subcommand let mut paths = matches.free[1..].iter().map(|p| p.into()).collect::<Vec<PathBuf>>(); let cfg_file = env::var_os("BOOTSTRAP_CONFIG").map(PathBuf::from); let verbose = matches.opt_present("verbose"); // User passed in -h/--help? if matches.opt_present("help") { usage(0, &opts, verbose, &subcommand_help); } let cmd = match subcommand.as_str() { "build" | "b" => Subcommand::Build { paths }, "check" | "c" => { if matches.opt_present("all-targets") { eprintln!( "Warning: --all-targets is now on by default and does not need to be passed explicitly." ); } Subcommand::Check { paths } } "clippy" => Subcommand::Clippy { paths, fix: matches.opt_present("fix") }, "fix" => Subcommand::Fix { paths }, "test" | "t" => Subcommand::Test { paths, bless: matches.opt_present("bless"), force_rerun: matches.opt_present("force-rerun"), compare_mode: matches.opt_str("compare-mode"), pass: matches.opt_str("pass"), run: matches.opt_str("run"), test_args: matches.opt_strs("test-args"), rustc_args: matches.opt_strs("rustc-args"), fail_fast: !matches.opt_present("no-fail-fast"), rustfix_coverage: matches.opt_present("rustfix-coverage"), doc_tests: if matches.opt_present("doc") { DocTests::Only } else if matches.opt_present("no-doc") { DocTests::No } else { DocTests::Yes }, }, "bench" => Subcommand::Bench { paths, test_args: matches.opt_strs("test-args") }, "doc" | "d" => Subcommand::Doc { paths, open: matches.opt_present("open") }, "clean" => { if !paths.is_empty() { println!("\nclean does not take a path argument\n"); usage(1, &opts, verbose, &subcommand_help); } Subcommand::Clean { all: matches.opt_present("all") } } "fmt" => Subcommand::Format { check: matches.opt_present("check"), paths }, "dist" => Subcommand::Dist { paths }, "install" => Subcommand::Install { paths }, "run" | "r" => { if paths.is_empty() { println!("\nrun requires at least a path!\n"); usage(1, &opts, verbose, &subcommand_help); } Subcommand::Run { paths } } "setup" => { let profile = if paths.len() > 1 { println!("\nat most one profile can be passed to setup\n"); usage(1, &opts, verbose, &subcommand_help) } else if let Some(path) = paths.pop() { let profile_string = t!(path.into_os_string().into_string().map_err( |path| format!("{} is not a valid UTF8 string", path.to_string_lossy()) )); profile_string.parse().unwrap_or_else(|err| { eprintln!("error: {}", err); eprintln!("help: the available profiles are:"); eprint!("{}", Profile::all_for_help("- ")); std::process::exit(1); }) } else { t!(crate::setup::interactive_path()) }; Subcommand::Setup { profile } } _ => { usage(1, &opts, verbose, &subcommand_help); } }; if let Subcommand::Check { .. } = &cmd { if matches.opt_str("keep-stage").is_some() || matches.opt_str("keep-stage-std").is_some() { println!("--keep-stage not yet supported for x.py check"); process::exit(1); } } Flags { verbose: matches.opt_count("verbose"), stage: matches.opt_str("stage").map(|j| j.parse().expect("`stage` should be a number")), dry_run: matches.opt_present("dry-run"), on_fail: matches.opt_str("on-fail"), rustc_error_format: matches.opt_str("error-format"), json_output: matches.opt_present("json-output"), keep_stage: matches .opt_strs("keep-stage") .into_iter() .map(|j| j.parse().expect("`keep-stage` should be a number")) .collect(), keep_stage_std: matches .opt_strs("keep-stage-std") .into_iter() .map(|j| j.parse().expect("`keep-stage-std` should be a number")) .collect(), host: if matches.opt_present("host") { Some( split(&matches.opt_strs("host")) .into_iter() .map(|x| TargetSelection::from_user(&x)) .collect::<Vec<_>>(), ) } else { None }, target: if matches.opt_present("target") { Some( split(&matches.opt_strs("target")) .into_iter() .map(|x| TargetSelection::from_user(&x)) .collect::<Vec<_>>(), ) } else { None }, config: cfg_file, jobs: matches.opt_str("jobs").map(|j| j.parse().expect("`jobs` should be a number")), cmd, incremental: matches.opt_present("incremental"), exclude: split(&matches.opt_strs("exclude")) .into_iter() .map(|p| p.into()) .collect::<Vec<_>>(), include_default_paths: matches.opt_present("include-default-paths"), deny_warnings: parse_deny_warnings(&matches), llvm_skip_rebuild: matches.opt_str("llvm-skip-rebuild").map(|s| s.to_lowercase()).map( |s| s.parse::<bool>().expect("`llvm-skip-rebuild` should be either true or false"), ), color: matches .opt_get_default("color", Color::Auto) .expect("`color` should be `always`, `never`, or `auto`"), rust_profile_use: matches.opt_str("rust-profile-use"), rust_profile_generate: matches.opt_str("rust-profile-generate"), llvm_profile_use: matches.opt_str("llvm-profile-use"), llvm_profile_generate: matches.opt_present("llvm-profile-generate"), } } } impl Subcommand { pub fn test_args(&self) -> Vec<&str> { match *self { Subcommand::Test { ref test_args, .. } | Subcommand::Bench { ref test_args, .. } => { test_args.iter().flat_map(|s| s.split_whitespace()).collect() } _ => Vec::new(), } } pub fn rustc_args(&self) -> Vec<&str> { match *self { Subcommand::Test { ref rustc_args, .. } => { rustc_args.iter().flat_map(|s| s.split_whitespace()).collect() } _ => Vec::new(), } } pub fn fail_fast(&self) -> bool { match *self { Subcommand::Test { fail_fast, .. } => fail_fast, _ => false, } } pub fn doc_tests(&self) -> DocTests { match *self { Subcommand::Test { doc_tests, .. } => doc_tests, _ => DocTests::Yes, } } pub fn bless(&self) -> bool { match *self { Subcommand::Test { bless, .. } => bless, _ => false, } } pub fn force_rerun(&self) -> bool { match *self { Subcommand::Test { force_rerun, .. } => force_rerun, _ => false, } } pub fn rustfix_coverage(&self) -> bool { match *self { Subcommand::Test { rustfix_coverage, .. } => rustfix_coverage, _ => false, } } pub fn compare_mode(&self) -> Option<&str> { match *self { Subcommand::Test { ref compare_mode, .. } => compare_mode.as_ref().map(|s| &s[..]), _ => None, } } pub fn pass(&self) -> Option<&str> { match *self { Subcommand::Test { ref pass, .. } => pass.as_ref().map(|s| &s[..]), _ => None, } } pub fn run(&self) -> Option<&str> { match *self { Subcommand::Test { ref run, .. } => run.as_ref().map(|s| &s[..]), _ => None, } } pub fn open(&self) -> bool { match *self { Subcommand::Doc { open, .. } => open, _ => false, } } } fn split(s: &[String]) -> Vec<String> { s.iter().flat_map(|s| s.split(',')).filter(|s| !s.is_empty()).map(|s| s.to_string()).collect() } fn parse_deny_warnings(matches: &getopts::Matches) -> Option<bool> { match matches.opt_str("warnings").as_deref() { Some("deny") => Some(true), Some("warn") => Some(false), Some(value) => { eprintln!(r#"invalid value for --warnings: {:?}, expected "warn" or "deny""#, value,); process::exit(1); } None => None, } }
35.377475
112
0.507189
0984519334daf2b4f610ba3bc67733285c39b240
924
use std::fs; use std::path::PathBuf; use clap::{App, ArgMatches, SubCommand}; use mdbook::MDBook; use mdbook::errors::*; use get_book_dir; // Create clap subcommand arguments pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("clean") .about("Delete built book") .arg_from_usage( "-d, --dest-dir=[dest-dir] 'The directory of built book{n}(Defaults to ./book when \ omitted)'", ) } // Clean command implementation pub fn execute(args: &ArgMatches) -> ::mdbook::errors::Result<()> { let book_dir = get_book_dir(args); let book = MDBook::load(&book_dir)?; let dir_to_remove = match args.value_of("dest-dir") { Some(dest_dir) => PathBuf::from(dest_dir), None => book.root.join(&book.config.build.build_dir), }; fs::remove_dir_all(&dir_to_remove).chain_err(|| "Unable to remove the build directory")?; Ok(()) }
29.806452
96
0.62987
d9fa30c285b593fb43b9ef9a4277c0a7dc9ac17f
835
//! An example of drawing text. Writes to the user-provided target file. use std::path::Path; use std::env; use imageproc::drawing::draw_text_mut; use image::{Rgb, RgbImage}; use rusttype::{FontCollection, Scale}; fn main() { let arg = if env::args().count() == 2 { env::args().nth(1).unwrap() } else { panic!("Please enter a target file path") }; let path = Path::new(&arg); let mut image = RgbImage::new(200, 200); let font = Vec::from(include_bytes!("DejaVuSans.ttf") as &[u8]); let font = FontCollection::from_bytes(font).unwrap().into_font().unwrap(); let height = 12.4; let scale = Scale { x: height * 2.0, y: height }; draw_text_mut(&mut image, Rgb([0u8, 0u8, 255u8]), 0, 0, scale, &font, "Hello, world!"); let _ = image.save(path).unwrap(); }
27.833333
91
0.602395
ed3f36a1513f9cb270a3e34b915e2252426a7aab
28,956
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ config::ConsensusProposerType::{FixedProposer, MultipleOrderedProposers, RotatingProposer}, keys::{ConsensusKeyPair, NetworkKeyPairs}, seed_peers::{SeedPeersConfig, SeedPeersConfigHelpers}, trusted_peers::{ ConfigHelpers, ConsensusPeersConfig, ConsensusPrivateKey, NetworkPeersConfig, NetworkPrivateKeys, UpstreamPeersConfig, }, utils::{deserialize_whitelist, get_available_port, get_local_ip, serialize_whitelist}, }; use failure::prelude::*; use libra_crypto::ValidKey; use libra_tools::tempdir::TempPath; use libra_types::{ transaction::{SignedTransaction, Transaction, SCRIPT_HASH_LENGTH}, PeerId, }; use parity_multiaddr::Multiaddr; use prost::Message; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::{ collections::HashSet, convert::TryFrom, fmt, fs::File, io::{Read, Write}, path::{Path, PathBuf}, str::FromStr, string::ToString, time::Duration, }; use toml; #[cfg(test)] #[path = "unit_tests/config_test.rs"] mod config_test; // path is relative to this file location static CONFIG_TEMPLATE: &[u8] = include_bytes!("../data/configs/node.config.toml"); /// Config pulls in configuration information from the config file. /// This is used to set up the nodes and configure various parameters. /// The config file is broken up into sections for each module /// so that only that module can be passed around #[derive(Debug, Deserialize, Serialize)] #[cfg_attr(any(test, feature = "fuzzing"), derive(Clone))] pub struct NodeConfig { //TODO Add configuration for multiple chain's in a future diff #[serde(default)] pub base: BaseConfig, #[serde(default)] pub metrics: MetricsConfig, #[serde(default)] pub execution: ExecutionConfig, #[serde(default)] pub admission_control: AdmissionControlConfig, #[serde(default)] pub debug_interface: DebugInterfaceConfig, #[serde(default)] pub storage: StorageConfig, #[serde(default)] pub networks: Vec<NetworkConfig>, #[serde(default)] pub consensus: ConsensusConfig, #[serde(default)] pub mempool: MempoolConfig, #[serde(default)] pub state_sync: StateSyncConfig, #[serde(default)] pub log_collector: LoggerConfig, #[serde(default)] pub vm_config: VMConfig, #[serde(default)] pub secret_service: SecretServiceConfig, } #[derive(Debug, Deserialize, Serialize)] #[serde(default)] pub struct BaseConfig { pub data_dir_path: PathBuf, #[serde(skip)] temp_data_dir: Option<TempPath>, // Number of retries per chunk download pub node_sync_retries: usize, // Buffer size for sync_channel used for node syncing (number of elements that it can // hold before it blocks on sends) pub node_sync_channel_buffer_size: u64, // chan_size of slog async drain for node logging. pub node_async_log_chan_size: usize, } impl Default for BaseConfig { fn default() -> BaseConfig { BaseConfig { data_dir_path: PathBuf::from("."), temp_data_dir: None, node_sync_retries: 7, node_sync_channel_buffer_size: 10, node_async_log_chan_size: 256, } } } #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum RoleType { Validator, FullNode, } impl<T> std::convert::From<T> for RoleType where T: AsRef<str>, { fn from(t: T) -> RoleType { match t.as_ref() { "validator" => RoleType::Validator, "full_node" => RoleType::FullNode, _ => unimplemented!("Invalid node role: {}", t.as_ref()), } } } impl fmt::Display for RoleType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { RoleType::Validator => write!(f, "validator"), RoleType::FullNode => write!(f, "full_node"), } } } impl BaseConfig { /// Constructs a new BaseConfig with an empty temp directory pub fn new( data_dir_path: PathBuf, node_sync_retries: usize, node_sync_channel_buffer_size: u64, node_async_log_chan_size: usize, ) -> Self { BaseConfig { data_dir_path, temp_data_dir: None, node_sync_retries, node_sync_channel_buffer_size, node_async_log_chan_size, } } } #[cfg(any(test, feature = "fuzzing"))] impl Clone for BaseConfig { fn clone(&self) -> Self { Self { data_dir_path: self.data_dir_path.clone(), temp_data_dir: None, node_sync_retries: self.node_sync_retries, node_sync_channel_buffer_size: self.node_sync_channel_buffer_size, node_async_log_chan_size: self.node_async_log_chan_size, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct MetricsConfig { pub dir: PathBuf, pub collection_interval_ms: u64, pub push_server_addr: String, } impl Default for MetricsConfig { fn default() -> MetricsConfig { MetricsConfig { dir: PathBuf::from("metrics"), collection_interval_ms: 1000, push_server_addr: "".to_string(), } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct ExecutionConfig { pub address: String, pub port: u16, // directive to load the testnet genesis block or the default genesis block. // There are semantic differences between the 2 genesis related to minting and // account creation pub testnet_genesis: bool, pub genesis_file_location: String, } impl Default for ExecutionConfig { fn default() -> ExecutionConfig { ExecutionConfig { address: "localhost".to_string(), port: 6183, testnet_genesis: false, genesis_file_location: "genesis.blob".to_string(), } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct LoggerConfig { pub is_async: bool, pub chan_size: Option<usize>, } impl Default for LoggerConfig { fn default() -> LoggerConfig { LoggerConfig { is_async: true, chan_size: None, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct SecretServiceConfig { pub address: String, pub secret_service_port: u16, } impl Default for SecretServiceConfig { fn default() -> SecretServiceConfig { SecretServiceConfig { address: "localhost".to_string(), secret_service_port: 6185, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct AdmissionControlConfig { pub address: String, pub admission_control_service_port: u16, pub need_to_check_mempool_before_validation: bool, pub max_concurrent_inbound_syncs: usize, pub upstream_proxy_timeout: Duration, } impl Default for AdmissionControlConfig { fn default() -> AdmissionControlConfig { AdmissionControlConfig { address: "0.0.0.0".to_string(), admission_control_service_port: 8000, need_to_check_mempool_before_validation: false, max_concurrent_inbound_syncs: 100, upstream_proxy_timeout: Duration::from_secs(1), } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct DebugInterfaceConfig { pub admission_control_node_debug_port: u16, pub secret_service_node_debug_port: u16, pub storage_node_debug_port: u16, // This has similar use to the core-node-debug-server itself pub metrics_server_port: u16, pub public_metrics_server_port: u16, pub address: String, } impl Default for DebugInterfaceConfig { fn default() -> DebugInterfaceConfig { DebugInterfaceConfig { admission_control_node_debug_port: 6191, storage_node_debug_port: 6194, secret_service_node_debug_port: 6195, metrics_server_port: 9101, public_metrics_server_port: 9102, address: "localhost".to_string(), } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct StorageConfig { pub address: String, pub port: u16, pub dir: PathBuf, pub grpc_max_receive_len: Option<i32>, } impl Default for StorageConfig { fn default() -> StorageConfig { StorageConfig { address: "localhost".to_string(), port: 6184, dir: PathBuf::from("libradb/db"), grpc_max_receive_len: Some(100_000_000), } } } #[cfg_attr(any(test, feature = "fuzzing"), derive(Clone))] #[derive(Debug, Deserialize, Serialize)] #[serde(default)] pub struct NetworkConfig { pub peer_id: String, // TODO: Add support for multiple listen/advertised addresses in config. // The address that this node is listening on for new connections. pub listen_address: Multiaddr, // The address that this node advertises to other nodes for the discovery protocol. pub advertised_address: Multiaddr, pub discovery_interval_ms: u64, pub connectivity_check_interval_ms: u64, // Flag to toggle if Noise is used for encryption and authentication. pub enable_encryption_and_authentication: bool, // If the network is permissioned, only trusted peers are allowed to connect. Otherwise, any // node can connect. If this flag is set to true, the `enable_encryption_and_authentication` // must also be set to true. pub is_permissioned: bool, // The role of the node in the network. One of: {"validator", "full_node"}. pub role: String, // network_keypairs contains the node's network keypairs. // it is filled later on from network_keypairs_file. #[serde(skip)] pub network_keypairs: NetworkKeyPairs, pub network_keypairs_file: PathBuf, // network peers are the nodes allowed to connect when the network is started in permissioned // mode. #[serde(skip)] pub network_peers: NetworkPeersConfig, pub network_peers_file: PathBuf, // seed_peers act as seed nodes for the discovery protocol. #[serde(skip)] pub seed_peers: SeedPeersConfig, pub seed_peers_file: PathBuf, } impl Default for NetworkConfig { fn default() -> NetworkConfig { NetworkConfig { peer_id: "".to_string(), role: "validator".to_string(), listen_address: "/ip4/0.0.0.0/tcp/6180".parse::<Multiaddr>().unwrap(), advertised_address: "/ip4/127.0.0.1/tcp/6180".parse::<Multiaddr>().unwrap(), discovery_interval_ms: 1000, connectivity_check_interval_ms: 5000, enable_encryption_and_authentication: true, is_permissioned: true, network_keypairs_file: PathBuf::from("network_keypairs.config.toml"), network_keypairs: NetworkKeyPairs::default(), network_peers_file: PathBuf::from("network_peers.config.toml"), network_peers: NetworkPeersConfig::default(), seed_peers_file: PathBuf::from("seed_peers.config.toml"), seed_peers: SeedPeersConfig::default(), } } } impl NetworkConfig { pub fn load<P: AsRef<Path>>(&mut self, path: P) -> Result<()> { if !self.network_peers_file.as_os_str().is_empty() { self.network_peers = NetworkPeersConfig::load_config( path.as_ref().with_file_name(&self.network_peers_file), ); } if !self.network_keypairs_file.as_os_str().is_empty() { self.network_keypairs = NetworkKeyPairs::load_config( path.as_ref().with_file_name(&self.network_keypairs_file), ); } if !self.seed_peers_file.as_os_str().is_empty() { self.seed_peers = SeedPeersConfig::load_config(path.as_ref().with_file_name(&self.seed_peers_file)); } if self.advertised_address.to_string().is_empty() { self.advertised_address = get_local_ip().ok_or_else(|| ::failure::err_msg("No local IP"))?; } if self.listen_address.to_string().is_empty() { self.listen_address = get_local_ip().ok_or_else(|| ::failure::err_msg("No local IP"))?; } // If PeerId is not set, it is derived from NetworkIdentityKey. if self.peer_id == "" { self.peer_id = PeerId::try_from( self.network_keypairs .get_network_identity_public() .to_bytes(), ) .unwrap() .to_string(); } Ok(()) } } #[cfg_attr(any(test, feature = "fuzzing"), derive(Clone))] #[derive(Debug, Deserialize, Serialize)] #[serde(default)] pub struct ConsensusConfig { pub max_block_size: u64, pub proposer_type: String, pub contiguous_rounds: u32, pub max_pruned_blocks_in_mem: Option<u64>, pub pacemaker_initial_timeout_ms: Option<u64>, // consensus_keypair contains the node's consensus keypair. // it is filled later on from consensus_keypair_file. #[serde(skip)] pub consensus_keypair: ConsensusKeyPair, pub consensus_keypair_file: PathBuf, #[serde(skip)] pub consensus_peers: ConsensusPeersConfig, pub consensus_peers_file: PathBuf, } impl Default for ConsensusConfig { fn default() -> ConsensusConfig { ConsensusConfig { max_block_size: 100, proposer_type: "multiple_ordered_proposers".to_string(), contiguous_rounds: 2, max_pruned_blocks_in_mem: None, pacemaker_initial_timeout_ms: None, consensus_keypair: ConsensusKeyPair::default(), consensus_keypair_file: PathBuf::from("consensus_keypair.config.toml"), consensus_peers: ConsensusPeersConfig::default(), consensus_peers_file: PathBuf::from("consensus_peers.config.toml"), } } } #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum ConsensusProposerType { // Choose the smallest PeerId as the proposer FixedProposer, // Round robin rotation of proposers RotatingProposer, // Multiple ordered proposers per round (primary, secondary, etc.) MultipleOrderedProposers, } impl ConsensusConfig { pub fn load<P: AsRef<Path>>(&mut self, path: P) -> Result<()> { if !self.consensus_keypair_file.as_os_str().is_empty() { self.consensus_keypair = ConsensusKeyPair::load_config( path.as_ref().with_file_name(&self.consensus_keypair_file), ); } if !self.consensus_peers_file.as_os_str().is_empty() { self.consensus_peers = ConsensusPeersConfig::load_config( path.as_ref().with_file_name(&self.consensus_peers_file), ); } Ok(()) } pub fn get_proposer_type(&self) -> ConsensusProposerType { match self.proposer_type.as_str() { "fixed_proposer" => FixedProposer, "rotating_proposer" => RotatingProposer, "multiple_ordered_proposers" => MultipleOrderedProposers, &_ => unimplemented!("Invalid proposer type: {}", self.proposer_type), } } pub fn contiguous_rounds(&self) -> u32 { self.contiguous_rounds } pub fn max_block_size(&self) -> u64 { self.max_block_size } pub fn max_pruned_blocks_in_mem(&self) -> &Option<u64> { &self.max_pruned_blocks_in_mem } pub fn pacemaker_initial_timeout_ms(&self) -> &Option<u64> { &self.pacemaker_initial_timeout_ms } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct MempoolConfig { pub broadcast_transactions: bool, pub shared_mempool_tick_interval_ms: u64, pub shared_mempool_batch_size: usize, pub shared_mempool_max_concurrent_inbound_syncs: usize, pub capacity: usize, // max number of transactions per user in Mempool pub capacity_per_user: usize, pub system_transaction_timeout_secs: u64, pub system_transaction_gc_interval_ms: u64, pub mempool_service_port: u16, pub address: String, } impl Default for MempoolConfig { fn default() -> MempoolConfig { MempoolConfig { broadcast_transactions: true, shared_mempool_tick_interval_ms: 50, shared_mempool_batch_size: 100, shared_mempool_max_concurrent_inbound_syncs: 100, capacity: 1_000_000, capacity_per_user: 100, system_transaction_timeout_secs: 86400, address: "localhost".to_string(), mempool_service_port: 6182, system_transaction_gc_interval_ms: 180_000, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct StateSyncConfig { // Size of chunk to request for state synchronization pub chunk_limit: u64, // interval used for checking state synchronization progress pub tick_interval_ms: u64, // default timeout used for long polling to remote peer pub long_poll_timeout_ms: u64, // valid maximum chunk limit for sanity check pub max_chunk_limit: u64, // valid maximum timeout limit for sanity check pub max_timeout_ms: u64, // List of peers to use as upstream in state sync protocols. #[serde(flatten)] pub upstream_peers: UpstreamPeersConfig, } impl Default for StateSyncConfig { fn default() -> Self { Self { chunk_limit: 1000, tick_interval_ms: 100, long_poll_timeout_ms: 30000, max_chunk_limit: 1000, max_timeout_ms: 120_000, upstream_peers: UpstreamPeersConfig::default(), } } } impl NodeConfig { /// Reads the config file and returns the configuration object in addition to doing some /// post-processing of the config /// Paths used in the config are either absolute or relative to the config location pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> { let mut config = Self::load_config(&path); let mut validator_count = 0; for network in &mut config.networks { // We use provided peer id for validator role. Otherwise peer id is generated using // network identity key. if network.role == "validator" { assert_eq!( validator_count, 0, "At most 1 network config should be for a validator" ); network.load(path.as_ref())?; validator_count += 1; } else { network.load(path.as_ref())?; } } config.consensus.load(path.as_ref())?; Ok(config) } /// Returns true if the node config is for a validator. Otherwise returns false. pub fn is_validator(&self) -> bool { self.networks .iter() .any(|network| RoleType::Validator == (&network.role).into()) } /// Returns true if the node config is for a validator. Otherwise returns false. pub fn get_role(&self) -> RoleType { if self.is_validator() { RoleType::Validator } else { RoleType::FullNode } } /// Returns the validator network config for this node. pub fn get_validator_network_config(&self) -> Option<&NetworkConfig> { self.networks .iter() .filter(|network| RoleType::Validator == (&network.role).into()) .last() } pub fn get_genesis_transaction_file(&self) -> PathBuf { let path = PathBuf::from(self.execution.genesis_file_location.clone()); if path.is_relative() { self.base.data_dir_path.join(path) } else { path } } pub fn get_genesis_transaction(&self) -> Result<Transaction> { let file_path = self.get_genesis_transaction_file(); let mut file: File = File::open(&file_path).unwrap_or_else(|err| { panic!( "Failed to open file: {:?}; error: {:?}", file_path.clone(), err ); }); let mut buffer = vec![]; file.read_to_end(&mut buffer)?; // TODO: update to use `Transaction::WriteSet` variant when ready. Ok(Transaction::UserTransaction(SignedTransaction::try_from( libra_types::proto::types::SignedTransaction::decode(&buffer)?, )?)) } pub fn get_storage_dir(&self) -> PathBuf { let path = self.storage.dir.clone(); if path.is_relative() { self.base.data_dir_path.join(path) } else { path } } pub fn get_metrics_dir(&self) -> Option<PathBuf> { let path = self.metrics.dir.as_path(); if path.as_os_str().is_empty() { None } else if path.is_relative() { Some(self.base.data_dir_path.join(path)) } else { Some(path.to_owned()) } } /// Returns true if network_config is for an upstream network pub fn is_upstream_network(&self, network_config: &NetworkConfig) -> bool { self.state_sync .upstream_peers .upstream_peers .iter() .any(|peer_id| network_config.network_peers.peers.contains_key(peer_id)) } pub fn get_upstream_peer_ids(&self) -> Vec<PeerId> { self.state_sync .upstream_peers .upstream_peers .iter() .map(|peer_id_str| { (PeerId::from_str(peer_id_str).unwrap_or_else(|_| { panic!("Failed to parse peer_id from string: {}", peer_id_str) })) }) .collect() } } pub struct NodeConfigHelpers {} impl NodeConfigHelpers { /// Returns a simple test config for single node. It does not have correct network_peers_file, /// consensus_peers_file, network_keypairs_file, consensus_keypair_file, and seed_peers_file /// set. It is expected that the callee will provide these. pub fn get_single_node_test_config(random_ports: bool) -> NodeConfig { Self::get_single_node_test_config_publish_options(random_ports, None) } /// Returns a simple test config for single node. It does not have correct network_peers_file, /// consensus_peers_file, network_keypairs_file, consensus_keypair_file, and seed_peers_file /// set. It is expected that the callee will provide these. /// `publishing_options` is either one of either `Open` or `CustomScripts` only. pub fn get_single_node_test_config_publish_options( random_ports: bool, publishing_options: Option<VMPublishingOption>, ) -> NodeConfig { let config_string = String::from_utf8_lossy(CONFIG_TEMPLATE); let mut config = NodeConfig::parse(&config_string).expect("Error parsing single node test config"); // Create temporary directory for persisting configs. let dir = TempPath::new(); dir.create_as_dir().expect("error creating tempdir"); config.base.data_dir_path = dir.path().to_owned(); config.base.temp_data_dir = Some(dir); if random_ports { NodeConfigHelpers::randomize_config_ports(&mut config); } if let Some(vm_publishing_option) = publishing_options { config.vm_config.publishing_options = vm_publishing_option; } let (mut private_keys, test_consensus_peers, test_network_peers) = ConfigHelpers::gen_validator_nodes(1, None); let peer_id = *private_keys.keys().nth(0).unwrap(); let ( ConsensusPrivateKey { consensus_private_key, }, NetworkPrivateKeys { network_signing_private_key, network_identity_private_key, }, ) = private_keys.remove_entry(&peer_id).unwrap().1; config.consensus.consensus_keypair = ConsensusKeyPair::load(Some(consensus_private_key)); config.consensus.consensus_peers = test_consensus_peers; // Setup node's peer id. let mut network = config.networks.get_mut(0).unwrap(); network.peer_id = peer_id.to_string(); network.network_keypairs = NetworkKeyPairs::load(network_signing_private_key, network_identity_private_key); let seed_peers_config = SeedPeersConfigHelpers::get_test_config(&test_network_peers, None); network.listen_address = seed_peers_config .seed_peers .get(&peer_id.to_string()) .unwrap() .get(0) .unwrap() .clone(); network.advertised_address = network.listen_address.clone(); network.seed_peers = seed_peers_config; network.network_peers = test_network_peers; config } pub fn randomize_config_ports(config: &mut NodeConfig) { config.admission_control.admission_control_service_port = get_available_port(); config.debug_interface.admission_control_node_debug_port = get_available_port(); config.debug_interface.metrics_server_port = get_available_port(); config.debug_interface.public_metrics_server_port = get_available_port(); config.debug_interface.secret_service_node_debug_port = get_available_port(); config.debug_interface.storage_node_debug_port = get_available_port(); config.execution.port = get_available_port(); config.mempool.mempool_service_port = get_available_port(); config.secret_service.secret_service_port = get_available_port(); config.storage.port = get_available_port(); } } /// Holds the VM configuration, currently this is only the publishing options for scripts and /// modules, but in the future this may need to be expanded to hold more information. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct VMConfig { pub publishing_options: VMPublishingOption, } impl Default for VMConfig { fn default() -> VMConfig { VMConfig { publishing_options: VMPublishingOption::Open, } } } /// Defines and holds the publishing policies for the VM. There are three possible configurations: /// 1. No module publishing, only whitelisted scripts are allowed. /// 2. No module publishing, custom scripts are allowed. /// 3. Both module publishing and custom scripts are allowed. /// We represent these as an enum instead of a struct since whitelisting and module/script /// publishing are mutually exclusive options. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(tag = "type", content = "whitelist")] pub enum VMPublishingOption { /// Only allow scripts on a whitelist to be run #[serde(deserialize_with = "deserialize_whitelist")] #[serde(serialize_with = "serialize_whitelist")] Locked(HashSet<[u8; SCRIPT_HASH_LENGTH]>), /// Allow custom scripts, but _not_ custom module publishing CustomScripts, /// Allow both custom scripts and custom module publishing Open, } impl VMPublishingOption { pub fn is_open(&self) -> bool { match self { VMPublishingOption::Open => true, _ => false, } } pub fn get_whitelist_set(&self) -> Option<&HashSet<[u8; SCRIPT_HASH_LENGTH]>> { match self { VMPublishingOption::Locked(whitelist) => Some(&whitelist), _ => None, } } } impl VMConfig { /// Creates a new `VMConfig` where the whitelist is empty. This should only be used for testing. #[allow(non_snake_case)] #[doc(hidden)] #[cfg(any(test, feature = "fuzzing"))] pub fn empty_whitelist_FOR_TESTING() -> Self { VMConfig { publishing_options: VMPublishingOption::Locked(HashSet::new()), } } } pub trait PersistableConfig: Serialize + DeserializeOwned { // TODO: Return Result<Self> instead of panic. fn load_config<P: AsRef<Path>>(path: P) -> Self { let path = path.as_ref(); let mut file = File::open(path).unwrap_or_else(|_| panic!("Cannot open config file {:?}", path)); let mut contents = String::new(); file.read_to_string(&mut contents) .unwrap_or_else(|_| panic!("Error reading config file {:?}", path)); Self::parse(&contents).expect("Unable to parse config") } fn save_config<P: AsRef<Path>>(&self, output_file: P) { let contents = toml::to_vec(&self).expect("Error serializing"); let mut file = File::create(output_file).expect("Error opening file"); file.write_all(&contents).expect("Error writing file"); } fn parse(serialized: &str) -> Result<Self> { Ok(toml::from_str(&serialized)?) } } impl<T: ?Sized> PersistableConfig for T where T: Serialize + DeserializeOwned {}
34.594982
100
0.647569
7622949950c534759ca05d5169e1f908f44c1762
30,598
//! Functions and filters for the sampling of pixels. // See http://cs.brown.edu/courses/cs123/lectures/08_Image_Processing_IV.pdf // for some of the theory behind image scaling and convolution use std::f32; use num_traits::{NumCast, ToPrimitive, Zero}; use crate::image::GenericImageView; use crate::traits::{Enlargeable, Pixel, Primitive}; use crate::utils::clamp; use crate::{ImageBuffer, Rgba32FImage}; /// Available Sampling Filters. /// /// ## Examples /// /// To test the different sampling filters on a real example, you can find two /// examples called /// [`scaledown`](https://github.com/image-rs/image/tree/master/examples/scaledown) /// and /// [`scaleup`](https://github.com/image-rs/image/tree/master/examples/scaleup) /// in the `examples` directory of the crate source code. /// /// Here is a 3.58 MiB /// [test image](https://github.com/image-rs/image/blob/master/examples/scaledown/test.jpg) /// that has been scaled down to 300x225 px: /// /// <!-- NOTE: To test new test images locally, replace the GitHub path with `../../../docs/` --> /// <div style="display: flex; flex-wrap: wrap; align-items: flex-start;"> /// <div style="margin: 0 8px 8px 0;"> /// <img src="https://raw.githubusercontent.com/image-rs/image/master/examples/scaledown/scaledown-test-near.png" title="Nearest"><br> /// Nearest Neighbor /// </div> /// <div style="margin: 0 8px 8px 0;"> /// <img src="https://raw.githubusercontent.com/image-rs/image/master/examples/scaledown/scaledown-test-tri.png" title="Triangle"><br> /// Linear: Triangle /// </div> /// <div style="margin: 0 8px 8px 0;"> /// <img src="https://raw.githubusercontent.com/image-rs/image/master/examples/scaledown/scaledown-test-cmr.png" title="CatmullRom"><br> /// Cubic: Catmull-Rom /// </div> /// <div style="margin: 0 8px 8px 0;"> /// <img src="https://raw.githubusercontent.com/image-rs/image/master/examples/scaledown/scaledown-test-gauss.png" title="Gaussian"><br> /// Gaussian /// </div> /// <div style="margin: 0 8px 8px 0;"> /// <img src="https://raw.githubusercontent.com/image-rs/image/master/examples/scaledown/scaledown-test-lcz2.png" title="Lanczos3"><br> /// Lanczos with window 3 /// </div> /// </div> /// /// ## Speed /// /// Time required to create each of the examples above, tested on an Intel /// i7-4770 CPU with Rust 1.37 in release mode: /// /// <table style="width: auto;"> /// <tr> /// <th>Nearest</th> /// <td>31 ms</td> /// </tr> /// <tr> /// <th>Triangle</th> /// <td>414 ms</td> /// </tr> /// <tr> /// <th>CatmullRom</th> /// <td>817 ms</td> /// </tr> /// <tr> /// <th>Gaussian</th> /// <td>1180 ms</td> /// </tr> /// <tr> /// <th>Lanczos3</th> /// <td>1170 ms</td> /// </tr> /// </table> #[derive(Clone, Copy, Debug, PartialEq)] pub enum FilterType { /// Nearest Neighbor Nearest, /// Linear Filter Triangle, /// Cubic Filter CatmullRom, /// Gaussian Filter Gaussian, /// Lanczos with window 3 Lanczos3, } /// A Representation of a separable filter. pub(crate) struct Filter<'a> { /// The filter's filter function. pub(crate) kernel: Box<dyn Fn(f32) -> f32 + 'a>, /// The window on which this filter operates. pub(crate) support: f32, } struct FloatNearest(f32); // to_i64, to_u64, and to_f64 implicitly affect all other lower conversions. // Note that to_f64 by default calls to_i64 and thus needs to be overridden. impl ToPrimitive for FloatNearest { // to_{i,u}64 is required, to_{i,u}{8,16} are usefull. // If a usecase for full 32 bits is found its trivial to add fn to_i8(&self) -> Option<i8> { self.0.round().to_i8() } fn to_i16(&self) -> Option<i16> { self.0.round().to_i16() } fn to_i64(&self) -> Option<i64> { self.0.round().to_i64() } fn to_u8(&self) -> Option<u8> { self.0.round().to_u8() } fn to_u16(&self) -> Option<u16> { self.0.round().to_u16() } fn to_u64(&self) -> Option<u64> { self.0.round().to_u64() } fn to_f64(&self) -> Option<f64> { self.0.to_f64() } } // sinc function: the ideal sampling filter. fn sinc(t: f32) -> f32 { let a = t * f32::consts::PI; if t == 0.0 { 1.0 } else { a.sin() / a } } // lanczos kernel function. A windowed sinc function. fn lanczos(x: f32, t: f32) -> f32 { if x.abs() < t { sinc(x) * sinc(x / t) } else { 0.0 } } // Calculate a splice based on the b and c parameters. // from authors Mitchell and Netravali. fn bc_cubic_spline(x: f32, b: f32, c: f32) -> f32 { let a = x.abs(); let k = if a < 1.0 { (12.0 - 9.0 * b - 6.0 * c) * a.powi(3) + (-18.0 + 12.0 * b + 6.0 * c) * a.powi(2) + (6.0 - 2.0 * b) } else if a < 2.0 { (-b - 6.0 * c) * a.powi(3) + (6.0 * b + 30.0 * c) * a.powi(2) + (-12.0 * b - 48.0 * c) * a + (8.0 * b + 24.0 * c) } else { 0.0 }; k / 6.0 } /// The Gaussian Function. /// ```r``` is the standard deviation. pub(crate) fn gaussian(x: f32, r: f32) -> f32 { ((2.0 * f32::consts::PI).sqrt() * r).recip() * (-x.powi(2) / (2.0 * r.powi(2))).exp() } /// Calculate the lanczos kernel with a window of 3 pub(crate) fn lanczos3_kernel(x: f32) -> f32 { lanczos(x, 3.0) } /// Calculate the gaussian function with a /// standard deviation of 0.5 pub(crate) fn gaussian_kernel(x: f32) -> f32 { gaussian(x, 0.5) } /// Calculate the Catmull-Rom cubic spline. /// Also known as a form of `BiCubic` sampling in two dimensions. pub(crate) fn catmullrom_kernel(x: f32) -> f32 { bc_cubic_spline(x, 0.0, 0.5) } /// Calculate the triangle function. /// Also known as `BiLinear` sampling in two dimensions. pub(crate) fn triangle_kernel(x: f32) -> f32 { if x.abs() < 1.0 { 1.0 - x.abs() } else { 0.0 } } /// Calculate the box kernel. /// Only pixels inside the box should be considered, and those /// contribute equally. So this method simply returns 1. pub(crate) fn box_kernel(_x: f32) -> f32 { 1.0 } // Sample the rows of the supplied image using the provided filter. // The height of the image remains unchanged. // ```new_width``` is the desired width of the new image // ```filter``` is the filter to use for sampling. // ```image``` is not necessarily Rgba and the order of channels is passed through. fn horizontal_sample<P, S>( image: &Rgba32FImage, new_width: u32, filter: &mut Filter, ) -> ImageBuffer<P, Vec<S>> where P: Pixel<Subpixel = S> + 'static, S: Primitive + 'static, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(new_width, height); let mut ws = Vec::new(); let max: f32 = NumCast::from(S::DEFAULT_MAX_VALUE).unwrap(); let min: f32 = NumCast::from(S::DEFAULT_MIN_VALUE).unwrap(); let ratio = width as f32 / new_width as f32; let sratio = if ratio < 1.0 { 1.0 } else { ratio }; let src_support = filter.support * sratio; for outx in 0..new_width { // Find the point in the input image corresponding to the centre // of the current pixel in the output image. let inputx = (outx as f32 + 0.5) * ratio; // Left and right are slice bounds for the input pixels relevant // to the output pixel we are calculating. Pixel x is relevant // if and only if (x >= left) && (x < right). // Invariant: 0 <= left < right <= width let left = (inputx - src_support).floor() as i64; let left = clamp(left, 0, <i64 as From<_>>::from(width) - 1) as u32; let right = (inputx + src_support).ceil() as i64; let right = clamp( right, <i64 as From<_>>::from(left) + 1, <i64 as From<_>>::from(width), ) as u32; // Go back to left boundary of pixel, to properly compare with i // below, as the kernel treats the centre of a pixel as 0. let inputx = inputx - 0.5; ws.clear(); let mut sum = 0.0; for i in left..right { let w = (filter.kernel)((i as f32 - inputx) / sratio); ws.push(w); sum += w; } ws.iter_mut().for_each(|w| *w /= sum); for y in 0..height { let mut t = (0.0, 0.0, 0.0, 0.0); for (i, w) in ws.iter().enumerate() { let p = image.get_pixel(left + i as u32, y); #[allow(deprecated)] let vec = p.channels4(); t.0 += vec.0 * w; t.1 += vec.1 * w; t.2 += vec.2 * w; t.3 += vec.3 * w; } #[allow(deprecated)] let t = Pixel::from_channels( NumCast::from(FloatNearest(clamp(t.0, min, max))).unwrap(), NumCast::from(FloatNearest(clamp(t.1, min, max))).unwrap(), NumCast::from(FloatNearest(clamp(t.2, min, max))).unwrap(), NumCast::from(FloatNearest(clamp(t.3, min, max))).unwrap(), ); out.put_pixel(outx, y, t); } } out } // Sample the columns of the supplied image using the provided filter. // The width of the image remains unchanged. // ```new_height``` is the desired height of the new image // ```filter``` is the filter to use for sampling. // The return value is not necessarily Rgba, the underlying order of channels in ```image``` is // preserved. fn vertical_sample<I, P, S>(image: &I, new_height: u32, filter: &mut Filter) -> Rgba32FImage where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S> + 'static, S: Primitive + 'static, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, new_height); let mut ws = Vec::new(); let ratio = height as f32 / new_height as f32; let sratio = if ratio < 1.0 { 1.0 } else { ratio }; let src_support = filter.support * sratio; for outy in 0..new_height { // For an explanation of this algorithm, see the comments // in horizontal_sample. let inputy = (outy as f32 + 0.5) * ratio; let left = (inputy - src_support).floor() as i64; let left = clamp(left, 0, <i64 as From<_>>::from(height) - 1) as u32; let right = (inputy + src_support).ceil() as i64; let right = clamp( right, <i64 as From<_>>::from(left) + 1, <i64 as From<_>>::from(height), ) as u32; let inputy = inputy - 0.5; ws.clear(); let mut sum = 0.0; for i in left..right { let w = (filter.kernel)((i as f32 - inputy) / sratio); ws.push(w); sum += w; } ws.iter_mut().for_each(|w| *w /= sum); for x in 0..width { let mut t = (0.0, 0.0, 0.0, 0.0); for (i, w) in ws.iter().enumerate() { let p = image.get_pixel(x, left + i as u32); #[allow(deprecated)] let (k1, k2, k3, k4) = p.channels4(); let vec: (f32, f32, f32, f32) = ( NumCast::from(k1).unwrap(), NumCast::from(k2).unwrap(), NumCast::from(k3).unwrap(), NumCast::from(k4).unwrap(), ); t.0 += vec.0 * w; t.1 += vec.1 * w; t.2 += vec.2 * w; t.3 += vec.3 * w; } #[allow(deprecated)] // This is not necessarily Rgba. let t = Pixel::from_channels(t.0, t.1, t.2, t.3); out.put_pixel(x, outy, t); } } out } /// Local struct for keeping track of pixel sums for fast thumbnail averaging struct ThumbnailSum<S: Primitive + Enlargeable>(S::Larger, S::Larger, S::Larger, S::Larger); impl<S: Primitive + Enlargeable> ThumbnailSum<S> { fn zeroed() -> Self { ThumbnailSum( S::Larger::zero(), S::Larger::zero(), S::Larger::zero(), S::Larger::zero(), ) } fn sample_val(val: S) -> S::Larger { <S::Larger as NumCast>::from(val).unwrap() } fn add_pixel<P: Pixel<Subpixel = S>>(&mut self, pixel: P) { #[allow(deprecated)] let pixel = pixel.channels4(); self.0 += Self::sample_val(pixel.0); self.1 += Self::sample_val(pixel.1); self.2 += Self::sample_val(pixel.2); self.3 += Self::sample_val(pixel.3); } } /// Resize the supplied image to the specific dimensions. /// /// For downscaling, this method uses a fast integer algorithm where each source pixel contributes /// to exactly one target pixel. May give aliasing artifacts if new size is close to old size. /// /// In case the current width is smaller than the new width or similar for the height, another /// strategy is used instead. For each pixel in the output, a rectangular region of the input is /// determined, just as previously. But when no input pixel is part of this region, the nearest /// pixels are interpolated instead. /// /// For speed reasons, all interpolation is performed linearly over the colour values. It will not /// take the pixel colour spaces into account. pub fn thumbnail<I, P, S>(image: &I, new_width: u32, new_height: u32) -> ImageBuffer<P, Vec<S>> where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S> + 'static, S: Primitive + Enlargeable + 'static, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(new_width, new_height); let x_ratio = width as f32 / new_width as f32; let y_ratio = height as f32 / new_height as f32; for outy in 0..new_height { let bottomf = outy as f32 * y_ratio; let topf = bottomf + y_ratio; let bottom = clamp(bottomf.ceil() as u32, 0, height - 1); let top = clamp(topf.ceil() as u32, bottom, height); for outx in 0..new_width { let leftf = outx as f32 * x_ratio; let rightf = leftf + x_ratio; let left = clamp(leftf.ceil() as u32, 0, width - 1); let right = clamp(rightf.ceil() as u32, left, width); let avg = if bottom != top && left != right { thumbnail_sample_block(image, left, right, bottom, top) } else if bottom != top { // && left == right // In the first column we have left == 0 and right > ceil(y_scale) > 0 so this // assertion can never trigger. debug_assert!( left > 0 && right > 0, "First output column must have corresponding pixels" ); let fraction_horizontal = (leftf.fract() + rightf.fract()) / 2.; thumbnail_sample_fraction_horizontal( image, right - 1, fraction_horizontal, bottom, top, ) } else if left != right { // && bottom == top // In the first line we have bottom == 0 and top > ceil(x_scale) > 0 so this // assertion can never trigger. debug_assert!( bottom > 0 && top > 0, "First output row must have corresponding pixels" ); let fraction_vertical = (topf.fract() + bottomf.fract()) / 2.; thumbnail_sample_fraction_vertical(image, left, right, top - 1, fraction_vertical) } else { // bottom == top && left == right let fraction_horizontal = (topf.fract() + bottomf.fract()) / 2.; let fraction_vertical = (leftf.fract() + rightf.fract()) / 2.; thumbnail_sample_fraction_both( image, right - 1, fraction_horizontal, top - 1, fraction_vertical, ) }; #[allow(deprecated)] let pixel = Pixel::from_channels(avg.0, avg.1, avg.2, avg.3); out.put_pixel(outx, outy, pixel); } } out } /// Get a pixel for a thumbnail where the input window encloses at least a full pixel. fn thumbnail_sample_block<I, P, S>( image: &I, left: u32, right: u32, bottom: u32, top: u32, ) -> (S, S, S, S) where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S>, S: Primitive + Enlargeable, { let mut sum = ThumbnailSum::zeroed(); for y in bottom..top { for x in left..right { let k = image.get_pixel(x, y); sum.add_pixel(k); } } let n = <S::Larger as NumCast>::from((right - left) * (top - bottom)).unwrap(); let round = <S::Larger as NumCast>::from(n / NumCast::from(2).unwrap()).unwrap(); ( S::clamp_from((sum.0 + round) / n), S::clamp_from((sum.1 + round) / n), S::clamp_from((sum.2 + round) / n), S::clamp_from((sum.3 + round) / n), ) } /// Get a thumbnail pixel where the input window encloses at least a vertical pixel. fn thumbnail_sample_fraction_horizontal<I, P, S>( image: &I, left: u32, fraction_horizontal: f32, bottom: u32, top: u32, ) -> (S, S, S, S) where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S>, S: Primitive + Enlargeable, { let fract = fraction_horizontal; let mut sum_left = ThumbnailSum::zeroed(); let mut sum_right = ThumbnailSum::zeroed(); for x in bottom..top { let k_left = image.get_pixel(left, x); sum_left.add_pixel(k_left); let k_right = image.get_pixel(left + 1, x); sum_right.add_pixel(k_right); } // Now we approximate: left/n*(1-fract) + right/n*fract let fact_right = fract / ((top - bottom) as f32); let fact_left = (1. - fract) / ((top - bottom) as f32); let mix_left_and_right = |leftv: S::Larger, rightv: S::Larger| { <S as NumCast>::from( fact_left * leftv.to_f32().unwrap() + fact_right * rightv.to_f32().unwrap(), ) .expect("Average sample value should fit into sample type") }; ( mix_left_and_right(sum_left.0, sum_right.0), mix_left_and_right(sum_left.1, sum_right.1), mix_left_and_right(sum_left.2, sum_right.2), mix_left_and_right(sum_left.3, sum_right.3), ) } /// Get a thumbnail pixel where the input window encloses at least a horizontal pixel. fn thumbnail_sample_fraction_vertical<I, P, S>( image: &I, left: u32, right: u32, bottom: u32, fraction_vertical: f32, ) -> (S, S, S, S) where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S>, S: Primitive + Enlargeable, { let fract = fraction_vertical; let mut sum_bot = ThumbnailSum::zeroed(); let mut sum_top = ThumbnailSum::zeroed(); for x in left..right { let k_bot = image.get_pixel(x, bottom); sum_bot.add_pixel(k_bot); let k_top = image.get_pixel(x, bottom + 1); sum_top.add_pixel(k_top); } // Now we approximate: bot/n*fract + top/n*(1-fract) let fact_top = fract / ((right - left) as f32); let fact_bot = (1. - fract) / ((right - left) as f32); let mix_bot_and_top = |botv: S::Larger, topv: S::Larger| { <S as NumCast>::from(fact_bot * botv.to_f32().unwrap() + fact_top * topv.to_f32().unwrap()) .expect("Average sample value should fit into sample type") }; ( mix_bot_and_top(sum_bot.0, sum_top.0), mix_bot_and_top(sum_bot.1, sum_top.1), mix_bot_and_top(sum_bot.2, sum_top.2), mix_bot_and_top(sum_bot.3, sum_top.3), ) } /// Get a single pixel for a thumbnail where the input window does not enclose any full pixel. fn thumbnail_sample_fraction_both<I, P, S>( image: &I, left: u32, fraction_vertical: f32, bottom: u32, fraction_horizontal: f32, ) -> (S, S, S, S) where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S>, S: Primitive + Enlargeable, { #[allow(deprecated)] let k_bl = image.get_pixel(left, bottom).channels4(); #[allow(deprecated)] let k_tl = image.get_pixel(left, bottom + 1).channels4(); #[allow(deprecated)] let k_br = image.get_pixel(left + 1, bottom).channels4(); #[allow(deprecated)] let k_tr = image.get_pixel(left + 1, bottom + 1).channels4(); let frac_v = fraction_vertical; let frac_h = fraction_horizontal; let fact_tr = frac_v * frac_h; let fact_tl = frac_v * (1. - frac_h); let fact_br = (1. - frac_v) * frac_h; let fact_bl = (1. - frac_v) * (1. - frac_h); let mix = |br: S, tr: S, bl: S, tl: S| { <S as NumCast>::from( fact_br * br.to_f32().unwrap() + fact_tr * tr.to_f32().unwrap() + fact_bl * bl.to_f32().unwrap() + fact_tl * tl.to_f32().unwrap(), ) .expect("Average sample value should fit into sample type") }; ( mix(k_br.0, k_tr.0, k_bl.0, k_tl.0), mix(k_br.1, k_tr.1, k_bl.1, k_tl.1), mix(k_br.2, k_tr.2, k_bl.2, k_tl.2), mix(k_br.3, k_tr.3, k_bl.3, k_tl.3), ) } /// Perform a 3x3 box filter on the supplied image. /// ```kernel``` is an array of the filter weights of length 9. pub fn filter3x3<I, P, S>(image: &I, kernel: &[f32]) -> ImageBuffer<P, Vec<S>> where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S> + 'static, S: Primitive + 'static, { // The kernel's input positions relative to the current pixel. let taps: &[(isize, isize)] = &[ (-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1), ]; let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, height); let max = S::DEFAULT_MAX_VALUE; let max: f32 = NumCast::from(max).unwrap(); let sum = match kernel.iter().fold(0.0, |s, &item| s + item) { x if x == 0.0 => 1.0, sum => sum, }; let sum = (sum, sum, sum, sum); for y in 1..height - 1 { for x in 1..width - 1 { let mut t = (0.0, 0.0, 0.0, 0.0); // TODO: There is no need to recalculate the kernel for each pixel. // Only a subtract and addition is needed for pixels after the first // in each row. for (&k, &(a, b)) in kernel.iter().zip(taps.iter()) { let k = (k, k, k, k); let x0 = x as isize + a; let y0 = y as isize + b; let p = image.get_pixel(x0 as u32, y0 as u32); #[allow(deprecated)] let (k1, k2, k3, k4) = p.channels4(); let vec: (f32, f32, f32, f32) = ( NumCast::from(k1).unwrap(), NumCast::from(k2).unwrap(), NumCast::from(k3).unwrap(), NumCast::from(k4).unwrap(), ); t.0 += vec.0 * k.0; t.1 += vec.1 * k.1; t.2 += vec.2 * k.2; t.3 += vec.3 * k.3; } let (t1, t2, t3, t4) = (t.0 / sum.0, t.1 / sum.1, t.2 / sum.2, t.3 / sum.3); #[allow(deprecated)] let t = Pixel::from_channels( NumCast::from(clamp(t1, 0.0, max)).unwrap(), NumCast::from(clamp(t2, 0.0, max)).unwrap(), NumCast::from(clamp(t3, 0.0, max)).unwrap(), NumCast::from(clamp(t4, 0.0, max)).unwrap(), ); out.put_pixel(x, y, t); } } out } /// Resize the supplied image to the specified dimensions. /// ```nwidth``` and ```nheight``` are the new dimensions. /// ```filter``` is the sampling filter to use. pub fn resize<I: GenericImageView>( image: &I, nwidth: u32, nheight: u32, filter: FilterType, ) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::Subpixel>> where I::Pixel: 'static, <I::Pixel as Pixel>::Subpixel: 'static, { let mut method = match filter { FilterType::Nearest => Filter { kernel: Box::new(box_kernel), support: 0.0, }, FilterType::Triangle => Filter { kernel: Box::new(triangle_kernel), support: 1.0, }, FilterType::CatmullRom => Filter { kernel: Box::new(catmullrom_kernel), support: 2.0, }, FilterType::Gaussian => Filter { kernel: Box::new(gaussian_kernel), support: 3.0, }, FilterType::Lanczos3 => Filter { kernel: Box::new(lanczos3_kernel), support: 3.0, }, }; // Note: tmp is not necessarily actually Rgba let tmp: Rgba32FImage = vertical_sample(image, nheight, &mut method); horizontal_sample(&tmp, nwidth, &mut method) } /// Performs a Gaussian blur on the supplied image. /// ```sigma``` is a measure of how much to blur by. pub fn blur<I: GenericImageView>( image: &I, sigma: f32, ) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::Subpixel>> where I::Pixel: 'static, { let sigma = if sigma <= 0.0 { 1.0 } else { sigma }; let mut method = Filter { kernel: Box::new(|x| gaussian(x, sigma)), support: 2.0 * sigma, }; let (width, height) = image.dimensions(); // Keep width and height the same for horizontal and // vertical sampling. // Note: tmp is not necessarily actually Rgba let tmp: Rgba32FImage = vertical_sample(image, height, &mut method); horizontal_sample(&tmp, width, &mut method) } /// Performs an unsharpen mask on the supplied image. /// ```sigma``` is the amount to blur the image by. /// ```threshold``` is the threshold for minimal brightness change that will be sharpened. /// /// See <https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking> pub fn unsharpen<I, P, S>(image: &I, sigma: f32, threshold: i32) -> ImageBuffer<P, Vec<S>> where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S> + 'static, S: Primitive + 'static, { let mut tmp = blur(image, sigma); let max = S::DEFAULT_MAX_VALUE; let max: i32 = NumCast::from(max).unwrap(); let (width, height) = image.dimensions(); for y in 0..height { for x in 0..width { let a = image.get_pixel(x, y); let b = tmp.get_pixel_mut(x, y); let p = a.map2(b, |c, d| { let ic: i32 = NumCast::from(c).unwrap(); let id: i32 = NumCast::from(d).unwrap(); let diff = (ic - id).abs(); if diff > threshold { let e = clamp(ic + diff, 0, max); // FIXME what does this do for f32? clamp 0-1 integers?? NumCast::from(e).unwrap() } else { c } }); *b = p; } } tmp } #[cfg(test)] mod tests { use super::{resize, FilterType}; use crate::{ImageBuffer, RgbImage}; #[cfg(feature = "benchmarks")] use test; #[bench] #[cfg(all(feature = "benchmarks", feature = "png"))] fn bench_resize(b: &mut test::Bencher) { use std::path::Path; let img = crate::open(&Path::new("./examples/fractal.png")).unwrap(); b.iter(|| { test::black_box(resize(&img, 200, 200, FilterType::Nearest)); }); b.bytes = 800 * 800 * 3 + 200 * 200 * 3; } #[test] fn test_issue_186() { let img: RgbImage = ImageBuffer::new(100, 100); let _ = resize(&img, 50, 50, FilterType::Lanczos3); } #[bench] #[cfg(all(feature = "benchmarks", feature = "tiff"))] fn bench_thumbnail(b: &mut test::Bencher) { let path = concat!( env!("CARGO_MANIFEST_DIR"), "/tests/images/tiff/testsuite/mandrill.tiff" ); let image = crate::open(path).unwrap(); b.iter(|| { test::black_box(image.thumbnail(256, 256)); }); b.bytes = 512 * 512 * 4 + 256 * 256 * 4; } #[bench] #[cfg(all(feature = "benchmarks", feature = "tiff"))] fn bench_thumbnail_upsize(b: &mut test::Bencher) { let path = concat!( env!("CARGO_MANIFEST_DIR"), "/tests/images/tiff/testsuite/mandrill.tiff" ); let image = crate::open(path).unwrap().thumbnail(256, 256); b.iter(|| { test::black_box(image.thumbnail(512, 512)); }); b.bytes = 512 * 512 * 4 + 256 * 256 * 4; } #[bench] #[cfg(all(feature = "benchmarks", feature = "tiff"))] fn bench_thumbnail_upsize_irregular(b: &mut test::Bencher) { let path = concat!( env!("CARGO_MANIFEST_DIR"), "/tests/images/tiff/testsuite/mandrill.tiff" ); let image = crate::open(path).unwrap().thumbnail(193, 193); b.iter(|| { test::black_box(image.thumbnail(256, 256)); }); b.bytes = 193 * 193 * 4 + 256 * 256 * 4; } #[test] #[cfg(feature = "png")] fn resize_transparent_image() { use super::FilterType::{CatmullRom, Gaussian, Lanczos3, Nearest, Triangle}; use crate::imageops::crop_imm; use crate::RgbaImage; fn assert_resize(image: &RgbaImage, filter: FilterType) { let resized = resize(image, 16, 16, filter); let cropped = crop_imm(&resized, 5, 5, 6, 6).to_image(); for pixel in cropped.pixels() { let alpha = pixel.0[3]; assert!( alpha != 254 && alpha != 253, "alpha value: {}, {:?}", alpha, filter ); } } let path = concat!( env!("CARGO_MANIFEST_DIR"), "/tests/images/png/transparency/tp1n3p08.png" ); let img = crate::open(path).unwrap(); let rgba8 = img.as_rgba8().unwrap(); let filters = &[Nearest, Triangle, CatmullRom, Gaussian, Lanczos3]; for filter in filters { assert_resize(rgba8, *filter); } } #[test] fn bug_1600() { let image = crate::RgbaImage::from_raw(629, 627, vec![255; 629 * 627 * 4]).unwrap(); let result = resize(&image, 22, 22, FilterType::Lanczos3); assert!(result.into_raw().into_iter().any(|c| c != 0)); } }
31.674948
140
0.54801
1dac4e22ae7ad2c80eaaa6b5c55cd982e10aca32
11,419
//! Recursive-descent parser for semver ranges. //! //! The parsers is divided into a set of functions, each responsible for parsing a subset of the //! grammar. //! //! # Examples //! //! ```rust //! use reproto_semver::parser::Parser; //! use reproto_semver::range::Op; //! //! let mut p = Parser::new("^1").expect("a broken parser"); //! //! assert_eq!(Ok(Op::Compatible), p.op()); //! assert_eq!(Ok(Some(1)), p.component()); //! ``` //! //! Example parsing a range: //! //! ```rust //! use reproto_semver::parser::Parser; //! use reproto_semver::range::{Op, Predicate}; //! //! let mut p = Parser::new("^1.0").expect("a broken parser"); //! //! assert_eq!(Ok(Some(Predicate { //! op: Op::Compatible, //! major: 1, //! minor: Some(0), //! patch: None, //! pre: vec![], //! })), p.predicate()); //! //! let mut p = Parser::new("^*").expect("a broken parser"); //! //! assert_eq!(Ok(None), p.predicate()); //! ``` use self::Error::*; use lexer::{self, Lexer, Token}; use range::{Op, Predicate, Range, WildcardVersion}; use std::error; use std::fmt; use std::mem; use version::{Identifier, Version}; /// Evaluate if parser contains the given pattern as a separator, surrounded by whitespace. macro_rules! has_ws_separator { ($slf:expr, $pat:pat) => {{ $slf.skip_whitespace()?; match $slf.peek() { $pat => { // pop the separator. $slf.pop()?; // strip suffixing whitespace. $slf.skip_whitespace()?; true } _ => false, } }}; } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Error<'input> { /// Needed more tokens for parsing, but none are available. UnexpectedEnd, /// Unexpected token. UnexpectedToken(Token<'input>), /// An error occurred in the lexer. Lexer(lexer::Error), /// More input available. MoreInput(Vec<Token<'input>>), /// Encountered empty predicate in a set of predicates. EmptyPredicate, /// Encountered an empty range. EmptyRange, } impl<'input> fmt::Display for Error<'input> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { UnexpectedEnd => write!(fmt, "unexpected end"), UnexpectedToken(ref t) => write!(fmt, "unexpected token: {:?}", t), Lexer(ref l) => write!(fmt, "lexer error: {}", l), MoreInput(..) => write!(fmt, "more input"), EmptyPredicate => write!(fmt, "empty predicate"), EmptyRange => write!(fmt, "empty range"), } } } impl<'input> error::Error for Error<'input> { fn description(&self) -> &str { match *self { UnexpectedEnd => "unexpected end", UnexpectedToken(..) => "unexpected token", Lexer(ref l) => l.description(), MoreInput(..) => "more input", EmptyPredicate => "empty predicate", EmptyRange => "empty range", } } } impl<'input> From<lexer::Error> for Error<'input> { fn from(value: lexer::Error) -> Self { Error::Lexer(value) } } /// impl for backwards compatibility. impl<'input> From<Error<'input>> for String { fn from(value: Error<'input>) -> Self { value.to_string() } } /// A recursive-descent parser for parsing version requirements. pub struct Parser<'input> { /// Source of token. lexer: Lexer<'input>, /// Lookaehead. c1: Option<Token<'input>>, } impl<'input> Parser<'input> { /// Construct a new parser for the given input. pub fn new(input: &'input str) -> Result<Parser<'input>, Error<'input>> { let mut lexer = Lexer::new(input); let c1 = if let Some(c1) = lexer.next() { Some(c1?) } else { None }; Ok(Parser { lexer, c1 }) } /// Pop one token. #[inline(always)] fn pop(&mut self) -> Result<Token<'input>, Error<'input>> { let c1 = if let Some(c1) = self.lexer.next() { Some(c1?) } else { None }; mem::replace(&mut self.c1, c1).ok_or_else(|| UnexpectedEnd) } /// Peek one token. #[inline(always)] fn peek(&mut self) -> Option<&Token<'input>> { self.c1.as_ref() } /// Skip whitespace if present. fn skip_whitespace(&mut self) -> Result<(), Error<'input>> { match self.peek() { Some(&Token::Whitespace(_, _)) => self.pop().map(|_| ()), _ => Ok(()), } } /// Parse an optional comma separator, then if that is present a predicate. pub fn comma_predicate(&mut self) -> Result<Option<Predicate>, Error<'input>> { if !has_ws_separator!(self, Some(&Token::Comma)) { return Ok(None); } if let Some(predicate) = self.predicate()? { Ok(Some(predicate)) } else { Err(EmptyPredicate) } } /// Parse a single component. /// /// Returns `None` if the component is a wildcard. pub fn component(&mut self) -> Result<Option<u64>, Error<'input>> { match self.pop()? { Token::Numeric(number) => Ok(Some(number)), ref t if t.is_wildcard() => Ok(None), tok => Err(UnexpectedToken(tok)), } } /// Parse a single numeric. pub fn numeric(&mut self) -> Result<u64, Error<'input>> { match self.pop()? { Token::Numeric(number) => Ok(number), tok => Err(UnexpectedToken(tok)), } } /// Optionally parse a dot, then a component. /// /// The second component of the tuple indicates if a wildcard has been encountered, and is /// always `false` if the first component is `Some`. /// /// If a dot is not encountered, `(None, false)` is returned. /// /// If a wildcard is encountered, `(None, true)` is returned. pub fn dot_component(&mut self) -> Result<(Option<u64>, bool), Error<'input>> { match self.peek() { Some(&Token::Dot) => {} _ => return Ok((None, false)), } // pop the peeked dot. self.pop()?; self.component().map(|n| (n, n.is_none())) } /// Parse a dot, then a numeric. pub fn dot_numeric(&mut self) -> Result<u64, Error<'input>> { match self.pop()? { Token::Dot => {} tok => return Err(UnexpectedToken(tok)), } self.numeric() } /// Parse an string identifier. /// /// Like, `foo`, or `bar`. pub fn identifier(&mut self) -> Result<Identifier, Error<'input>> { let identifier = match self.pop()? { Token::AlphaNumeric(identifier) => { // TODO: Borrow? Identifier::AlphaNumeric(identifier.to_string()) } Token::Numeric(n) => Identifier::Numeric(n), tok => return Err(UnexpectedToken(tok)), }; Ok(identifier) } /// Parse all pre-release identifiers, separated by dots. /// /// Like, `abcdef.1234`. fn pre(&mut self) -> Result<Vec<Identifier>, Error<'input>> { match self.peek() { Some(&Token::Hyphen) => {} _ => return Ok(vec![]), } // pop the peeked hyphen. self.pop()?; self.parts() } /// Parse a dot-separated set of identifiers. fn parts(&mut self) -> Result<Vec<Identifier>, Error<'input>> { let mut parts = Vec::new(); parts.push(self.identifier()?); loop { match self.peek() { Some(&Token::Dot) | Some(&Token::Hyphen) => {} _ => break, } // pop the peeked hyphen. self.pop()?; parts.push(self.identifier()?); } Ok(parts) } /// Parse optional build metadata. /// /// Like, `` (empty), or `+abcdef`. fn plus_build_metadata(&mut self) -> Result<Vec<Identifier>, Error<'input>> { match self.peek() { Some(&Token::Plus) => {} _ => return Ok(vec![]), } // pop the plus. self.pop()?; self.parts() } /// Optionally parse a single operator. /// /// Like, `~`, or `^`. pub fn op(&mut self) -> Result<Op, Error<'input>> { use self::Token::*; let op = match self.peek() { Some(&Eq) => Op::Ex, Some(&Gt) => Op::Gt, Some(&GtEq) => Op::GtEq, Some(&Lt) => Op::Lt, Some(&LtEq) => Op::LtEq, Some(&Tilde) => Op::Tilde, Some(&Caret) => Op::Compatible, // default op _ => return Ok(Op::Compatible), }; // remove the matched token. self.pop()?; self.skip_whitespace()?; Ok(op) } /// Parse a single predicate. /// /// Like, `^1`, or `>=2.0.0`. pub fn predicate(&mut self) -> Result<Option<Predicate>, Error<'input>> { // empty predicate, treated the same as wildcard. if self.peek().is_none() { return Ok(None); } let mut op = self.op()?; let major = match self.component()? { Some(major) => major, None => return Ok(None), }; let (minor, minor_wildcard) = self.dot_component()?; let (patch, patch_wildcard) = self.dot_component()?; let pre = self.pre()?; // TODO: avoid illegal combinations, like `1.*.0`. if minor_wildcard { op = Op::Wildcard(WildcardVersion::Minor); } if patch_wildcard { op = Op::Wildcard(WildcardVersion::Patch); } // ignore build metadata self.plus_build_metadata()?; Ok(Some(Predicate { op, major, minor, patch, pre, })) } /// Parse a single range. /// /// Like, `^1.0` or `>=3.0.0, <4.0.0`. pub fn range(&mut self) -> Result<Range, Error<'input>> { let mut predicates = Vec::new(); if let Some(predicate) = self.predicate()? { predicates.push(predicate); while let Some(next) = self.comma_predicate()? { predicates.push(next); } } Ok(Range { predicates }) } /// Parse a version. /// /// Like, `1.0.0` or `3.0.0-beta.1`. pub fn version(&mut self) -> Result<Version, Error<'input>> { self.skip_whitespace()?; let major = self.numeric()?; let minor = self.dot_numeric()?; let patch = self.dot_numeric()?; let pre = self.pre()?; let build = self.plus_build_metadata()?; self.skip_whitespace()?; Ok(Version { major, minor, patch, pre, build, }) } /// Check if we have reached the end of input. pub fn is_eof(&self) -> bool { self.c1.is_none() } /// Get the rest of the tokens in the parser. /// /// Useful for debugging. #[allow(unused)] pub fn tail(&mut self) -> Result<Vec<Token<'input>>, Error<'input>> { let mut out = Vec::new(); if let Some(t) = self.c1.take() { out.push(t); } while let Some(t) = self.lexer.next() { out.push(t?); } Ok(out) } }
27.059242
96
0.512829
18aa1973469c8bfc9be4c2e31bbcfd7f364b6293
4,120
mod test; use std::rc::Rc; use std::cell::RefCell; use std::fs::File; use std::io::{Read, BufReader}; use core::*; use lexer::*; use parser::*; use walker::*; pub struct Printer { vm: Rc<RefCell<Heliqs>>, } impl Printer { pub fn new(vm: Rc<RefCell<Heliqs>>) -> Self { Printer{ vm: vm } } pub fn print(&self) -> String { if let Some(entrypoint) = self.vm.borrow().entry() { self.print_aexp(entrypoint, 0) } else { "".to_string() } } pub fn print_aexp(&self, i: NodeId, nest_level: u32) -> String { let vm = self.vm.borrow(); let &Node(_, ref epiq) = vm.get_epiq(i); match **epiq { Epiq::Unit => ";".to_string(), Epiq::Tval => "^T".to_string(), Epiq::Fval => "^F".to_string(), Epiq::Name(ref n) => n.to_string(), Epiq::Uit8(ref n) => format!("{}", n), Epiq::Text(ref n) => format!("\"{}\"", n), Epiq::Prim(ref n) => format!("Prim({})", n), Epiq::Tpiq { ref o, p, q } => self.print_piq(o, p, q, nest_level), Epiq::Mpiq { ref o, p, q } => self.print_piq(&format!("^{}", o), p, q, nest_level), Epiq::Eval(p, q) => self.print_piq(">", p, q, nest_level), Epiq::Quot(p, q) => self.print_piq("|", p, q, nest_level), Epiq::Lpiq(p, q) => self.print_piq(":", p, q, nest_level), Epiq::Appl(p, q) => self.print_piq("!", p, q, nest_level), Epiq::Rslv(p, q) => self.print_piq("@", p, q, nest_level), Epiq::Cond(p, q) => self.print_piq("?", p, q, nest_level), Epiq::Envn(p, q) => self.print_piq("%", p, q, nest_level), Epiq::Bind(p, q) => self.print_piq("#", p, q, nest_level), Epiq::Accs(p, q) => self.print_piq(".", p, q, nest_level), Epiq::Lmbd(p, q) => self.print_piq(r"\", p, q, nest_level), // _ => "".to_string(), } } fn print_piq(&self, otag: &str, p: NodeId, q:NodeId, nest_level: u32) -> String { format!("{}({} {})", otag, self.print_aexp(p, nest_level + 1), self.print_aexp(q, nest_level + 1)) } } pub fn print_str(left: &str, right: &str) { let mut iter = left.bytes(); let scanners: &Vec<&Scanner> = &all_scanners!(); let lexer = Lexer::new(&mut iter, scanners); let vm = Rc::new(RefCell::new(Heliqs::new())); let vm2 = vm.clone(); let mut parser = Parser::new(lexer, vm); let _parsed_ast = parser.parse(); let printer = Printer::new(vm2); assert_eq!(printer.print(), right); } pub fn evaled_str(left: &str) -> String { let mut iter = left.bytes(); let scanners: &Vec<&Scanner> = &all_scanners!(); let lexer = Lexer::new(&mut iter, scanners); evaled_lexer(lexer) } pub fn evaled_reader(file_name: &str) -> String { let file = File::open(file_name).unwrap(); let mut bytes = BufReader::new(file).bytes(); let scanners: &Vec<&Scanner> = &all_scanners!(); let lexer = Lexer::new2(&mut bytes, scanners); evaled_lexer(lexer) } fn evaled_lexer<'a>(lexer :Lexer<'a, 'a>) -> String { let vm = Rc::new(RefCell::new(Heliqs::new())); let vm2 = vm.clone(); let vm3 = vm.clone(); let mut parser = Parser::new(lexer, vm); parser.parse(); let walker = Walker::new(vm2); walker.walk(); let printer = Printer::new(vm3); printer.print() } pub fn print_evaled_str(left: &str, right: &str) { let result = evaled_str(left); assert_eq!(result, right); } /// leftを評価したらちゃんとrightになるかどうかのテスト pub fn print_syntax_sugar(left: &str, right: &str) { let result_left = evaled_str(left); let result_right = evaled_str(right); assert_eq!(result_left, result_right); } pub fn only_evaluate(s: &str) { let mut iter = s.bytes(); let scanners: &Vec<&Scanner> = &all_scanners!(); let lexer = Lexer::new(&mut iter, scanners); let vm = Rc::new(RefCell::new(Heliqs::new())); let vm2 = vm.clone(); let mut parser = Parser::new(lexer, vm); parser.parse(); let walker = Walker::new(vm2); walker.walk(); }
30.294118
106
0.554369
1134a39588b1264355f4ffb74806d49845e50467
970
use fil_actors_runtime::test_utils::{expect_abort, MockRuntime}; use fvm_shared::{econ::TokenAmount, error::ExitCode}; mod util; use util::*; fn setup() -> (ActorHarness, MockRuntime) { let big_balance = 20u128.pow(23); let period_offset = 100; let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); rt.balance.replace(TokenAmount::from(big_balance)); (h, rt) } #[test] fn successfully_check_sector_is_proven() { let (mut h, mut rt) = setup(); let sectors = h.commit_and_prove_sectors(&mut rt, 1, DEFAULT_SECTOR_EXPIRATION, vec![vec![10]], true); h.check_sector_proven(&mut rt, sectors[0].sector_number).unwrap(); check_state_invariants(&rt); } #[test] fn fails_if_sector_is_not_found() { let (h, mut rt) = setup(); let result = h.check_sector_proven(&mut rt, 1); expect_abort(ExitCode::USR_NOT_FOUND, result); check_state_invariants(&rt); }
24.871795
96
0.684536
ab3c5d641675ca864939cae6103a70699a1bf8fe
1,897
use super::add::handle_add_op; use crate::{object::Array, Evaluator, Object, RuntimeErrorKind}; /// This calls the add op under the hood /// We negate the RHS and send it to the add op pub fn handle_sub_op( left: Object, right: Object, evaluator: &mut Evaluator, ) -> Result<Object, RuntimeErrorKind> { let negated_right = match right { Object::Null => { return Err(RuntimeErrorKind::UnstructuredError { span: Default::default(), message: "cannot do an operation with the null object".to_string(), }) } Object::Arithmetic(arith) => Object::Arithmetic(-&arith), Object::Constants(c) => Object::Constants(-c), Object::Linear(linear) => Object::Linear(-&linear), Object::Integer(_rhs_integer) => { let left_int = left.integer(); match left_int { Some(left_int) => return Ok(Object::Integer(left_int.sub(right, evaluator)?)), None => { return Err(RuntimeErrorKind::UnstructuredError { span: Default::default(), message: "rhs is an integer, however the lhs is not".to_string(), }) } } } Object::Array(_right_arr) => { let left_arr = left.array(); match left_arr { Some(left_arr) => { return Ok(Object::Array(Array::sub(left_arr, _right_arr, evaluator)?)) } None => { return Err(RuntimeErrorKind::UnstructuredError { span: Default::default(), message: "rhs is an integer, however the lhs is not".to_string(), }) } } } }; handle_add_op(left, negated_right, evaluator) }
37.196078
94
0.518187
0870118d98dbdf8155273ff9a8e6ccb1a46ce959
29,217
use super::{input::ParserInput, PResult, Parser}; use crate::{ error::{Error, ErrorKind}, Parse, }; use swc_atoms::{js_word, JsWord}; use swc_common::{BytePos, Span}; use swc_css_ast::*; impl<I> Parser<I> where I: ParserInput, { pub(super) fn parse_selectors(&mut self) -> PResult<SelectorList> { self.input.skip_ws()?; let child = self.parse_complex_selector()?; let mut children = vec![child]; loop { self.input.skip_ws()?; if !eat!(self, ",") { break; } self.input.skip_ws()?; let child = self.parse_complex_selector()?; children.push(child); } let start_pos = match children.first() { Some(ComplexSelector { span, .. }) => span.lo, _ => { unreachable!(); } }; let last_pos = match children.last() { Some(ComplexSelector { span, .. }) => span.hi, _ => { unreachable!(); } }; Ok(SelectorList { span: Span::new(start_pos, last_pos, Default::default()), children, }) } fn parse_complex_selector(&mut self) -> PResult<ComplexSelector> { let child = ComplexSelectorChildren::CompoundSelector(self.parse_compound_selector()?); let mut children = vec![child]; loop { let span = self.input.cur_span()?; self.input.skip_ws()?; if is_one_of!(self, EOF, ",", "{") { break; } let mut combinator = self.parse_combinator()?; if combinator.value == CombinatorValue::Descendant { combinator.span = span; } else { self.input.skip_ws()?; } children.push(ComplexSelectorChildren::Combinator(combinator)); let child = self.parse_compound_selector()?; children.push(ComplexSelectorChildren::CompoundSelector(child)); } let start_pos = match children.first() { Some(ComplexSelectorChildren::CompoundSelector(child)) => child.span.lo, _ => { unreachable!(); } }; let last_pos = match children.last() { Some(ComplexSelectorChildren::CompoundSelector(child)) => child.span.hi, _ => { unreachable!(); } }; Ok(ComplexSelector { span: Span::new(start_pos, last_pos, Default::default()), children, }) } fn parse_combinator(&mut self) -> PResult<Combinator> { let span = self.input.cur_span()?; if eat!(self, ">") { return Ok(Combinator { span, value: CombinatorValue::Child, }); } else if eat!(self, "+") { return Ok(Combinator { span, value: CombinatorValue::NextSibling, }); } else if eat!(self, "~") { return Ok(Combinator { span, value: CombinatorValue::LaterSibling, }); } return Ok(Combinator { span, value: CombinatorValue::Descendant, }); } fn parse_ns_prefix(&mut self) -> PResult<Option<Ident>> { let span = self.input.cur_span()?; if is!(self, Ident) && peeked_is!(self, "|") { let token = bump!(self); let ident = match token { Token::Ident { value, raw } => Ident { span, value, raw }, _ => { unreachable!() } }; bump!(self); return Ok(Some(ident)); } else if is!(self, "*") && peeked_is!(self, "|") { bump!(self); bump!(self); let value: JsWord = "*".into(); let raw = value.clone(); return Ok(Some(Ident { span, value, raw })); } else if is!(self, "|") { bump!(self); return Ok(Some(Ident { span: Span::new(span.lo, span.lo, Default::default()), value: js_word!(""), raw: js_word!(""), })); } Ok(None) } fn parse_wq_name(&mut self) -> PResult<(Option<Ident>, Option<Ident>)> { let state = self.input.state(); if is!(self, Ident) && peeked_is!(self, "|") || is!(self, "*") && peeked_is!(self, "|") || is!(self, "|") { let prefix = self.parse_ns_prefix()?; if is!(self, Ident) { let span = self.input.cur_span()?; let token = bump!(self); let name = match token { Token::Ident { value, raw } => Ident { span, value, raw }, _ => { unreachable!() } }; return Ok((prefix, Some(name))); } else { // TODO: implement `peeked_ahead_is` for perf self.input.reset(&state); } } if is!(self, Ident) { let span = self.input.cur_span()?; let token = bump!(self); let name = match token { Token::Ident { value, raw } => Ident { span, value, raw }, _ => { unreachable!() } }; return Ok((None, Some(name))); } Ok((None, None)) } fn parse_type_selector(&mut self) -> PResult<Option<TypeSelector>> { let span = self.input.cur_span()?; let mut prefix = None; if let Ok(result) = self.parse_ns_prefix() { prefix = result; } if is!(self, Ident) { let name_span = self.input.cur_span()?; let token = bump!(self); let name = match token { Token::Ident { value, raw } => Ident { span: name_span, value, raw, }, _ => { unreachable!() } }; return Ok(Some(TypeSelector { span: span!(self, span.lo), prefix, name, })); } else if is!(self, "*") { let name_span = self.input.cur_span()?; bump!(self); let value: JsWord = "*".into(); let raw = value.clone(); let name = Ident { span: name_span, value, raw, }; return Ok(Some(TypeSelector { span: span!(self, span.lo), prefix, name, })); } Ok(None) } fn parse_id_selector(&mut self) -> PResult<IdSelector> { let span = self.input.cur_span()?; let ident = match bump!(self) { Token::Hash { value, raw, .. } => Ident { span, value, raw }, _ => { unreachable!() } }; Ok(IdSelector { span: span!(self, span.lo), text: ident, }) } fn parse_class_selector(&mut self) -> PResult<ClassSelector> { let start_pos = self.input.cur_span()?.lo; bump!(self); let span = self.input.cur_span()?; match cur!(self) { Token::Ident { .. } => {} _ => Err(Error::new(span, ErrorKind::ExpectedSelectorText))?, } let value = bump!(self); let values = match value { Token::Ident { value, raw } => (value, raw), _ => unreachable!(), }; Ok(ClassSelector { span: span!(self, start_pos), text: Ident { span, value: values.0, raw: values.1, }, }) } fn parse_attribute_selector(&mut self) -> PResult<AttrSelector> { let start_pos = self.input.cur_span()?.lo; expect!(self, "["); self.input.skip_ws()?; let prefix; let name; let mut attr_matcher = None; let mut matcher_value = None; let mut matcher_modifier = None; if let Ok((p, Some(n))) = self.parse_wq_name() { prefix = p; name = n; } else { return Err(Error::new( span!(self, start_pos), ErrorKind::InvalidAttrSelectorName, )); } self.input.skip_ws()?; if !is!(self, "]") { let span = self.input.cur_span()?; attr_matcher = match cur!(self) { tok!("~") | tok!("|") | tok!("^") | tok!("$") | tok!("*") => { let tok = bump!(self); expect!(self, "="); Some(match tok { tok!("~") => AttrSelectorMatcher::Tilde, tok!("|") => AttrSelectorMatcher::Bar, tok!("^") => AttrSelectorMatcher::Caret, tok!("$") => AttrSelectorMatcher::Dollar, tok!("*") => AttrSelectorMatcher::Asterisk, _ => { unreachable!() } }) } tok!("=") => { let tok = bump!(self); Some(match tok { tok!("=") => AttrSelectorMatcher::Equals, _ => { unreachable!() } }) } _ => Err(Error::new(span, ErrorKind::InvalidAttrSelectorMatcher))?, }; self.input.skip_ws()?; let span = self.input.cur_span()?; matcher_value = match cur!(self) { Token::Ident { .. } => { let value = bump!(self); let ident = match value { Token::Ident { value, raw } => (value, raw), _ => unreachable!(), }; Some(AttrSelectorValue::Ident(Ident { span, value: ident.0, raw: ident.1, })) } Token::Str { .. } => { let value = bump!(self); let str = match value { Token::Str { value, raw } => (value, raw), _ => unreachable!(), }; Some(AttrSelectorValue::Str(Str { span, value: str.0, raw: str.1, })) } _ => Err(Error::new(span, ErrorKind::InvalidAttrSelectorMatcherValue))?, }; self.input.skip_ws()?; if is!(self, Ident) { let span = self.input.cur_span()?; match self.input.cur()? { Some(Token::Ident { value, .. }) => { matcher_modifier = value.chars().next(); bump!(self); } _ => Err(Error::new(span, ErrorKind::InvalidAttrSelectorModifier))?, } } self.input.skip_ws()?; } expect!(self, "]"); Ok(AttrSelector { span: span!(self, start_pos), prefix, name, matcher: attr_matcher, value: matcher_value, modifier: matcher_modifier, }) } fn parse_nth(&mut self) -> PResult<Nth> { self.input.skip_ws()?; let span = self.input.cur_span()?; let nth = match cur!(self) { // odd | even Token::Ident { value, .. } if &(*value).to_ascii_lowercase() == "odd" || &(*value).to_ascii_lowercase() == "even" => { let name = bump!(self); let names = match name { Token::Ident { value, raw } => (value, raw), _ => { unreachable!(); } }; NthValue::Ident(Ident { span: span!(self, span.lo), value: names.0.into(), raw: names.1.into(), }) } // <integer> Token::Num { .. } => { let num = match bump!(self) { Token::Num { value, raw } => (value, raw), _ => { unreachable!(); } }; NthValue::AnPlusB(AnPlusB { span: span!(self, span.lo), a: None, a_raw: None, b: Some(num.0 as i32), b_raw: Some(num.1), }) } // '+'? n // '+'? <ndashdigit-ident> // '+'? n <signed-integer> // '+'? n- <signless-integer> // '+'? n ['+' | '-'] <signless-integer> // -n // <dashndashdigit-ident> // -n <signed-integer> // -n- <signless-integer> // -n ['+' | '-'] <signless-integer> Token::Ident { .. } | Token::Delim { value: '+' } | // <n-dimension> // <ndashdigit-dimension> // <ndash-dimension> <signless-integer> // <n-dimension> <signed-integer> // <n-dimension> ['+' | '-'] <signless-integer> Token::Dimension { .. } => { let mut has_plus_sign = false; // '+' n match cur!(self) { Token::Delim { value: '+' } => { let peeked = self.input.peek()?; match peeked { Some(Token::Ident { .. }) => { bump!(self); has_plus_sign = true; } _ => {} } } _ => {} } let a; let a_raw; let n_value; match cur!(self) { Token::Ident { .. } => { let ident_value = match bump!(self) { Token::Ident { value, .. } => value, _ => { unreachable!(); } }; let has_minus_sign = ident_value.chars().nth(0) == Some('-'); let n_char = if has_minus_sign { ident_value.chars().nth(1) } else { ident_value.chars().nth(0) }; if n_char != Some('n') && n_char != Some('N') { return Err(Error::new( span, ErrorKind::Expected("'n' character in Ident"), )); } a = Some(if has_minus_sign { -1 } else {1 }); a_raw = Some((if has_plus_sign { "+" } else if has_minus_sign { "-" } else { "" }).into()); n_value = if has_minus_sign { ident_value.clone()[1..].to_string() } else { ident_value.clone().to_string() }; } Token::Dimension { .. } => { let dimension = match bump!(self) { Token::Dimension { value, raw_value, unit, .. } => (value, raw_value, unit), _ => { unreachable!(); } }; let n_char = dimension.2.chars().nth(0); if n_char != Some('n') && n_char != Some('N') { return Err(Error::new( span, ErrorKind::Expected("'n' character in Ident"), )); } a = Some(dimension.0 as i32); a_raw = Some(dimension.1.into()); n_value = (*dimension.2).to_string(); } _ => { return Err(Error::new(span, ErrorKind::InvalidAnPlusBMicrosyntax)); } }; self.input.skip_ws()?; let mut b = None; let mut b_raw = None; let dash_after_n = n_value.chars().nth(1); match cur!(self) { // '+'? n <signed-integer> // -n <signed-integer> // <n-dimension> <signed-integer> Token::Num { .. } if dash_after_n == None => { let num = match bump!(self) { Token::Num { value, raw, .. } => (value, raw), _ => { unreachable!(); } }; b = Some(num.0 as i32); b_raw = Some(num.1); } // -n- <signless-integer> // '+'? n- <signless-integer> // <ndash-dimension> <signless-integer> Token::Num { .. } if dash_after_n == Some('-') => { let num = match bump!(self) { Token::Num { value, raw, .. } => (value, raw), _ => { unreachable!(); } }; b = Some(-1 * num.0 as i32); let mut b_raw_str = String::new(); b_raw_str.push_str("- "); b_raw_str.push_str(&num.1); b_raw = Some(b_raw_str.into()); } // '+'? n ['+' | '-'] <signless-integer> // -n ['+' | '-'] <signless-integer> // <n-dimension> ['+' | '-'] <signless-integer> Token::Delim { value: '-', .. } | Token::Delim { value: '+', .. } => { let (b_sign, b_sign_raw) = match bump!(self) { Token::Delim { value, .. } => (if value == '-' { -1 } else { 1 }, value), _ => { unreachable!(); } }; self.input.skip_ws()?; let num = match bump!(self) { Token::Num { value, raw, .. } => (value, raw), _ => { return Err(Error::new(span, ErrorKind::Expected("Num"))); } }; b = Some(b_sign * num.0 as i32); let mut b_raw_str = String::new(); b_raw_str.push(' '); b_raw_str.push(b_sign_raw); b_raw_str.push(' '); b_raw_str.push_str(&num.1); b_raw = Some(b_raw_str.into()); } // '+'? <ndashdigit-ident> // <dashndashdigit-ident> // <ndashdigit-dimension> _ if dash_after_n == Some('-') => { let b_from_ident = &n_value[2..]; let parsed: i32 = lexical::parse(b_from_ident).unwrap_or_else(|err| { unreachable!( "failed to parse `{}` using lexical: {:?}", b_from_ident, err ) }); b = Some(-1 * parsed); let mut b_raw_str = String::new(); b_raw_str.push('-'); b_raw_str.push_str(b_from_ident); b_raw = Some(b_raw_str.into()); } // '+'? n // -n _ if dash_after_n == None => {} _ => { return Err(Error::new(span, ErrorKind::InvalidAnPlusBMicrosyntax)); } } NthValue::AnPlusB(AnPlusB { span: span!(self, span.lo), a, a_raw, b, b_raw, }) } _ => { return Err(Error::new(span, ErrorKind::InvalidAnPlusBMicrosyntax)); } }; let nth = Nth { span: span!(self, span.lo), nth, selector_list: None, }; self.input.skip_ws()?; // match cur!(self) { // Token::Ident { value, .. } => { // match &*value.to_ascii_lowercase() { // "of" => { // bump!(self); // // self.input.skip_ws()?; // // // TODO: fix me // selector_list = Some(self.parse_selectors()?); // } // _ => {} // } // } // _ => {} // } Ok(nth) } fn parse_pseudo_class_selector(&mut self) -> PResult<PseudoClassSelector> { let span = self.input.cur_span()?; expect!(self, ":"); // `:` if is!(self, Function) { let fn_span = self.input.cur_span()?; let name = bump!(self); let names = match name { Token::Function { value, raw } => (value, raw), _ => unreachable!(), }; let children = match &*names.0.to_ascii_lowercase() { "nth-child" | "nth-last-child" | "nth-of-type" | "nth-last-of-type" => { let state = self.input.state(); let nth = self.parse_nth(); match nth { Ok(nth) => PseudoSelectorChildren::Nth(nth), Err(_) => { self.input.reset(&state); PseudoSelectorChildren::Tokens(self.parse_any_value(false)?) } } } _ => PseudoSelectorChildren::Tokens(self.parse_any_value(false)?), }; expect!(self, ")"); return Ok(PseudoClassSelector { span: span!(self, span.lo), name: Ident { span: Span::new(fn_span.lo, fn_span.hi - BytePos(1), Default::default()), value: names.0, raw: names.1, }, children: Some(children), }); } else if is!(self, Ident) { let ident_span = self.input.cur_span()?; let value = bump!(self); let values = match value { Token::Ident { value, raw } => (value, raw), _ => unreachable!(), }; return Ok(PseudoClassSelector { span: span!(self, span.lo), name: Ident { span: ident_span, value: values.0, raw: values.1, }, children: None, }); } let span = self.input.cur_span()?; return Err(Error::new(span, ErrorKind::InvalidSelector)); } fn parse_pseudo_element_selector(&mut self) -> PResult<PseudoElementSelector> { let span = self.input.cur_span()?; expect!(self, ":"); // `:` expect!(self, ":"); // `:` if is!(self, Function) { let fn_span = self.input.cur_span()?; let name = bump!(self); let names = match name { Token::Function { value, raw } => (value, raw), _ => unreachable!(), }; let children = self.parse_any_value(false)?; expect!(self, ")"); return Ok(PseudoElementSelector { span: span!(self, span.lo), name: Ident { span: Span::new(fn_span.lo, fn_span.hi - BytePos(1), Default::default()), value: names.0, raw: names.1, }, children: Some(children), }); } else if is!(self, Ident) { let ident_span = self.input.cur_span()?; let value = bump!(self); let values = match value { Token::Ident { value, raw } => (value, raw), _ => unreachable!(), }; return Ok(PseudoElementSelector { span: span!(self, span.lo), name: Ident { span: ident_span, value: values.0, raw: values.1, }, children: None, }); } let span = self.input.cur_span()?; return Err(Error::new(span, ErrorKind::InvalidSelector)); } fn parse_compound_selector(&mut self) -> PResult<CompoundSelector> { let span = self.input.cur_span()?; let start_pos = span.lo; let mut nesting_selector = None; // TODO: move under option, because it is draft // This is an extension: https://drafts.csswg.org/css-nesting-1/ if eat!(self, "&") { nesting_selector = Some(NestingSelector { span: span!(self, start_pos), }); } let type_selector = self.parse_type_selector().unwrap(); let mut subclass_selectors = vec![]; 'subclass_selectors: loop { if is!(self, EOF) { break; } match cur!(self) { Token::Hash { is_id, .. } => { if !*is_id { break 'subclass_selectors; } subclass_selectors.push(self.parse_id_selector()?.into()); } tok!(".") => { subclass_selectors.push(self.parse_class_selector()?.into()); } tok!("[") => { let attr = self.parse_attribute_selector()?; subclass_selectors.push(attr.into()); } tok!(":") => { if peeked_is!(self, ":") { while is!(self, ":") { let pseudo_element = self.parse_pseudo_element_selector()?; subclass_selectors.push(pseudo_element.into()); } break 'subclass_selectors; } let pseudo_class = self.parse_pseudo_class_selector()?; subclass_selectors.push(pseudo_class.into()); } Token::AtKeyword { .. } if self.ctx.allow_at_selector => { let values = match bump!(self) { Token::AtKeyword { value, raw } => (value, raw), _ => { unreachable!() } }; subclass_selectors.push(SubclassSelector::At(AtSelector { span, text: Ident { span, value: values.0, raw: values.1, }, })); break 'subclass_selectors; } _ => { break 'subclass_selectors; } } } let span = span!(self, start_pos); if nesting_selector.is_none() && type_selector.is_none() && subclass_selectors.len() == 0 { return Err(Error::new(span, ErrorKind::InvalidSelector)); } Ok(CompoundSelector { span, nesting_selector, type_selector, subclass_selectors, }) } } impl<I> Parse<SelectorList> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<SelectorList> { self.parse_selectors() } } impl<I> Parse<ComplexSelector> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<ComplexSelector> { self.parse_complex_selector() } }
31.654388
134
0.3857
2197c68e913071110302697eb47259a6c007994b
1,108
use crate::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] enum List { Cons(i32, RefCell<Rc<List>>), Nil, } impl List { fn tail(&self) -> Option<&RefCell<Rc<List>>> { match self { Cons(_, item) => Some(item), Nil => None, } } } fn main() { let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); println!("a initial rc count = {}", Rc::strong_count(&a)); println!("a next item = {:?}", a.tail()); let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a)))); println!("a rc count after b creation = {}", Rc::strong_count(&a)); println!("b initial rc count = {}", Rc::strong_count(&b)); println!("b next item = {:?}", b.tail()); if let Some(link) = a.tail() { *link.borrow_mut() = Rc::clone(&b); } println!("b rc count after changing a = {}", Rc::strong_count(&b)); println!("a rc count after changing a = {}", Rc::strong_count(&a)); // Uncomment the next line to see that we have a cycle; it will overflow the stack //println!("a next item = {:?}", a.tail()); }
26.380952
86
0.542419
912d146ab0e59e757d5e9778e7c56a7477a8316b
1,209
use azure_core::prelude::*; use azure_storage::core::prelude::*; use futures::stream::StreamExt; use std::error::Error; use std::sync::Arc; #[tokio::main] async fn main() -> Result<(), Box<dyn Error + Sync + Send>> { let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let container = std::env::args() .nth(1) .expect("please specify container name as command line parameter"); let http_client: Arc<Box<dyn HttpClient>> = Arc::new(Box::new(reqwest::Client::new())); let container = StorageAccountClient::new_access_key(http_client.clone(), &account, &master_key) .as_storage_client() .as_container_client(&container); let mut count: usize = 0; let mut list_blobs = Box::pin(container.list_blobs().stream()); while let Some(list_blobs_response) = list_blobs.next().await { let list_blobs_response = list_blobs_response?; count += list_blobs_response.incomplete_vector.vector.len(); } println!("blob count {}", count); Ok(()) }
34.542857
97
0.658395
d5feaec68b4de1dee8c8461e05068637f486e1bc
5,644
use ring::aead; use ring::rand::*; use ring::digest; use ring::pbkdf2; use base64::encode; use base64::decode; use std::str::from_utf8; static ALGORITHM_NAME: &'static aead::Algorithm = &aead::AES_128_GCM; const ALGORITHM_NONCE_SIZE: usize = 12; const ALGORITHM_TAG_SIZE: usize = 16; const ALGORITHM_KEY_SIZE: usize = 16; static PBKDF2_NAME: &'static digest::Algorithm = &digest::SHA256; const PBKDF2_SALT_SIZE: usize = 16; const PBKDF2_ITERATIONS: u32 = 32767; pub fn encrypt_string(plaintext: &String, password: &String) -> Option<String> { // Generate a 128-bit salt using a CSPRNG. let rand_provider: SystemRandom = SystemRandom::new(); let mut salt: [u8; PBKDF2_SALT_SIZE] = [0; PBKDF2_SALT_SIZE]; let err = rand_provider.fill(&mut salt); if err.is_err() { return None; } // Derive a key using PBKDF2. let mut key: [u8; ALGORITHM_KEY_SIZE] = [0; ALGORITHM_KEY_SIZE]; pbkdf2::derive(PBKDF2_NAME, PBKDF2_ITERATIONS, &salt, password.as_bytes(), &mut key); // Encrypt and prepend salt. let mut ciphertext_and_nonce: Vec<u8> = vec![0; plaintext.len() + ALGORITHM_NONCE_SIZE + ALGORITHM_TAG_SIZE]; let size = match encrypt(plaintext.as_bytes(), &key, ciphertext_and_nonce.as_mut_slice()) { Some(size) => size, None => return None }; let mut ciphertext_and_nonce_and_salt: Vec<u8> = vec![0; ciphertext_and_nonce.len() + salt.len()]; ciphertext_and_nonce_and_salt[..PBKDF2_SALT_SIZE].copy_from_slice(&salt); ciphertext_and_nonce_and_salt[PBKDF2_SALT_SIZE..].copy_from_slice(&ciphertext_and_nonce[..size]); // Return as base64 string. return Some(encode(&ciphertext_and_nonce_and_salt[..])); } pub fn decrypt_string(base64_ciphertext_and_nonce_and_salt: &String, password: &String) -> Option<String> { // Decode the base64. let ciphertext_and_nonce_and_salt: Vec<u8> = match decode(base64_ciphertext_and_nonce_and_salt.as_bytes()) { Ok(r) => r, Err(_) => return None }; // Get slices of salt and ciphertext_and_nonce. let salt: &[u8] = &ciphertext_and_nonce_and_salt[..PBKDF2_SALT_SIZE]; let ciphertext_and_nonce: &[u8] = &ciphertext_and_nonce_and_salt[PBKDF2_SALT_SIZE..]; // Derive the key using PBKDF2. let mut key: [u8; ALGORITHM_KEY_SIZE] = [0; ALGORITHM_KEY_SIZE]; pbkdf2::derive(PBKDF2_NAME, PBKDF2_ITERATIONS, &salt, password.as_bytes(), &mut key); // Decrypt and return result. let mut plaintext: Vec<u8> = vec![0; ciphertext_and_nonce.len() - ALGORITHM_NONCE_SIZE]; let size = match decrypt(ciphertext_and_nonce, &key, &mut plaintext) { Some(size) => size, None => return None }; let result = match from_utf8(&plaintext[..size]) { Ok(r) => String::from(r), Err(_) => return None }; return Some(result); } pub fn encrypt(plaintext: &[u8], key: &[u8], ciphertext_and_nonce: &mut [u8]) -> Option<usize> { // Panic if ciphertext_and_nonce is not large enough. let minimum_size: usize = plaintext.len() + ALGORITHM_NONCE_SIZE + ALGORITHM_TAG_SIZE; if ciphertext_and_nonce.len() < minimum_size { panic!("Expected ciphertext_and_nonce to be at least {} bytes in size, but was {}", minimum_size, ciphertext_and_nonce.len()); } // Generate a 96-bit nonce using a CSPRNG. let rand_provider: SystemRandom = SystemRandom::new(); let mut nonce: [u8; ALGORITHM_NONCE_SIZE] = [0; ALGORITHM_NONCE_SIZE]; let err = rand_provider.fill(&mut nonce); if err.is_err() { return None; } // Create a sealing key from key. let sealing_key = match aead::SealingKey::new(ALGORITHM_NAME, key) { Ok(k) => k, Err(_) => return None }; // We don't have any additional data. let ad: [u8; 0] = [ ]; // Copy plaintext to ciphertext_and_nonce to use as in_out. ciphertext_and_nonce[ALGORITHM_NONCE_SIZE..plaintext.len() + ALGORITHM_NONCE_SIZE].copy_from_slice(plaintext); // Perform encryption. let result = aead::seal_in_place(&sealing_key, &nonce, &ad, &mut ciphertext_and_nonce[ALGORITHM_NONCE_SIZE..], ALGORITHM_TAG_SIZE); if result.is_err() { return None; } // Prepend nonce. ciphertext_and_nonce[..ALGORITHM_NONCE_SIZE].copy_from_slice(&nonce); return Some(plaintext.len() + ALGORITHM_NONCE_SIZE + ALGORITHM_TAG_SIZE); } pub fn decrypt(ciphertext_and_nonce: &[u8], key: &[u8], plaintext: &mut [u8]) -> Option<usize> { // Panic if plaintext is not large enough. let minimum_size: usize = ciphertext_and_nonce.len() - ALGORITHM_NONCE_SIZE; if plaintext.len() < minimum_size { panic!("Expected plaintext to be at least {} bytes in size, but was {}", minimum_size, plaintext.len()); } // Retrieve the nonce. let mut nonce: [u8; ALGORITHM_NONCE_SIZE] = [0; ALGORITHM_NONCE_SIZE]; nonce[..].copy_from_slice(&ciphertext_and_nonce[..ALGORITHM_NONCE_SIZE]); // Put the ciphertext into plaintext to use as in_out. let ciphertext_with_tag = &ciphertext_and_nonce[ALGORITHM_NONCE_SIZE..]; let ciphertext_with_tag_len = ciphertext_with_tag.len(); plaintext.copy_from_slice(ciphertext_with_tag); // We don't have any additional data. let ad: [u8; 0] = [ ]; // Create a opening key from key. let opening_key = match aead::OpeningKey::new(ALGORITHM_NAME, key) { Ok(k) => k, Err(_) => return None }; // Perform decryption. let result = aead::open_in_place(&opening_key, &nonce, &ad, 0, plaintext); if result.is_err() { return None; } return Some(ciphertext_with_tag_len - ALGORITHM_TAG_SIZE); }
38.394558
135
0.685152
2169957995819bc856c68112ea853955a0488270
21,407
//! Serial use core::fmt; use core::marker::PhantomData; use core::ptr; use embedded_hal::prelude::*; use embedded_hal::serial; use nb::block; use crate::stm32::rcc::d2ccip2r; use crate::stm32::usart1::cr1::{M0W, PCEW, PSW}; use crate::stm32::{USART1, USART2, USART3, USART6}; use crate::stm32::{UART4, UART5, UART7, UART8}; use crate::gpio::gpioa::{ PA0, PA1, PA10, PA11, PA12, PA15, PA2, PA3, PA4, PA8, PA9, }; use crate::gpio::gpiob::{ PB10, PB11, PB12, PB13, PB14, PB15, PB3, PB4, PB5, PB6, PB7, PB8, PB9, }; use crate::gpio::gpioc::{PC10, PC11, PC12, PC6, PC7, PC8}; use crate::gpio::gpiod::{PD0, PD1, PD10, PD2, PD5, PD6, PD7, PD8, PD9}; use crate::gpio::gpioe::{PE0, PE1, PE7, PE8}; use crate::gpio::gpiof::{PF6, PF7}; use crate::gpio::gpiog::{PG14, PG7, PG9}; use crate::gpio::gpioh::{PH13, PH14}; use crate::gpio::gpioi::PI9; use crate::gpio::gpioj::{PJ8, PJ9}; use crate::gpio::{Alternate, AF11, AF14, AF4, AF6, AF7, AF8}; use crate::rcc::Ccdr; use crate::time::Hertz; use crate::Never; /// Serial error #[derive(Debug)] pub enum Error { /// Framing error Framing, /// Noise error Noise, /// RX buffer overrun Overrun, /// Parity check error Parity, #[doc(hidden)] _Extensible, } /// Interrupt event pub enum Event { /// New data has been received Rxne, /// New data can be sent Txe, /// Idle line state detected Idle, } pub mod config { use crate::time::Bps; use crate::time::U32Ext; pub enum WordLength { DataBits8, DataBits9, } pub enum Parity { ParityNone, ParityEven, ParityOdd, } pub enum StopBits { #[doc = "1 stop bit"] STOP1, #[doc = "0.5 stop bits"] STOP0P5, #[doc = "2 stop bits"] STOP2, #[doc = "1.5 stop bits"] STOP1P5, } pub struct Config { pub baudrate: Bps, pub wordlength: WordLength, pub parity: Parity, pub stopbits: StopBits, } impl Config { pub fn baudrate(mut self, baudrate: Bps) -> Self { self.baudrate = baudrate; self } pub fn parity_none(mut self) -> Self { self.parity = Parity::ParityNone; self } pub fn parity_even(mut self) -> Self { self.parity = Parity::ParityEven; self } pub fn parity_odd(mut self) -> Self { self.parity = Parity::ParityOdd; self } pub fn wordlength_8(mut self) -> Self { self.wordlength = WordLength::DataBits8; self } pub fn wordlength_9(mut self) -> Self { self.wordlength = WordLength::DataBits9; self } pub fn stopbits(mut self, stopbits: StopBits) -> Self { self.stopbits = stopbits; self } } #[derive(Debug)] pub struct InvalidConfig; impl Default for Config { fn default() -> Config { let baudrate = 19_200_u32.bps(); Config { baudrate, wordlength: WordLength::DataBits8, parity: Parity::ParityNone, stopbits: StopBits::STOP1, } } } } pub trait Pins<USART> {} pub trait PinTx<USART> {} pub trait PinRx<USART> {} pub trait PinCk<USART> {} impl<USART, TX, RX> Pins<USART> for (TX, RX) where TX: PinTx<USART>, RX: PinRx<USART>, { } /// A filler type for when the Tx pin is unnecessary pub struct NoTx; /// A filler type for when the Rx pin is unnecessary pub struct NoRx; /// A filler type for when the Ck pin is unnecessary pub struct NoCk; macro_rules! usart_pins { ($($USARTX:ty: TX: [$($TX:ty),*] RX: [$($RX:ty),*] CK: [$($CK:ty),*])+) => { $( $( impl PinTx<$USARTX> for $TX {} )* $( impl PinRx<$USARTX> for $RX {} )* $( impl PinCk<$USARTX> for $CK {} )* )+ } } macro_rules! uart_pins { ($($UARTX:ty: TX: [$($TX:ty),*] RX: [$($RX:ty),*])+) => { $( $( impl PinTx<$UARTX> for $TX {} )* $( impl PinRx<$UARTX> for $RX {} )* )+ } } usart_pins! { USART1: TX: [ NoTx, PA9<Alternate<AF7>>, PB6<Alternate<AF7>>, PB14<Alternate<AF4>> ] RX: [ NoRx, PA10<Alternate<AF7>>, PB7<Alternate<AF7>>, PB15<Alternate<AF4>> ] CK: [ NoCk, PA8<Alternate<AF7>> ] USART2: TX: [ NoTx, PA2<Alternate<AF7>>, PD5<Alternate<AF7>> ] RX: [ NoRx, PA3<Alternate<AF7>>, PD6<Alternate<AF7>> ] CK: [ NoCk, PA4<Alternate<AF7>>, PD7<Alternate<AF7>> ] USART3: TX: [ NoTx, PB10<Alternate<AF7>>, PC10<Alternate<AF7>>, PD8<Alternate<AF7>> ] RX: [ NoRx, PB11<Alternate<AF7>>, PC11<Alternate<AF7>>, PD9<Alternate<AF7>> ] CK: [ NoCk, PB12<Alternate<AF7>>, PC12<Alternate<AF7>>, PD10<Alternate<AF7>> ] USART6: TX: [ NoTx, PC6<Alternate<AF7>>, PG14<Alternate<AF7>> ] RX: [ NoRx, PC7<Alternate<AF7>>, PG9<Alternate<AF7>> ] CK: [ NoCk, PC8<Alternate<AF7>>, PG7<Alternate<AF7>> ] } uart_pins! { UART4: TX: [ NoTx, PA0<Alternate<AF8>>, PA12<Alternate<AF6>>, PB9<Alternate<AF8>>, PC10<Alternate<AF8>>, PD1<Alternate<AF8>>, PH13<Alternate<AF8>> ] RX: [ NoRx, PA1<Alternate<AF8>>, PA11<Alternate<AF6>>, PB8<Alternate<AF8>>, PC11<Alternate<AF8>>, PD0<Alternate<AF8>>, PH14<Alternate<AF8>>, PI9<Alternate<AF8>> ] UART5: TX: [ NoTx, PB6<Alternate<AF14>>, PB13<Alternate<AF14>>, PC12<Alternate<AF8>> ] RX: [ NoRx, PB5<Alternate<AF14>>, PB12<Alternate<AF14>>, PD2<Alternate<AF8>> ] UART7: TX: [ NoTx, PA15<Alternate<AF11>>, PB4<Alternate<AF11>>, PE8<Alternate<AF7>>, PF7<Alternate<AF7>> ] RX: [ NoRx, PA8<Alternate<AF11>>, PB3<Alternate<AF11>>, PE7<Alternate<AF7>>, PF6<Alternate<AF7>> ] UART8: TX: [ NoTx, PE1<Alternate<AF8>>, PJ8<Alternate<AF8>> ] RX: [ NoRx, PE0<Alternate<AF8>>, PJ9<Alternate<AF8>> ] } /// Serial abstraction pub struct Serial<USART, PINS> { usart: USART, pins: PINS, } /// Serial receiver pub struct Rx<USART> { _usart: PhantomData<USART>, } /// Serial transmitter pub struct Tx<USART> { _usart: PhantomData<USART>, } pub trait SerialExt<USART> { fn usart<PINS>( self, pins: PINS, config: config::Config, ccdr: &mut Ccdr, ) -> Result<Serial<USART, PINS>, config::InvalidConfig> where PINS: Pins<USART>; } macro_rules! usart { ($( $USARTX:ident: ($usartX:ident, $apb:ident, $usartXen:ident, $usartXrst:ident, $pclkX:ident), )+) => { $( /// Configures a USART peripheral to provide serial /// communication impl<PINS> Serial<$USARTX, PINS> { pub fn $usartX( usart: $USARTX, pins: PINS, config: config::Config, ccdr: &mut Ccdr, ) -> Result<Self, config::InvalidConfig> where PINS: Pins<$USARTX>, { use crate::stm32::usart1::cr2::STOPW; use self::config::*; // Enable clock for USART and reset ccdr.$apb.enr().modify(|_, w| w.$usartXen().enabled()); ccdr.$apb.rstr().modify(|_, w| w.$usartXrst().set_bit()); ccdr.$apb.rstr().modify(|_, w| w.$usartXrst().clear_bit()); // Get kernel clock let usart_ker_ck = match Self::kernel_clk(ccdr) { Some(ker_hz) => ker_hz.0, _ => panic!("$USARTX kernel clock not running!") }; // Prescaler not used for now let usart_ker_ck_presc = usart_ker_ck; usart.presc.reset(); // Calculate baudrate divisor let usartdiv = usart_ker_ck_presc / config.baudrate.0; assert!(usartdiv <= 65_536); // 16 times oversampling, OVER8 = 0 let brr = usartdiv as u16; usart.brr.write(|w| { w.brr().bits(brr) }); // disable hardware flow control // TODO enable DMA // usart.cr3.write(|w| w.rtse().clear_bit().ctse().clear_bit()); // Reset registers to disable advanced USART features usart.cr2.reset(); usart.cr3.reset(); // Set stop bits usart.cr2.write(|w| { w.stop().variant(match config.stopbits { StopBits::STOP0P5 => STOPW::STOP0P5, StopBits::STOP1 => STOPW::STOP1, StopBits::STOP1P5 => STOPW::STOP1P5, StopBits::STOP2 => STOPW::STOP2, }) }); // Enable transmission and receiving // and configure frame usart.cr1.write(|w| { w.fifoen() .set_bit() // FIFO mode enabled .over8() .oversampling16() // Oversampling by 16 .ue() .enabled() .te() .enabled() .re() .enabled() .m1() .clear_bit() .m0() .variant(match config.wordlength { WordLength::DataBits8 => M0W::BIT8, WordLength::DataBits9 => M0W::BIT9, }).pce() .variant(match config.parity { Parity::ParityNone => PCEW::DISABLED, _ => PCEW::ENABLED, }).ps() .variant(match config.parity { Parity::ParityOdd => PSW::EVEN, _ => PSW::ODD, }) }); Ok(Serial { usart, pins }) } /// Starts listening for an interrupt event pub fn listen(&mut self, event: Event) { match event { Event::Rxne => { self.usart.cr1.modify(|_, w| w.rxneie().enabled()) }, Event::Txe => { self.usart.cr1.modify(|_, w| w.txeie().enabled()) }, Event::Idle => { self.usart.cr1.modify(|_, w| w.idleie().enabled()) }, } } /// Stop listening for an interrupt event pub fn unlisten(&mut self, event: Event) { match event { Event::Rxne => { self.usart.cr1.modify(|_, w| w.rxneie().disabled()) }, Event::Txe => { self.usart.cr1.modify(|_, w| w.txeie().disabled()) }, Event::Idle => { self.usart.cr1.modify(|_, w| w.idleie().disabled()) }, } } /// Return true if the line idle status is set pub fn is_idle(& self) -> bool { unsafe { (*$USARTX::ptr()).isr.read().idle().bit_is_set() } } /// Return true if the tx register is empty (and can accept data) pub fn is_txe(& self) -> bool { unsafe { (*$USARTX::ptr()).isr.read().txe().bit_is_set() } } /// Return true if the rx register is not empty (and can be read) pub fn is_rxne(& self) -> bool { unsafe { (*$USARTX::ptr()).isr.read().rxne().bit_is_set() } } pub fn split(self) -> (Tx<$USARTX>, Rx<$USARTX>) { ( Tx { _usart: PhantomData, }, Rx { _usart: PhantomData, }, ) } /// Releases the USART peripheral and associated pins pub fn release(self) -> ($USARTX, PINS) { // Wait until both TXFIFO and shift register are empty while self.usart.isr.read().tc().bit_is_clear() {} (self.usart, self.pins) } } impl SerialExt<$USARTX> for $USARTX { fn usart<PINS>(self, pins: PINS, config: config::Config, ccdr: &mut Ccdr) -> Result<Serial<$USARTX, PINS>, config::InvalidConfig> where PINS: Pins<$USARTX> { Serial::$usartX(self, pins, config, ccdr) } } impl<PINS> serial::Read<u8> for Serial<$USARTX, PINS> { type Error = Error; fn read(&mut self) -> nb::Result<u8, Error> { let mut rx: Rx<$USARTX> = Rx { _usart: PhantomData, }; rx.read() } } impl serial::Read<u8> for Rx<$USARTX> { type Error = Error; fn read(&mut self) -> nb::Result<u8, Error> { // NOTE(unsafe) atomic read with no side effects let isr = unsafe { (*$USARTX::ptr()).isr.read() }; // TODO clear errors in ICR Err(if isr.pe().bit_is_set() { nb::Error::Other(Error::Parity) } else if isr.fe().bit_is_set() { nb::Error::Other(Error::Framing) } else if isr.nf().bit_is_set() { nb::Error::Other(Error::Noise) } else if isr.ore().bit_is_set() { nb::Error::Other(Error::Overrun) } else if isr.rxne().bit_is_set() { // NOTE(read_volatile) see `write_volatile` below return Ok(unsafe { ptr::read_volatile(&(*$USARTX::ptr()).rdr as *const _ as *const _) }); } else { nb::Error::WouldBlock }) } } impl<PINS> serial::Write<u8> for Serial<$USARTX, PINS> { type Error = Never; fn flush(&mut self) -> nb::Result<(), Never> { let mut tx: Tx<$USARTX> = Tx { _usart: PhantomData, }; tx.flush() } fn write(&mut self, byte: u8) -> nb::Result<(), Never> { let mut tx: Tx<$USARTX> = Tx { _usart: PhantomData, }; tx.write(byte) } } impl serial::Write<u8> for Tx<$USARTX> { // NOTE(Void) See section "29.7 USART interrupts"; the // only possible errors during transmission are: clear // to send (which is disabled in this case) errors and // framing errors (which only occur in SmartCard // mode); neither of these apply to our hardware // configuration type Error = Never; fn flush(&mut self) -> nb::Result<(), Never> { // NOTE(unsafe) atomic read with no side effects let isr = unsafe { (*$USARTX::ptr()).isr.read() }; if isr.tc().bit_is_set() { Ok(()) } else { Err(nb::Error::WouldBlock) } } fn write(&mut self, byte: u8) -> nb::Result<(), Never> { // NOTE(unsafe) atomic read with no side effects let isr = unsafe { (*$USARTX::ptr()).isr.read() }; if isr.txe().bit_is_set() { // NOTE(unsafe) atomic write to stateless register // NOTE(write_volatile) 8-bit write that's not // possible through the svd2rust API unsafe { ptr::write_volatile( &(*$USARTX::ptr()).tdr as *const _ as *mut _, byte) } Ok(()) } else { Err(nb::Error::WouldBlock) } } } )+ } } macro_rules! usart16sel { ($($USARTX:ident,)+) => { $( impl<PINS> Serial<$USARTX, PINS> { /// Returns the frequency of the current kernel clock /// for USART1 and 6 fn kernel_clk(ccdr: &Ccdr) -> Option<Hertz> { match ccdr.rb.d2ccip2r.read().usart16sel() { d2ccip2r::USART16SELR::RCC_PCLK2 => Some(ccdr.clocks.pclk2()), d2ccip2r::USART16SELR::PLL2_Q => ccdr.clocks.pll2_q_ck(), d2ccip2r::USART16SELR::PLL3_Q => ccdr.clocks.pll3_q_ck(), d2ccip2r::USART16SELR::HSI_KER => ccdr.clocks.hsi_ck(), d2ccip2r::USART16SELR::CSI_KER => ccdr.clocks.csi_ck(), d2ccip2r::USART16SELR::LSE => unimplemented!(), _ => unreachable!(), } } } )+ } } macro_rules! usart234578sel { ($($USARTX:ident,)+) => { $( impl<PINS> Serial<$USARTX, PINS> { /// Returns the frequency of the current kernel clock /// for USART2/3, UART4/5/7/8 fn kernel_clk(ccdr: &Ccdr) -> Option<Hertz> { match ccdr.rb.d2ccip2r.read().usart234578sel() { d2ccip2r::USART234578SELR::RCC_PCLK1 => Some(ccdr.clocks.pclk1()), d2ccip2r::USART234578SELR::PLL2_Q => ccdr.clocks.pll2_q_ck(), d2ccip2r::USART234578SELR::PLL3_Q => ccdr.clocks.pll3_q_ck(), d2ccip2r::USART234578SELR::HSI_KER => ccdr.clocks.hsi_ck(), d2ccip2r::USART234578SELR::CSI_KER => ccdr.clocks.csi_ck(), d2ccip2r::USART234578SELR::LSE => unimplemented!(), _ => unreachable!(), } } } )+ } } usart! { USART1: (usart1, apb2, usart1en, usart1rst, pclk2), USART2: (usart2, apb1l, usart2en, usart2rst, pclk1), USART3: (usart3, apb1l, usart3en, usart3rst, pclk1), USART6: (usart6, apb2, usart6en, usart6rst, pclk2), UART4: (uart4, apb1l, uart4en, uart4rst, pclk1), UART5: (uart5, apb1l, uart5en, uart5rst, pclk1), UART7: (uart7, apb1l, uart7en, uart7rst, pclk1), UART8: (uart8, apb1l, uart8en, uart8rst, pclk1), } usart16sel! { USART1, USART6, } usart234578sel! { USART2, USART3, UART4, UART5, UART7, UART8, } impl<USART> fmt::Write for Tx<USART> where Tx<USART>: serial::Write<u8>, { fn write_str(&mut self, s: &str) -> fmt::Result { let _ = s.as_bytes().iter().map(|c| block!(self.write(*c))).last(); Ok(()) } }
30.757184
103
0.425655
ac3c42f53e0c564c55ad5da72ce05502cb7453c2
9,924
// Copyright 2014 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. //! Traits for working with Errors. //! //! # The `Error` trait //! //! `Error` is a trait representing the basic expectations for error values, //! i.e. values of type `E` in `Result<T, E>`. At a minimum, errors must provide //! a description, but they may optionally provide additional detail (via //! `Display`) and cause chain information: //! //! ``` //! use std::fmt::Display; //! //! trait Error: Display { //! fn description(&self) -> &str; //! //! fn cause(&self) -> Option<&Error> { None } //! } //! ``` //! //! The `cause` method is generally used when errors cross "abstraction //! boundaries", i.e. when a one module must report an error that is "caused" //! by an error from a lower-level module. This setup makes it possible for the //! high-level module to provide its own errors that do not commit to any //! particular implementation, but also reveal some of its implementation for //! debugging via `cause` chains. // A note about crates and the facade: // // Originally, the `Error` trait was defined in libcore, and the impls // were scattered about. However, coherence objected to this // arrangement, because to create the blanket impls for `Box` required // knowing that `&str: !Error`, and we have no means to deal with that // sort of conflict just now. Therefore, for the time being, we have // moved the `Error` trait into libstd. As we evolve a sol'n to the // coherence challenge (e.g., specialization, neg impls, etc) we can // reconsider what crate these items belong in. use any::TypeId; use boxed::Box; use convert::From; use fmt::{self, Debug, Display}; use marker::{Send, Sync, Reflect}; use mem::transmute; use num; use option::Option::{self, Some, None}; use result::Result::{self, Ok, Err}; use raw::TraitObject; use str; use string::{self, String}; use system; /// Base functionality for all errors in Rust. pub trait Error: Debug + Display + Reflect { /// A short description of the error. /// /// The description should not contain newlines or sentence-ending /// punctuation, to facilitate embedding in larger user-facing /// strings. fn description(&self) -> &str; /// The lower-level cause of this error, if any. fn cause(&self) -> Option<&Error> { None } /// Get the `TypeId` of `self` #[doc(hidden)] fn type_id(&self) -> TypeId where Self: 'static { TypeId::of::<Self>() } } impl<'a, E: Error + 'a> From<E> for Box<Error + 'a> { fn from(err: E) -> Box<Error + 'a> { Box::new(err) } } impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<Error + Send + Sync + 'a> { fn from(err: E) -> Box<Error + Send + Sync + 'a> { Box::new(err) } } impl From<String> for Box<Error + Send + Sync> { fn from(err: String) -> Box<Error + Send + Sync> { #[derive(Debug)] struct StringError(String); impl Error for StringError { fn description(&self) -> &str { &self.0 } } impl Display for StringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(&self.0, f) } } Box::new(StringError(err)) } } impl<'a, 'b> From<&'b str> for Box<Error + Send + Sync + 'a> { fn from(err: &'b str) -> Box<Error + Send + Sync + 'a> { From::from(String::from(err)) } } impl Error for str::ParseBoolError { fn description(&self) -> &str { "failed to parse bool" } } impl Error for str::Utf8Error { fn description(&self) -> &str { "invalid utf-8: corrupt contents" } } impl Error for num::ParseIntError { fn description(&self) -> &str { self.__description() } } #[cfg(not(disable_float))] impl Error for num::ParseFloatError { fn description(&self) -> &str { self.__description() } } impl Error for string::FromUtf8Error { fn description(&self) -> &str { "invalid utf-8" } } impl Error for string::FromUtf16Error { fn description(&self) -> &str { "invalid utf-16" } } impl Error for system::error::Error { fn description(&self) -> &str { self.text() } } // copied from any.rs impl Error + 'static { /// Returns true if the boxed type is the same as `T` #[inline] pub fn is<T: Error + 'static>(&self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[inline] pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(&*(to.data as *const T)) } } else { None } } /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[inline] pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(&mut *(to.data as *const T as *mut T)) } } else { None } } } impl Error + 'static + Send { /// Forwards to the method defined on the type `Any`. #[inline] pub fn is<T: Error + 'static>(&self) -> bool { <Error + 'static>::is::<T>(self) } /// Forwards to the method defined on the type `Any`. #[inline] pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> { <Error + 'static>::downcast_ref::<T>(self) } /// Forwards to the method defined on the type `Any`. #[inline] pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> { <Error + 'static>::downcast_mut::<T>(self) } } impl Error + 'static + Send + Sync { /// Forwards to the method defined on the type `Any`. #[inline] pub fn is<T: Error + 'static>(&self) -> bool { <Error + 'static>::is::<T>(self) } /// Forwards to the method defined on the type `Any`. #[inline] pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> { <Error + 'static>::downcast_ref::<T>(self) } /// Forwards to the method defined on the type `Any`. #[inline] pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> { <Error + 'static>::downcast_mut::<T>(self) } } impl Error { #[inline] /// Attempt to downcast the box to a concrete type. pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error>> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let raw = Box::into_raw(self); let to: TraitObject = transmute::<*mut Error, TraitObject>(raw); // Extract the data pointer Ok(Box::from_raw(to.data as *mut T)) } } else { Err(self) } } } impl Error + Send { #[inline] /// Attempt to downcast the box to a concrete type. pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error + Send>> { let err: Box<Error> = self; <Error>::downcast(err).map_err(|s| unsafe { // reapply the Send marker transmute::<Box<Error>, Box<Error + Send>>(s) }) } } impl Error + Send + Sync { #[inline] /// Attempt to downcast the box to a concrete type. pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> { let err: Box<Error> = self; <Error>::downcast(err).map_err(|s| unsafe { // reapply the Send+Sync marker transmute::<Box<Error>, Box<Error + Send + Sync>>(s) }) } } #[cfg(test)] mod tests { use prelude::v1::*; use super::Error; use fmt; #[derive(Debug, PartialEq)] struct A; #[derive(Debug, PartialEq)] struct B; impl fmt::Display for A { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "A") } } impl fmt::Display for B { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "B") } } impl Error for A { fn description(&self) -> &str { "A-desc" } } impl Error for B { fn description(&self) -> &str { "A-desc" } } #[test] fn downcasting() { let mut a = A; let mut a = &mut a as &mut (Error + 'static); assert_eq!(a.downcast_ref::<A>(), Some(&A)); assert_eq!(a.downcast_ref::<B>(), None); assert_eq!(a.downcast_mut::<A>(), Some(&mut A)); assert_eq!(a.downcast_mut::<B>(), None); let a: Box<Error> = Box::new(A); match a.downcast::<B>() { Ok(..) => panic!("expected error"), Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A), } } }
28.43553
95
0.562475
293b485d77f245c63f754df7fb6741211fa2a43c
738
use serde::Deserialize; use tabled::Tabled; use crate::util::deserialize::null_to_default; #[derive(Default, Debug, Deserialize)] #[serde(default)] pub struct ApiKeys { pub api_keys: Vec<ApiKey>, } #[derive(Tabled, Default, Debug, Deserialize)] #[serde(default)] pub struct ApiKey { #[serde(deserialize_with = "null_to_default")] pub description: String, #[serde(deserialize_with = "null_to_default")] pub id: u64, #[serde(deserialize_with = "null_to_default")] pub key: String, #[serde(deserialize_with = "null_to_default")] pub time_added: u64, #[serde(deserialize_with = "null_to_default")] pub user_id: u64, #[serde(deserialize_with = "null_to_default")] pub username: String, }
26.357143
50
0.695122
76cb00bca5983552a6fceea694fe1f352e8f0c6c
600
/* * Copyright Nick G. 2021. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at * https://www.boost.org/LICENSE_1_0.txt) */ use std::{fmt, io}; #[derive(Debug)] pub struct StatusError { pub message: String, } impl From<io::Error> for StatusError { fn from(err: io::Error) -> StatusError { StatusError { message: err.to_string(), } } } impl fmt::Display for StatusError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.message) } }
21.428571
61
0.588333
f9525029d7502d977ba7d97077be8d84b850e593
515
//! A crate for both interacting with SCSI devices as a host and for writing //! new SCSI device software/firmware. //! //! Currently the main focus of this crate is Bulk Only USB Mass Storage Device //! compatibility, since that comprises a significant chunk of use cases. However, //! more functionality can be requested and/or PRed as necessary or desired. #![warn(missing_docs)] #![cfg_attr(not(test), no_std)] extern crate byteorder; mod error; pub mod scsi; mod traits; pub use error::*; pub use traits::*;
30.294118
82
0.741748
f453047c4ce06de3d739b50f9e05e45e2a2b0555
14,365
use crate::{ crypto::keccak256, etl::collector::*, kv::{tables, traits::*}, models::*, stagedsync::{stage::*, stages::*}, stages::stage_util::should_do_clean_promotion, upsert_hashed_storage_value, }; use anyhow::format_err; use async_trait::async_trait; use std::sync::Arc; use tempfile::TempDir; use tokio::pin; use tokio_stream::StreamExt; use tracing::*; pub async fn promote_clean_accounts<'db, Tx>(txn: &Tx, temp_dir: &TempDir) -> anyhow::Result<()> where Tx: MutableTransaction<'db>, { txn.clear_table(tables::HashedAccount).await?; let mut collector_account = TableCollector::<tables::HashedAccount>::new(temp_dir, OPTIMAL_BUFFER_CAPACITY); let mut src = txn.cursor(tables::Account).await?; src.first().await?; let mut i = 0; let walker = walk(&mut src, None); pin!(walker); while let Some((address, account)) = walker.try_next().await? { collector_account.push(keccak256(address), account); i += 1; if i % 5_000_000 == 0 { debug!("Converted {} entries", i); } } debug!("Loading hashed entries"); let mut dst = txn.mutable_cursor(tables::HashedAccount.erased()).await?; collector_account.load(&mut dst).await?; Ok(()) } pub async fn promote_clean_storage<'db, Tx>(txn: &Tx, path: &TempDir) -> anyhow::Result<()> where Tx: MutableTransaction<'db>, { txn.clear_table(tables::HashedStorage).await?; let mut collector_storage = TableCollector::<tables::HashedStorage>::new(path, OPTIMAL_BUFFER_CAPACITY); let mut src = txn.cursor(tables::Storage).await?; src.first().await?; let mut i = 0; let walker = walk(&mut src, None); pin!(walker); while let Some((address, (location, value))) = walker.try_next().await? { collector_storage.push(keccak256(address), (keccak256(location), value)); i += 1; if i % 5_000_000 == 0 { debug!("Converted {} entries", i); } } debug!("Loading hashed entries"); let mut dst = txn.mutable_cursor(tables::HashedStorage.erased()).await?; collector_storage.load(&mut dst).await?; Ok(()) } async fn promote_accounts<'db, Tx>(tx: &Tx, stage_progress: BlockNumber) -> anyhow::Result<()> where Tx: MutableTransaction<'db>, { let mut changeset_table = tx.cursor(tables::AccountChangeSet).await?; let mut account_table = tx.cursor(tables::Account).await?; let mut target_table = tx.mutable_cursor(tables::HashedAccount).await?; let starting_block = stage_progress + 1; let walker = walk(&mut changeset_table, Some(starting_block)); pin!(walker); while let Some((_, tables::AccountChange { address, .. })) = walker.try_next().await? { let hashed_address = || keccak256(address); if let Some((_, account)) = account_table.seek_exact(address).await? { target_table.upsert((hashed_address)(), account).await?; } else if target_table.seek_exact((hashed_address)()).await?.is_some() { target_table.delete_current().await?; } } Ok(()) } async fn promote_storage<'db, Tx>(tx: &Tx, stage_progress: BlockNumber) -> anyhow::Result<()> where Tx: MutableTransaction<'db>, { let mut changeset_table = tx.cursor(tables::StorageChangeSet).await?; let mut storage_table = tx.cursor_dup_sort(tables::Storage).await?; let mut target_table = tx.mutable_cursor_dupsort(tables::HashedStorage).await?; let starting_block = stage_progress + 1; let walker = walk(&mut changeset_table, Some(starting_block)); pin!(walker); while let Some(( tables::StorageChangeKey { address, .. }, tables::StorageChange { location, .. }, )) = walker.try_next().await? { let hashed_address = keccak256(address); let hashed_location = keccak256(location); let mut v = U256::ZERO; if let Some((found_location, value)) = storage_table.seek_both_range(address, location).await? { if location == found_location { v = value; } } upsert_hashed_storage_value(&mut target_table, hashed_address, hashed_location, v).await?; } Ok(()) } #[derive(Debug)] pub struct HashState { temp_dir: Arc<TempDir>, clean_promotion_threshold: u64, } impl HashState { pub fn new(temp_dir: Arc<TempDir>, clean_promotion_threshold: Option<u64>) -> Self { Self { temp_dir, clean_promotion_threshold: clean_promotion_threshold .unwrap_or(30_000_000_u64 * 1_000_000_u64), } } } #[async_trait] impl<'db, RwTx> Stage<'db, RwTx> for HashState where RwTx: MutableTransaction<'db>, { fn id(&self) -> StageId { HASH_STATE } async fn execute<'tx>( &mut self, tx: &'tx mut RwTx, input: StageInput, ) -> anyhow::Result<ExecOutput> where 'db: 'tx, { let genesis = BlockNumber(0); let past_progress = input.stage_progress.unwrap_or(genesis); let max_block = input .previous_stage .ok_or_else(|| format_err!("Cannot be first stage"))? .1; if should_do_clean_promotion( tx, genesis, past_progress, max_block, self.clean_promotion_threshold, ) .await? { info!("Generating hashed accounts"); promote_clean_accounts(tx, &*self.temp_dir).await?; info!("Generating hashed storage"); promote_clean_storage(tx, &*self.temp_dir).await?; } else { info!("Incrementally hashing accounts"); promote_accounts(tx, past_progress).await?; info!("Incrementally hashing storage"); promote_storage(tx, past_progress).await?; } Ok(ExecOutput::Progress { stage_progress: max_block, done: true, }) } async fn unwind<'tx>( &mut self, tx: &'tx mut RwTx, input: UnwindInput, ) -> anyhow::Result<UnwindOutput> where 'db: 'tx, { info!("Unwinding hashed accounts"); let mut hashed_account_cur = tx.mutable_cursor(tables::HashedAccount).await?; let mut account_cs_cur = tx.cursor(tables::AccountChangeSet).await?; let walker = walk_back(&mut account_cs_cur, None); pin!(walker); while let Some((block_number, tables::AccountChange { address, account })) = walker.try_next().await? { if block_number > input.unwind_to { let hashed_address = keccak256(address); if let Some(account) = account { hashed_account_cur.put(hashed_address, account).await? } else if hashed_account_cur.seek(hashed_address).await?.is_some() { hashed_account_cur.delete_current().await? } } else { break; } } info!("Unwinding hashed storage"); let mut hashed_storage_cur = tx.mutable_cursor_dupsort(tables::HashedStorage).await?; let mut storage_cs_cur = tx.cursor(tables::StorageChangeSet).await?; let walker = walk_back(&mut storage_cs_cur, None); pin!(walker); while let Some(( tables::StorageChangeKey { block_number, address, }, tables::StorageChange { location, value }, )) = walker.try_next().await? { if block_number > input.unwind_to { let hashed_address = keccak256(address); let hashed_location = keccak256(location); upsert_hashed_storage_value( &mut hashed_storage_cur, hashed_address, hashed_location, value, ) .await?; } else { break; } } Ok(UnwindOutput { stage_progress: input.unwind_to, }) } } #[cfg(test)] mod tests { use super::*; use crate::{ execution::{address::*, *}, kv::new_mem_database, res::chainspec::MAINNET, u256_to_h256, Buffer, State, }; use hex_literal::*; use std::time::Instant; #[tokio::test] async fn stage_hashstate() { let db = new_mem_database().unwrap(); let mut tx = db.begin_mutable().await.unwrap(); let mut gas = 0; tx.set(tables::TotalGas, 0.into(), gas).await.unwrap(); let block_number = BlockNumber(1); let miner = hex!("5a0b54d5dc17e0aadc383d2db43b0a0d3e029c4c").into(); let gas_limit = 100_000; // This contract initially sets its 0th storage to 0x2a // and its 1st storage to 0x01c9. // When called, it updates its 0th storage to the input provided. let contract_code = hex!("600035600055").to_vec(); let deployment_code = hex!("602a6000556101c960015560068060166000396000f3").to_vec(); let sender = hex!("b685342b8c54347aad148e1f22eff3eb3eb29391").into(); let mut header = PartialHeader { number: block_number, beneficiary: miner, gas_limit, gas_used: 63_820, ..PartialHeader::empty() }; let transaction = move |nonce, value, action, input| MessageWithSender { message: Message::Legacy { chain_id: None, nonce, gas_price: U256::from(20 * GIGA), gas_limit, action, value, input, }, sender, }; let mut body = BlockBodyWithSenders { transactions: vec![(transaction)( 0, 0.as_u256(), TransactionAction::Create, deployment_code.into_iter().chain(contract_code).collect(), )], ommers: vec![], }; let mut buffer = Buffer::new(&tx, BlockNumber(0), None); let sender_account = Account { balance: ETHER.into(), ..Account::default() }; buffer.update_account(sender, None, Some(sender_account)); // --------------------------------------- // Execute first block // --------------------------------------- execute_block(&mut buffer, &MAINNET, &header, &body) .await .unwrap(); gas += header.gas_used; tx.set(tables::TotalGas, header.number, gas).await.unwrap(); let contract_address = create_address(sender, 0); // --------------------------------------- // Execute second block // --------------------------------------- let new_val = hex!("000000000000000000000000000000000000000000000000000000000000003e"); let block_number = BlockNumber(2); header.number = block_number; header.gas_used = 26_201; body.transactions = vec![(transaction)( 1, 1000.as_u256(), TransactionAction::Call(contract_address), new_val.to_vec().into(), )]; execute_block(&mut buffer, &MAINNET.clone(), &header, &body) .await .unwrap(); gas += header.gas_used; tx.set(tables::TotalGas, header.number, gas).await.unwrap(); // --------------------------------------- // Execute third block // --------------------------------------- let new_val = 0x3b; let block_number = BlockNumber(3); header.number = block_number; header.gas_used = 26_201; body.transactions = vec![(transaction)( 2, 1000.as_u256(), TransactionAction::Call(contract_address), u256_to_h256(new_val.as_u256()).0.to_vec().into(), )]; execute_block(&mut buffer, &MAINNET.clone(), &header, &body) .await .unwrap(); buffer.write_to_db().await.unwrap(); gas += header.gas_used; tx.set(tables::TotalGas, header.number, gas).await.unwrap(); // --------------------------------------- // Execute stage forward // --------------------------------------- assert_eq!( HashState { temp_dir: Arc::new(TempDir::new().unwrap()), clean_promotion_threshold: u64::MAX, } .execute( &mut tx, StageInput { restarted: false, first_started_at: (Instant::now(), None), previous_stage: Some((EXECUTION, BlockNumber(3))), stage_progress: None, }, ) .await .unwrap(), ExecOutput::Progress { stage_progress: BlockNumber(3), done: true, } ); // --------------------------------------- // Check hashed account // --------------------------------------- let mut hashed_address_table = tx.cursor(tables::HashedAccount).await.unwrap(); let sender_keccak = keccak256(sender); let (_, account) = hashed_address_table .seek_exact(sender_keccak) .await .unwrap() .unwrap(); assert_eq!(account.nonce, 3); assert!(account.balance < ETHER); // --------------------------------------- // Check hashed storage // --------------------------------------- let mut hashed_storage_cursor = tx.cursor(tables::HashedStorage).await.unwrap(); let k = keccak256(contract_address); let walker = walk(&mut hashed_storage_cursor, Some(k)); pin!(walker); for (location, expected_value) in [(0, new_val), (1, 0x01c9)] { let (wk, (hashed_location, value)) = walker.try_next().await.unwrap().unwrap(); assert_eq!(k, wk); assert_eq!(hashed_location, keccak256(u256_to_h256(location.as_u256()))); assert_eq!(value, expected_value.as_u256()); } assert!(walker.try_next().await.unwrap().is_none()); } }
31.160521
98
0.546606
bfe61b7d7f3c2cca14150c9accabd6705821442d
6,522
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Low-level module for establishing connections with peers //! //! The main component of this module is the [`Transport`] trait, which provides an interface for //! establishing both inbound and outbound connections with remote peers. The [`TransportExt`] //! trait contains a variety of combinators for modifying a transport allowing composability and //! layering of additional transports or protocols. //! //! [`Transport`]: crate::transport::Transport //! [`TransportExt`]: crate::transport::TransportExt use futures::{future::Future, stream::Stream}; use libra_network_address::NetworkAddress; use libra_types::PeerId; use serde::Serialize; use std::time::Duration; pub mod and_then; pub mod boxed; pub mod memory; pub mod tcp; pub mod timeout; /// Origin of how a Connection was established. #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Serialize)] pub enum ConnectionOrigin { /// `Inbound` indicates that we are the listener for this connection. Inbound, /// `Outbound` indicates that we are the dialer for this connection. Outbound, } /// A Transport is responsible for establishing connections with remote Peers. /// /// Connections are established either by [listening](Transport::listen_on) /// or [dialing](Transport::dial) on a [`Transport`]. A peer that /// obtains a connection by listening is often referred to as the *listener* and the /// peer that initiated the connection through dialing as the *dialer*. /// /// Additional protocols can be layered on top of the connections established /// by a [`Transport`] through utilizing the combinators in the [`TransportExt`] trait. pub trait Transport { /// The result of establishing a connection. /// /// Generally this would include a socket-like streams which allows for sending and receiving /// of data through the connection. type Output; /// The Error type of errors which can happen while establishing a connection. type Error: ::std::error::Error + Send + Sync + 'static; /// A stream of [`Inbound`](Transport::Inbound) connections and the address of the dialer. /// /// An item should be produced whenever a connection is received at the lowest level of the /// transport stack. Each item is an [`Inbound`](Transport::Inbound) future /// that resolves to an [`Output`](Transport::Output) value once all protocol upgrades /// have been applied. type Listener: Stream<Item = Result<(Self::Inbound, NetworkAddress), Self::Error>> + Send + Unpin; /// A pending [`Output`](Transport::Output) for an inbound connection, /// obtained from the [`Listener`](Transport::Listener) stream. /// /// After a connection has been accepted by the transport, it may need to go through /// asynchronous post-processing (i.e. protocol upgrade negotiations). Such /// post-processing should not block the `Listener` from producing the next /// connection, hence further connection setup proceeds asynchronously. /// Once a `Inbound` future resolves it yields the [`Output`](Transport::Output) /// of the connection setup process. type Inbound: Future<Output = Result<Self::Output, Self::Error>> + Send; /// A pending [`Output`](Transport::Output) for an outbound connection, /// obtained from [dialing](Transport::dial) stream. type Outbound: Future<Output = Result<Self::Output, Self::Error>> + Send; /// Listens on the given [`NetworkAddress`], returning a stream of incoming connections. /// /// The returned [`NetworkAddress`] is the actual listening address, this is done to take into /// account OS-assigned port numbers (e.g. listening on port 0). fn listen_on( &self, addr: NetworkAddress, ) -> Result<(Self::Listener, NetworkAddress), Self::Error> where Self: Sized; /// Dials the given [`NetworkAddress`], returning a future for a pending outbound connection. fn dial(&self, peer_id: PeerId, addr: NetworkAddress) -> Result<Self::Outbound, Self::Error> where Self: Sized; } impl<T: ?Sized> TransportExt for T where T: Transport {} /// An extension trait for [`Transport`]s that provides a variety of convenient /// combinators. /// /// Additional protocols or functionality can be layered on top of an existing /// [`Transport`] by using this extension trait. For example, one might want to /// take a raw connection and upgrade it to a secure transport followed by /// version handshake by chaining calls to [`and_then`](TransportExt::and_then). /// Each method yields a new [`Transport`] whose connection setup incorporates /// all earlier upgrades followed by the new upgrade, i.e. the order of the /// upgrades is significant. pub trait TransportExt: Transport { /// Turns a [`Transport`] into an abstract boxed transport. fn boxed(self) -> boxed::BoxedTransport<Self::Output, Self::Error> where Self: Sized + Send + 'static, Self::Listener: Send + 'static, Self::Inbound: Send + 'static, Self::Outbound: Send + 'static, { boxed::BoxedTransport::new(self) } /// Applies a function producing an asynchronous result to every connection /// created by this transport. /// /// This function can be used for ad-hoc protocol upgrades on a transport /// or for processing or adapting the output of an earlier upgrade. The /// provided function must take as input the output from the existing /// transport and a [`ConnectionOrigin`] which can be used to identify the /// origin of the connection (inbound vs outbound). fn and_then<F, Fut, O>(self, f: F) -> and_then::AndThen<Self, F> where Self: Sized, F: FnOnce(Self::Output, NetworkAddress, ConnectionOrigin) -> Fut + Clone, // Pin the error types to be the same for now // TODO don't require the error types to be the same Fut: Future<Output = Result<O, Self::Error>>, { and_then::AndThen::new(self, f) } /// Wraps a [`Transport`] with a timeout to the /// [Inbound](Transport::Inbound) and [Outbound](Transport::Outbound) /// connection futures. /// /// Note: The timeout does not apply to the [Listener](Transport::Listener) stream. fn with_timeout(self, timeout: Duration) -> timeout::TimeoutTransport<Self> where Self: Sized, { timeout::TimeoutTransport::new(self, timeout) } }
43.192053
98
0.691352
f47dcf0e9fd104b6e3360644b97fa1b459b70649
10,959
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use crate::deno_dir; use crate::file_fetcher::CacheSetting; use crate::file_fetcher::FileFetcher; use crate::flags; use crate::http_cache; use crate::import_map::ImportMap; use crate::lockfile::Lockfile; use crate::module_graph::CheckOptions; use crate::module_graph::GraphBuilder; use crate::module_graph::TranspileOptions; use crate::module_graph::TypeLib; use crate::source_maps::SourceMapGetter; use crate::specifier_handler::FetchHandler; use crate::version; use deno_runtime::inspector::InspectorServer; use deno_runtime::permissions::Permissions; use deno_core::error::anyhow; use deno_core::error::get_custom_error_class; use deno_core::error::AnyError; use deno_core::error::Context; use deno_core::resolve_url; use deno_core::url::Url; use deno_core::ModuleSource; use deno_core::ModuleSpecifier; use log::debug; use log::warn; use std::collections::HashMap; use std::env; use std::fs::read; use std::sync::Arc; use std::sync::Mutex; pub fn exit_unstable(api_name: &str) { eprintln!( "Unstable API '{}'. The --unstable flag must be provided.", api_name ); std::process::exit(70); } /// This structure represents state of single "deno" program. /// /// It is shared by all created workers (thus V8 isolates). pub struct ProgramState { /// Flags parsed from `argv` contents. pub flags: flags::Flags, pub dir: deno_dir::DenoDir, pub coverage_dir: Option<String>, pub file_fetcher: FileFetcher, pub modules: Arc<Mutex<HashMap<ModuleSpecifier, Result<ModuleSource, AnyError>>>>, pub lockfile: Option<Arc<Mutex<Lockfile>>>, pub maybe_import_map: Option<ImportMap>, pub maybe_inspector_server: Option<Arc<InspectorServer>>, pub ca_data: Option<Vec<u8>>, } impl ProgramState { pub async fn build(flags: flags::Flags) -> Result<Arc<Self>, AnyError> { let custom_root = env::var("DENO_DIR").map(String::into).ok(); let dir = deno_dir::DenoDir::new(custom_root)?; let deps_cache_location = dir.root.join("deps"); let http_cache = http_cache::HttpCache::new(&deps_cache_location); let ca_file = flags.ca_file.clone().or_else(|| env::var("DENO_CERT").ok()); let ca_data = match &ca_file { Some(ca_file) => Some(read(ca_file).context("Failed to open ca file")?), None => None, }; let cache_usage = if flags.cached_only { CacheSetting::Only } else if !flags.cache_blocklist.is_empty() { CacheSetting::ReloadSome(flags.cache_blocklist.clone()) } else if flags.reload { CacheSetting::ReloadAll } else { CacheSetting::Use }; let file_fetcher = FileFetcher::new( http_cache, cache_usage, !flags.no_remote, ca_data.clone(), )?; let lockfile = if let Some(filename) = &flags.lock { let lockfile = Lockfile::new(filename.clone(), flags.lock_write)?; Some(Arc::new(Mutex::new(lockfile))) } else { None }; let maybe_import_map: Option<ImportMap> = match flags.import_map_path.as_ref() { None => None, Some(import_map_url) => { let import_map_specifier = deno_core::resolve_url_or_path(&import_map_url).context( format!("Bad URL (\"{}\") for import map.", import_map_url), )?; let file = file_fetcher .fetch(&import_map_specifier, &Permissions::allow_all()) .await?; let import_map = ImportMap::from_json(import_map_specifier.as_str(), &file.source)?; Some(import_map) } }; let maybe_inspect_host = flags.inspect.or(flags.inspect_brk); let maybe_inspector_server = maybe_inspect_host.map(|host| { Arc::new(InspectorServer::new(host, version::get_user_agent())) }); let coverage_dir = flags .coverage_dir .clone() .or_else(|| env::var("DENO_UNSTABLE_COVERAGE_DIR").ok()); let program_state = ProgramState { dir, coverage_dir, flags, file_fetcher, modules: Default::default(), lockfile, maybe_import_map, maybe_inspector_server, ca_data, }; Ok(Arc::new(program_state)) } /// This function is called when new module load is /// initialized by the JsRuntime. Its resposibility is to collect /// all dependencies and if it is required then also perform TS typecheck /// and traspilation. pub async fn prepare_module_load( self: &Arc<Self>, specifier: ModuleSpecifier, lib: TypeLib, runtime_permissions: Permissions, is_dynamic: bool, maybe_import_map: Option<ImportMap>, ) -> Result<(), AnyError> { let specifier = specifier.clone(); // Workers are subject to the current runtime permissions. We do the // permission check here early to avoid "wasting" time building a module // graph for a module that cannot be loaded. if lib == TypeLib::DenoWorker || lib == TypeLib::UnstableDenoWorker { runtime_permissions.check_specifier(&specifier)?; } let handler = Arc::new(Mutex::new(FetchHandler::new(self, runtime_permissions)?)); let mut builder = GraphBuilder::new(handler, maybe_import_map, self.lockfile.clone()); builder.add(&specifier, is_dynamic).await?; let mut graph = builder.get_graph(); let debug = self.flags.log_level == Some(log::Level::Debug); let maybe_config_path = self.flags.config_path.clone(); let result_modules = if self.flags.no_check { let result_info = graph.transpile(TranspileOptions { debug, maybe_config_path, reload: self.flags.reload, })?; debug!("{}", result_info.stats); if let Some(ignored_options) = result_info.maybe_ignored_options { warn!("{}", ignored_options); } result_info.loadable_modules } else { let result_info = graph.check(CheckOptions { debug, emit: true, lib, maybe_config_path, reload: self.flags.reload, })?; debug!("{}", result_info.stats); if let Some(ignored_options) = result_info.maybe_ignored_options { eprintln!("{}", ignored_options); } if !result_info.diagnostics.is_empty() { return Err(anyhow!(result_info.diagnostics)); } result_info.loadable_modules }; let mut loadable_modules = self.modules.lock().unwrap(); loadable_modules.extend(result_modules); if let Some(ref lockfile) = self.lockfile { let g = lockfile.lock().unwrap(); g.write()?; } Ok(()) } pub fn load( &self, specifier: ModuleSpecifier, maybe_referrer: Option<ModuleSpecifier>, ) -> Result<ModuleSource, AnyError> { let modules = self.modules.lock().unwrap(); modules .get(&specifier) .map(|r| match r { Ok(module_source) => Ok(module_source.clone()), Err(err) => { // TODO(@kitsonk) this feels a bit hacky but it works, without // introducing another enum to have to try to deal with. if get_custom_error_class(err) == Some("NotFound") { let message = if let Some(referrer) = &maybe_referrer { format!("{}\n From: {}\n If the source module contains only types, use `import type` and `export type` to import it instead.", err, referrer) } else { format!("{}\n If the source module contains only types, use `import type` and `export type` to import it instead.", err) }; warn!("{}: {}", crate::colors::yellow("warning"), message); Ok(ModuleSource { code: "".to_string(), module_url_found: specifier.to_string(), module_url_specified: specifier.to_string(), }) } else { // anyhow errors don't support cloning, so we have to manage this // ourselves Err(anyhow!(err.to_string())) } }, }) .unwrap_or_else(|| { if let Some(referrer) = maybe_referrer { Err(anyhow!( "Module \"{}\" is missing from the graph.\n From: {}", specifier, referrer )) } else { Err(anyhow!( "Module \"{}\" is missing from the graph.", specifier )) } }) } // TODO(@kitsonk) this should be refactored to get it from the module graph fn get_emit(&self, url: &Url) -> Option<(Vec<u8>, Option<Vec<u8>>)> { match url.scheme() { // we should only be looking for emits for schemes that denote external // modules, which the disk_cache supports "wasm" | "file" | "http" | "https" | "data" => (), _ => { return None; } } let emit_path = self .dir .gen_cache .get_cache_filename_with_extension(&url, "js")?; let emit_map_path = self .dir .gen_cache .get_cache_filename_with_extension(&url, "js.map")?; if let Ok(code) = self.dir.gen_cache.get(&emit_path) { let maybe_map = if let Ok(map) = self.dir.gen_cache.get(&emit_map_path) { Some(map) } else { None }; Some((code, maybe_map)) } else { None } } } // TODO(@kitsonk) this is only temporary, but should be refactored to somewhere // else, like a refactored file_fetcher. impl SourceMapGetter for ProgramState { fn get_source_map(&self, file_name: &str) -> Option<Vec<u8>> { if let Ok(specifier) = resolve_url(file_name) { if let Some((code, maybe_map)) = self.get_emit(&specifier) { let code = String::from_utf8(code).unwrap(); source_map_from_code(code).or(maybe_map) } else if let Ok(source) = self.load(specifier, None) { source_map_from_code(source.code) } else { None } } else { None } } fn get_source_line( &self, file_name: &str, line_number: usize, ) -> Option<String> { if let Ok(specifier) = resolve_url(file_name) { self.file_fetcher.get_source(&specifier).map(|out| { // Do NOT use .lines(): it skips the terminating empty line. // (due to internally using .split_terminator() instead of .split()) let lines: Vec<&str> = out.source.split('\n').collect(); assert!(lines.len() > line_number); lines[line_number].to_string() }) } else { None } } } fn source_map_from_code(code: String) -> Option<Vec<u8>> { let lines: Vec<&str> = code.split('\n').collect(); if let Some(last_line) = lines.last() { if last_line .starts_with("//# sourceMappingURL=data:application/json;base64,") { let input = last_line.trim_start_matches( "//# sourceMappingURL=data:application/json;base64,", ); let decoded_map = base64::decode(input) .expect("Unable to decode source map from emitted file."); Some(decoded_map) } else { None } } else { None } }
32.04386
159
0.627612
aceebaa287605e373102d3bc80cac6cedfc77d7a
534
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. // // A test that uses a widened summary. //use mirai_annotations::*; fn fact(n: u8) -> u128 { if n == 0 { 1 } else { let n1fac = fact(n - 1); //assume!(n1fac <= std::u128::MAX / (n as u128)); (n as u128) * n1fac //~ possible attempt to multiply with overflow } } pub fn main() { let _x = fact(10); }
22.25
74
0.589888
899d945b63ac1c9d9a06e8ed578906e1a8825c4d
22,391
use crate::error::{MetricsResult, StorageError}; use crate::ir::{TsPoint, TsValue}; use crate::IntoPoint; use chrono::offset::Utc; use chrono::DateTime; use log::{error, trace}; use reqwest::header::{HeaderMap, HeaderValue, ACCEPT}; use serde::de::DeserializeOwned; /** * Copyright 2019 Comcast Cable Communications Management, LLC * * 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. * * SPDX-License-Identifier: Apache-2.0 */ use std::fmt::Debug; #[derive(Clone, Deserialize, Debug)] pub struct BrocadeConfig { /// The brocade endpoint to use pub endpoint: String, pub user: String, /// This gets replaced with the token at runtime pub password: String, /// Optional certificate file to use against the server /// der encoded pub certificate: Option<String>, /// Optional root certificate file to use against the server /// der encoded pub root_certificate: Option<String>, /// The region this cluster is located in pub region: String, } pub struct Brocade { client: reqwest::Client, config: BrocadeConfig, token: String, } impl Brocade { /// Initialize and connect to a Brocade switch. pub fn new(client: &reqwest::Client, config: BrocadeConfig) -> MetricsResult<Self> { let token = login(&client, &config)?; Ok(Brocade { client: client.clone(), config, token, }) } } impl Drop for Brocade { fn drop(&mut self) { if let Err(e) = self.logout() { error!("logout failed: {}", e); } } } #[test] fn parse_resource_groups() { use std::fs::File; use std::io::Read; let mut f = File::open("tests/brocade/resource_groups.json").unwrap(); let mut buff = String::new(); f.read_to_string(&mut buff).unwrap(); let i: ResourceGroups = serde_json::from_str(&buff).unwrap(); println!("result: {:#?}", i); } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] pub struct ResourceGroups { pub resource_groups: Vec<ResourceGroup>, } #[derive(Deserialize, Debug)] pub struct ResourceGroup { pub key: String, pub name: String, #[serde(rename = "type")] pub resource_type: String, } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] pub struct BufferCredit { pub bb_credit: u64, #[serde(rename = "peerBBCredit")] pub peer_bb_credit: u64, pub round_trip_time: u64, } #[test] fn parse_fc_fabrics() { use std::fs::File; use std::io::Read; sleep_the_collections(); let mut f = File::open("tests/brocade/fcfabrics.json").unwrap(); let mut buff = String::new(); f.read_to_string(&mut buff).unwrap(); let i: FcFabrics = serde_json::from_str(&buff).unwrap(); println!("result: {:#?}", i); } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] pub struct FcFabrics { pub fc_fabrics: Vec<FcFabric>, pub start_index: Option<i32>, pub items_per_page: Option<i32>, pub total_results: Option<u64>, } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug, IntoPoint)] pub struct FcFabric { pub key: String, pub seed_switch_wwn: String, pub name: String, pub secure: bool, pub ad_environment: bool, pub contact: Option<String>, pub location: Option<String>, pub description: Option<String>, pub principal_switch_wwn: String, pub fabric_name: String, pub virtual_fabric_id: i32, pub seed_switch_ip_address: String, } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] pub struct FcPorts { pub fc_ports: Vec<FcPort>, pub start_index: Option<i32>, pub items_per_page: Option<i32>, pub total_results: Option<u64>, } #[test] fn parse_fc_ports() { use std::fs::File; use std::io::Read; let mut f = File::open("tests/brocade/fcports.json").unwrap(); let mut buff = String::new(); f.read_to_string(&mut buff).unwrap(); let i: FcPorts = serde_json::from_str(&buff).unwrap(); println!("result: {:#?}", i); } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug, IntoPoint)] pub struct FcPort { key: String, wwn: String, name: String, slot_number: u64, port_number: u64, user_port_number: u64, port_id: String, port_index: u64, area_id: u64, #[serde(rename = "type")] port_type: String, status: String, status_message: String, locked_port_type: String, speed: String, speeds_supported: String, max_port_speed: u16, desired_credits: u64, buffer_allocated: u64, estimated_distance: u64, actual_distance: u64, long_distance_setting: u64, remote_node_wwn: String, remote_port_wwn: String, licensed: bool, swapped: bool, trunked: bool, trunk_master: bool, persistently_disabled: bool, ficon_supported: bool, blocked: bool, prohibit_port_numbers: Option<String>, prohibit_port_count: u64, npiv_capable: bool, npiv_enabled: bool, fc_fast_write_enabled: bool, isl_rrdy_enabled: bool, rate_limit_capable: bool, rate_limited: bool, qos_capable: bool, qos_enabled: bool, fcr_fabric_id: u64, state: String, occupied: bool, master_port_number: i64, } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] pub struct Fec { pub corrected_blocks: u64, pub uncorrected_blocks: u64, } #[test] fn parse_fc_switches() { use std::fs::File; use std::io::Read; let mut f = File::open("tests/brocade/fcswitches.json").unwrap(); let mut buff = String::new(); f.read_to_string(&mut buff).unwrap(); let i: FcSwitches = serde_json::from_str(&buff).unwrap(); println!("result: {:#?}", i); } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] pub struct FcSwitches { pub fc_switches: Vec<FcSwitch>, pub start_index: Option<i32>, pub items_per_page: Option<i32>, pub total_results: Option<u64>, } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug, IntoPoint)] pub struct FcSwitch { pub key: String, #[serde(rename = "type")] pub fc_type: u64, pub name: String, pub wwn: String, pub virtual_fabric_id: i64, pub domain_id: u64, pub base_switch: bool, pub role: String, pub fcs_role: String, pub ad_capable: bool, pub operational_status: String, pub state: String, pub status_reason: Option<String>, pub lf_enabled: bool, pub default_logical_switch: bool, pub fms_mode: bool, pub dynamic_load_sharing_capable: bool, pub port_based_routing_present: bool, pub in_order_delivery_capable: bool, pub persistent_did_enabled: bool, pub auto_snmp_enabled: bool, } pub enum FabricTimeSeries { MemoryUtilPercentage, CpuUtilPercentage, Temperature, FanSpeed, ResponseTime, SystemUpTime, PortsNotInUse, PingPktLossPercentage, } impl ToString for FabricTimeSeries { fn to_string(&self) -> String { match *self { FabricTimeSeries::MemoryUtilPercentage => "timeseriesmemoryutilpercentage".into(), FabricTimeSeries::CpuUtilPercentage => "timeseriescpuutilpercentage".into(), FabricTimeSeries::Temperature => "timeseriestemperature".into(), FabricTimeSeries::FanSpeed => "timeseriesfanspeed".into(), FabricTimeSeries::ResponseTime => "timeseriesresponsetime".into(), FabricTimeSeries::SystemUpTime => "timeseriessystemuptime".into(), FabricTimeSeries::PortsNotInUse => "timeseriesportsnotinuse".into(), FabricTimeSeries::PingPktLossPercentage => "timeseriespingpktlosspercentage".into(), } } } pub enum FcIpTimeSeries { CompressionRatio, Latency, DroppedPackets, LinkRetransmits, TimeoutRetransmits, FastRetransmits, DupAckRecvd, WindowSizeRtt, TcpOooSegments, SlowStartStatusErrors, RealtimeCompressionRatio, } impl ToString for FcIpTimeSeries { fn to_string(&self) -> String { match *self { FcIpTimeSeries::CompressionRatio => "timeseriescompressionratio".into(), FcIpTimeSeries::Latency => "timeserieslatency".into(), FcIpTimeSeries::DroppedPackets => "timeseriesdroppedpackets".into(), FcIpTimeSeries::LinkRetransmits => "timeserieslinkretransmits".into(), FcIpTimeSeries::TimeoutRetransmits => "timeseriestimeoutretransmits".into(), FcIpTimeSeries::FastRetransmits => "timeseriesfastretransmits".into(), FcIpTimeSeries::DupAckRecvd => "timeseriesdupackrecvd".into(), FcIpTimeSeries::WindowSizeRtt => "timeserieswindowsizertt".into(), FcIpTimeSeries::TcpOooSegments => "timeseriestcpooosegments".into(), FcIpTimeSeries::SlowStartStatusErrors => "timeseriesslowstartstatuserrors".into(), FcIpTimeSeries::RealtimeCompressionRatio => "timeseriesrealtimecompressionratio".into(), } } } pub enum FcTimeSeries { UtilPercentage, Traffic, CrcErrors, LinkResets, SignalLosses, SyncLosses, LinkFailures, SequenceErrors, InvalidTransmissions, C3Discards, C3DiscardsTxTo, C3DiscardsRxTo, C3DiscardsUnreachable, C3DiscardsOther, EncodeErrorOut, SfpPower, SfpVoltage, SfpCurrent, SfpTemperature, InvalidOrderedSets, BbCreditZero, TruncatedFrames, } impl ToString for FcTimeSeries { fn to_string(&self) -> String { match *self { FcTimeSeries::UtilPercentage => "timeseriesutilpercentage".into(), FcTimeSeries::Traffic => "timeseriestraffic".into(), FcTimeSeries::CrcErrors => "timeseriescrcerrors".into(), FcTimeSeries::LinkResets => "timeserieslinkresets".into(), FcTimeSeries::SignalLosses => "timeseriessignallosses".into(), FcTimeSeries::SyncLosses => "timeseriessynclosses".into(), FcTimeSeries::LinkFailures => "timeserieslinkfailures".into(), FcTimeSeries::SequenceErrors => "timeseriessequenceerrors".into(), FcTimeSeries::InvalidTransmissions => "timeseriesinvalidtransmissions".into(), FcTimeSeries::C3Discards => "timeseriesc3discards".into(), FcTimeSeries::C3DiscardsTxTo => "timeseriesc3discardstxto".into(), FcTimeSeries::C3DiscardsRxTo => "timeseriesc3discardsrxto".into(), FcTimeSeries::C3DiscardsUnreachable => "timeseriesc3discardsunreachable".into(), FcTimeSeries::C3DiscardsOther => "timeseriesc3discardsother".into(), FcTimeSeries::EncodeErrorOut => "timeseriesencodeerrorout".into(), FcTimeSeries::SfpPower => "timeseriessfppower".into(), FcTimeSeries::SfpVoltage => "timeseriessfpvoltage".into(), FcTimeSeries::SfpCurrent => "timeseriessfpcurrent".into(), FcTimeSeries::SfpTemperature => "timeseriessfptemperature".into(), FcTimeSeries::InvalidOrderedSets => "timeseriesinvalidorderedsets".into(), FcTimeSeries::BbCreditZero => "timeseriesbbcreditzero".into(), FcTimeSeries::TruncatedFrames => "timeseriestruncatedframes".into(), } } } pub enum FrameTimeSeries { TxFrameCount, RxFrameCount, TxFrameRate, RxFrameRate, TxWordCount, RxWordCount, TxThroughput, RxThroughput, AvgTxFrameSize, AvgRxFrameSize, GeneratorTxFrameCount, GeneratorRxFrameCount, MirroredFramesCount, MirroredTxFrames, MirroredRxFrames, } impl ToString for FrameTimeSeries { fn to_string(&self) -> String { match *self { FrameTimeSeries::TxFrameCount => "timeseriestxframecount".into(), FrameTimeSeries::RxFrameCount => "timeseriesrxframecount".into(), FrameTimeSeries::TxFrameRate => "timeseriestxframerate".into(), FrameTimeSeries::RxFrameRate => "timeseriesrxframerate".into(), FrameTimeSeries::TxWordCount => "timeseriestxwordcount".into(), FrameTimeSeries::RxWordCount => "timeseriesrxwordcount".into(), FrameTimeSeries::TxThroughput => "timeseriestxthroughput".into(), FrameTimeSeries::RxThroughput => "timeseriesrxthroughput".into(), FrameTimeSeries::AvgTxFrameSize => "timeseriesavgtxframesize".into(), FrameTimeSeries::AvgRxFrameSize => "timeseriesavgrxframesize".into(), FrameTimeSeries::GeneratorTxFrameCount => "timeseriesgeneratortxframecount".into(), FrameTimeSeries::GeneratorRxFrameCount => "timeseriesgeneratorrxframecount".into(), FrameTimeSeries::MirroredFramesCount => "timeseriesmirroredframescount".into(), FrameTimeSeries::MirroredTxFrames => "timeseriesmirroredtxframes".into(), FrameTimeSeries::MirroredRxFrames => "timeseriesmirroredrxframes".into(), } } } pub struct ReadDiagnostic { pub switch_name: String, pub switch_wwn: String, pub number_of_ports: u64, pub stats_type: RdpStatsType, pub port_wwn: String, pub port_type: String, pub node_wwn: String, pub tx_power: String, pub rx_power: String, pub temperature: String, pub sfp_type: String, pub laser_type: String, pub voltage: String, pub current: String, pub connecter_type: String, pub supported_speeds: String, pub link_failure: u64, pub loss_of_sync: u64, pub loss_of_signal: u64, pub protocol_error: u64, pub invalid_word: u64, pub invalid_crc: u64, pub fec: Fec, pub buffer_credit: BufferCredit, } pub enum RdpStatsType { Historical, Realtime, } pub enum ScsiTimeSeries { ReadFrameCount, WriteFrameCount, ReadFrameRate, WriteFrameRate, ReadData, WriteData, ReadDataRate, WriteDataRate, } impl ToString for ScsiTimeSeries { fn to_string(&self) -> String { match *self { ScsiTimeSeries::ReadFrameCount => "timeseriesscsireadframecount".into(), ScsiTimeSeries::WriteFrameCount => "timeseriesscsiwriteframecount".into(), ScsiTimeSeries::ReadFrameRate => "timeseriesscsireadframerate".into(), ScsiTimeSeries::WriteFrameRate => "timeseriesscsiwriteframerate".into(), ScsiTimeSeries::ReadData => "timeseriesscsireaddata".into(), ScsiTimeSeries::WriteData => "timeseriesscsiwritedata".into(), ScsiTimeSeries::ReadDataRate => "timeseriesscsireaddatarate".into(), ScsiTimeSeries::WriteDataRate => "timeseriesscsiwritedatarate".into(), } } } pub enum TimeSeries { Fc(FcTimeSeries), FcIp(FcIpTimeSeries), } // Connect to the server and request a new api token pub fn login(client: &reqwest::Client, config: &BrocadeConfig) -> MetricsResult<String> { let mut headers = HeaderMap::new(); headers.insert( ACCEPT, HeaderValue::from_str("application/vnd.brocade.networkadvisor+json;version=v1")?, ); headers.insert("WSUsername", HeaderValue::from_str(&config.user)?); headers.insert("WSPassword", HeaderValue::from_str(&config.password)?); let resp = client .post(&format!( "{}://{}/rest/login", match config.certificate { Some(_) => "https", None => "http", }, config.endpoint )) .headers(headers) .send()? .error_for_status()?; // We need a WSToken back from the server which takes the place of the // password in future requests let token = resp.headers().get("WStoken"); match token { Some(data) => Ok(data.to_str()?.to_owned()), None => Err(StorageError::new(format!( "WSToken multiple lines. {:?}. Please check server", token ))), } } // This is to delay the collections so the Brocade SAN switches do not // get their queue over-ran with requests until they can upgrade to newer version // which deals with that issue otherwise switch soft resets can occur // Added the 'use' statement here to be localized so this can all be removed later fn sleep_the_collections() { use std::{thread, time}; let sleep_time = time::Duration::from_millis(5000); let now = time::Instant::now(); thread::sleep(sleep_time); assert!(now.elapsed() >= sleep_time); } impl Brocade { // Deletes the client session pub fn logout(&self) -> MetricsResult<()> { let mut headers = HeaderMap::new(); headers.insert("WStoken", HeaderValue::from_str(&self.token)?); self.client .post(&format!( "{}://{}/rest/logout", match self.config.certificate { Some(_) => "https", None => "http", }, self.config.endpoint )) .headers(headers) .send()? .error_for_status()?; Ok(()) } fn get_server_response<T>(&self, api_call: &str, ws_token: &str) -> MetricsResult<T> where T: DeserializeOwned + Debug, { let url = format!( "{}://{}/rest/{}", match self.config.certificate { Some(_) => "https", None => "http", }, self.config.endpoint, api_call ); let resp = self .client .get(&url) .header( ACCEPT, "application/vnd.brocade.networkadvisor+json;version=v1", ) .header("WStoken", HeaderValue::from_str(&ws_token)?) .send()? .error_for_status()? .text()?; trace!("server returned: {}", resp); let json: Result<T, serde_json::Error> = serde_json::from_str(&resp); trace!("json result: {:?}", json); Ok(json?) } pub fn get_fc_fabrics(&self, t: DateTime<Utc>) -> MetricsResult<Vec<TsPoint>> { sleep_the_collections(); let result = self.get_server_response::<FcFabrics>("resourcegroups/All/fcfabrics", &self.token)?; let mut points = result .fc_fabrics .iter() .flat_map(|fabric| fabric.into_point(Some("brocade_fc_fabric"), true)) .collect::<Vec<TsPoint>>(); for point in &mut points { point.timestamp = Some(t) } Ok(points) } pub fn get_fc_switch_timeseries( &self, switch_key: &str, timeseries: TimeSeries, ) -> MetricsResult<()> { // TODO: Not sure if these performance metrics need to be enabled on the switches first sleep_the_collections(); let _url = format!( "resourcegroups/All/fcswitches/{}/{}?duration=360", switch_key, match timeseries { TimeSeries::Fc(ts) => ts.to_string(), TimeSeries::FcIp(ts) => ts.to_string(), } ); Ok(()) } pub fn get_fc_fabric_timeseries( &self, fabric_key: &str, timeseries: &FabricTimeSeries, ) -> MetricsResult<()> { // TODO: Not sure if these performance metrics need to be enabled on the switches first sleep_the_collections(); let _url = format!( "resourcegroups/All/fcfabrics/{}/{}?duration=360", fabric_key, timeseries.to_string(), ); Ok(()) } pub fn get_fc_fabric_ids(&self) -> MetricsResult<Vec<String>> { sleep_the_collections(); let result = self .get_server_response::<FcFabrics>("resourcegroups/All/fcfabrics", &self.token) .and_then(|fabrics| { let fabrics: Vec<String> = fabrics .fc_fabrics .iter() .map(|fabric| fabric.key.clone()) .collect::<Vec<String>>(); Ok(fabrics) })?; Ok(result) } pub fn get_fc_ports(&self, fabric_key: &str, t: DateTime<Utc>) -> MetricsResult<Vec<TsPoint>> { sleep_the_collections(); let result = self.get_server_response::<FcPorts>( &format!("resourcegroups/All/fcswitches/{}/fcports", fabric_key), &self.token, )?; let mut points = result .fc_ports .iter() .flat_map(|port| port.into_point(Some("brocade_fc_port"), true)) .collect::<Vec<TsPoint>>(); for point in &mut points { point.timestamp = Some(t) } Ok(points) } pub fn get_fc_switch_ids(&self) -> MetricsResult<Vec<String>> { sleep_the_collections(); let result = self .get_server_response::<FcSwitches>("resourcegroups/All/fcswitches", &self.token) .and_then(|switches| { let switches: Vec<String> = switches .fc_switches .iter() .map(|switch| switch.key.clone()) .collect::<Vec<String>>(); Ok(switches) })?; Ok(result) } pub fn get_fc_switches(&self, t: DateTime<Utc>) -> MetricsResult<Vec<TsPoint>> { sleep_the_collections(); let result = self.get_server_response::<FcSwitches>("resourcegroups/All/fcswitches", &self.token)?; let mut points = result .fc_switches .iter() .flat_map(|switch| switch.into_point(Some("brocade_fc_switch"), true)) .collect::<Vec<TsPoint>>(); for point in &mut points { point.timestamp = Some(t) } Ok(points) } pub fn get_resource_groups(&self) -> MetricsResult<ResourceGroups> { let result = self.get_server_response::<ResourceGroups>("resourcegroups", &self.token)?; Ok(result) } }
31.715297
100
0.629494
712b4ac96016594466b3c48d8130b7659abee77a
18,251
#[rustfmt::skip] #[cfg(not(any(target_os = "macos", windows)))] use { std::sync::atomic::AtomicBool, std::sync::Arc, glutin::platform::unix::{WindowBuilderExtUnix, WindowExtUnix}, }; #[rustfmt::skip] #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] use { wayland_client::protocol::wl_surface::WlSurface, wayland_client::{Attached, EventQueue, Proxy}, glutin::platform::unix::EventLoopWindowTargetExtUnix, }; #[rustfmt::skip] #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] use { std::io::Cursor, x11_dl::xlib::{Display as XDisplay, PropModeReplace, XErrorEvent, Xlib}, glutin::window::Icon, png::Decoder, }; use std::fmt::{self, Display, Formatter}; use std::ops::{Deref, DerefMut}; #[cfg(target_os = "macos")] use cocoa::base::{id, NO, YES}; use glutin::dpi::{PhysicalPosition, PhysicalSize}; use glutin::event_loop::EventLoopWindowTarget; #[cfg(target_os = "macos")] use glutin::platform::macos::{WindowBuilderExtMacOS, WindowExtMacOS}; #[cfg(windows)] use glutin::platform::windows::IconExtWindows; use glutin::window::{ CursorIcon, Fullscreen, UserAttentionType, Window as GlutinWindow, WindowBuilder, WindowId, }; use glutin::{self, ContextBuilder, PossiblyCurrent, Rect, WindowedContext}; #[cfg(target_os = "macos")] use objc::{msg_send, sel, sel_impl}; #[cfg(target_os = "macos")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; #[cfg(windows)] use winapi::shared::minwindef::WORD; use alacritty_terminal::index::Point; use alacritty_terminal::term::SizeInfo; use crate::config::window::{Decorations, Identity, WindowConfig}; use crate::config::UiConfig; use crate::gl; /// Window icon for `_NET_WM_ICON` property. #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] static WINDOW_ICON: &[u8] = include_bytes!("../../alacritty.png"); /// This should match the definition of IDI_ICON from `windows.rc`. #[cfg(windows)] const IDI_ICON: WORD = 0x101; /// Window errors. #[derive(Debug)] pub enum Error { /// Error creating the window. ContextCreation(glutin::CreationError), /// Error dealing with fonts. Font(crossfont::Error), /// Error manipulating the rendering context. Context(glutin::ContextError), } /// Result of fallible operations concerning a Window. type Result<T> = std::result::Result<T, Error>; impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::ContextCreation(err) => err.source(), Error::Context(err) => err.source(), Error::Font(err) => err.source(), } } } impl Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::ContextCreation(err) => write!(f, "Error creating GL context; {}", err), Error::Context(err) => write!(f, "Error operating on render context; {}", err), Error::Font(err) => err.fmt(f), } } } impl From<glutin::CreationError> for Error { fn from(val: glutin::CreationError) -> Self { Error::ContextCreation(val) } } impl From<glutin::ContextError> for Error { fn from(val: glutin::ContextError) -> Self { Error::Context(val) } } impl From<crossfont::Error> for Error { fn from(val: crossfont::Error) -> Self { Error::Font(val) } } fn create_gl_window<E>( mut window: WindowBuilder, event_loop: &EventLoopWindowTarget<E>, srgb: bool, vsync: bool, dimensions: Option<PhysicalSize<u32>>, ) -> Result<WindowedContext<PossiblyCurrent>> { if let Some(dimensions) = dimensions { window = window.with_inner_size(dimensions); } let windowed_context = ContextBuilder::new() .with_srgb(srgb) .with_vsync(vsync) .with_hardware_acceleration(None) .build_windowed(window, event_loop)?; // Make the context current so OpenGL operations can run. let windowed_context = unsafe { windowed_context.make_current().map_err(|(_, err)| err)? }; Ok(windowed_context) } /// A window which can be used for displaying the terminal. /// /// Wraps the underlying windowing library to provide a stable API in Alacritty. pub struct Window { /// Flag tracking frame redraw requests from Wayland compositor. #[cfg(not(any(target_os = "macos", windows)))] pub should_draw: Arc<AtomicBool>, /// Attached Wayland surface to request new frame events. #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] pub wayland_surface: Option<Attached<WlSurface>>, /// Cached DPR for quickly scaling pixel sizes. pub dpr: f64, /// Current window title. title: String, windowed_context: Replaceable<WindowedContext<PossiblyCurrent>>, current_mouse_cursor: CursorIcon, mouse_visible: bool, } impl Window { /// Create a new window. /// /// This creates a window and fully initializes a window. pub fn new<E>( event_loop: &EventLoopWindowTarget<E>, config: &UiConfig, identity: &Identity, size: Option<PhysicalSize<u32>>, #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] wayland_event_queue: Option<&EventQueue>, ) -> Result<Window> { let identity = identity.clone(); let mut window_builder = Window::get_platform_window(&identity, &config.window); if let Some(position) = config.window.position { window_builder = window_builder .with_position(PhysicalPosition::<i32>::from((position.x, position.y))); } // Check if we're running Wayland to disable vsync. #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] let is_wayland = event_loop.is_wayland(); #[cfg(any(not(feature = "wayland"), target_os = "macos", windows))] let is_wayland = false; let windowed_context = create_gl_window(window_builder.clone(), event_loop, false, !is_wayland, size) .or_else(|_| { create_gl_window(window_builder, event_loop, true, !is_wayland, size) })?; // Text cursor. let current_mouse_cursor = CursorIcon::Text; windowed_context.window().set_cursor_icon(current_mouse_cursor); // Set OpenGL symbol loader. This call MUST be after window.make_current on windows. gl::load_with(|symbol| windowed_context.get_proc_address(symbol) as *const _); #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] if !is_wayland { // On X11, embed the window inside another if the parent ID has been set. if let Some(parent_window_id) = config.window.embed { x_embed_window(windowed_context.window(), parent_window_id); } } #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] let wayland_surface = if is_wayland { // Attach surface to Alacritty's internal wayland queue to handle frame callbacks. let surface = windowed_context.window().wayland_surface().unwrap(); let proxy: Proxy<WlSurface> = unsafe { Proxy::from_c_ptr(surface as _) }; Some(proxy.attach(wayland_event_queue.as_ref().unwrap().token())) } else { None }; let dpr = windowed_context.window().scale_factor(); Ok(Self { current_mouse_cursor, mouse_visible: true, windowed_context: Replaceable::new(windowed_context), title: identity.title, #[cfg(not(any(target_os = "macos", windows)))] should_draw: Arc::new(AtomicBool::new(true)), #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] wayland_surface, dpr, }) } #[inline] pub fn set_inner_size(&mut self, size: PhysicalSize<u32>) { self.window().set_inner_size(size); } #[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { self.window().inner_size() } #[inline] pub fn set_visible(&self, visibility: bool) { self.window().set_visible(visibility); } /// Set the window title. #[inline] pub fn set_title(&mut self, title: String) { self.title = title; self.window().set_title(&self.title); } /// Get the window title. #[inline] pub fn title(&self) -> &str { &self.title } #[inline] pub fn request_redraw(&self) { self.window().request_redraw(); } #[inline] pub fn set_mouse_cursor(&mut self, cursor: CursorIcon) { if cursor != self.current_mouse_cursor { self.current_mouse_cursor = cursor; self.window().set_cursor_icon(cursor); } } /// Set mouse cursor visible. pub fn set_mouse_visible(&mut self, visible: bool) { if visible != self.mouse_visible { self.mouse_visible = visible; self.window().set_cursor_visible(visible); } } #[cfg(not(any(target_os = "macos", windows)))] pub fn get_platform_window(identity: &Identity, window_config: &WindowConfig) -> WindowBuilder { #[cfg(feature = "x11")] let icon = { let decoder = Decoder::new(Cursor::new(WINDOW_ICON)); let (info, mut reader) = decoder.read_info().expect("invalid embedded icon"); let mut buf = vec![0; info.buffer_size()]; let _ = reader.next_frame(&mut buf); Icon::from_rgba(buf, info.width, info.height) }; let builder = WindowBuilder::new() .with_title(&identity.title) .with_visible(false) .with_transparent(true) .with_decorations(window_config.decorations != Decorations::None) .with_maximized(window_config.maximized()) .with_fullscreen(window_config.fullscreen()); #[cfg(feature = "x11")] let builder = builder.with_window_icon(icon.ok()); #[cfg(feature = "wayland")] let builder = builder.with_app_id(identity.class.instance.to_owned()); #[cfg(feature = "x11")] let builder = builder .with_class(identity.class.instance.to_owned(), identity.class.general.to_owned()); #[cfg(feature = "x11")] let builder = match &window_config.gtk_theme_variant { Some(val) => builder.with_gtk_theme_variant(val.clone()), None => builder, }; builder } #[cfg(windows)] pub fn get_platform_window(identity: &Identity, window_config: &WindowConfig) -> WindowBuilder { let icon = glutin::window::Icon::from_resource(IDI_ICON, None); WindowBuilder::new() .with_title(&identity.title) .with_visible(false) .with_decorations(window_config.decorations != Decorations::None) .with_transparent(true) .with_maximized(window_config.maximized()) .with_fullscreen(window_config.fullscreen()) .with_window_icon(icon.ok()) } #[cfg(target_os = "macos")] pub fn get_platform_window(identity: &Identity, window_config: &WindowConfig) -> WindowBuilder { let window = WindowBuilder::new() .with_title(&identity.title) .with_visible(false) .with_transparent(true) .with_maximized(window_config.maximized()) .with_fullscreen(window_config.fullscreen()); match window_config.decorations { Decorations::Full => window, Decorations::Transparent => window .with_title_hidden(true) .with_titlebar_transparent(true) .with_fullsize_content_view(true), Decorations::Buttonless => window .with_title_hidden(true) .with_titlebar_buttons_hidden(true) .with_titlebar_transparent(true) .with_fullsize_content_view(true), Decorations::None => window.with_titlebar_hidden(true), } } pub fn set_urgent(&self, is_urgent: bool) { let attention = if is_urgent { Some(UserAttentionType::Critical) } else { None }; self.window().request_user_attention(attention); } #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] pub fn x11_window_id(&self) -> Option<usize> { self.window().xlib_window().map(|xlib_window| xlib_window as usize) } #[cfg(any(not(feature = "x11"), target_os = "macos", windows))] pub fn x11_window_id(&self) -> Option<usize> { None } pub fn id(&self) -> WindowId { self.window().id() } #[cfg(not(any(target_os = "macos", windows)))] pub fn set_maximized(&self, maximized: bool) { self.window().set_maximized(maximized); } pub fn set_minimized(&self, minimized: bool) { self.window().set_minimized(minimized); } /// Toggle the window's fullscreen state. pub fn toggle_fullscreen(&mut self) { self.set_fullscreen(self.window().fullscreen().is_none()); } #[cfg(target_os = "macos")] pub fn toggle_simple_fullscreen(&mut self) { self.set_simple_fullscreen(!self.window().simple_fullscreen()); } pub fn set_fullscreen(&mut self, fullscreen: bool) { if fullscreen { self.window().set_fullscreen(Some(Fullscreen::Borderless(None))); } else { self.window().set_fullscreen(None); } } #[cfg(target_os = "macos")] pub fn set_simple_fullscreen(&mut self, simple_fullscreen: bool) { self.window().set_simple_fullscreen(simple_fullscreen); } #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] pub fn wayland_surface(&self) -> Option<&Attached<WlSurface>> { self.wayland_surface.as_ref() } /// Adjust the IME editor position according to the new location of the cursor. pub fn update_ime_position(&mut self, point: Point, size: &SizeInfo) { let nspot_x = f64::from(size.padding_x() + point.column.0 as f32 * size.cell_width()); let nspot_y = f64::from(size.padding_y() + (point.line.0 + 1) as f32 * size.cell_height()); self.window().set_ime_position(PhysicalPosition::new(nspot_x, nspot_y)); } pub fn swap_buffers(&self) { self.windowed_context.swap_buffers().expect("swap buffers"); } pub fn swap_buffers_with_damage(&self, damage: &[Rect]) { self.windowed_context.swap_buffers_with_damage(damage).expect("swap buffes with damage"); } pub fn swap_buffers_with_damage_supported(&self) -> bool { self.windowed_context.swap_buffers_with_damage_supported() } pub fn resize(&self, size: PhysicalSize<u32>) { self.windowed_context.resize(size); } pub fn make_current(&mut self) { if !self.windowed_context.is_current() { self.windowed_context .replace_with(|context| unsafe { context.make_current().expect("context swap") }); } } /// Disable macOS window shadows. /// /// This prevents rendering artifacts from showing up when the window is transparent. #[cfg(target_os = "macos")] pub fn set_has_shadow(&self, has_shadows: bool) { let raw_window = match self.window().raw_window_handle() { RawWindowHandle::AppKit(handle) => handle.ns_window as id, _ => return, }; let value = if has_shadows { YES } else { NO }; unsafe { let _: () = msg_send![raw_window, setHasShadow: value]; } } fn window(&self) -> &GlutinWindow { self.windowed_context.window() } } #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] fn x_embed_window(window: &GlutinWindow, parent_id: std::os::raw::c_ulong) { let (xlib_display, xlib_window) = match (window.xlib_display(), window.xlib_window()) { (Some(display), Some(window)) => (display, window), _ => return, }; let xlib = Xlib::open().expect("get xlib"); unsafe { let atom = (xlib.XInternAtom)(xlib_display as *mut _, "_XEMBED".as_ptr() as *const _, 0); (xlib.XChangeProperty)( xlib_display as _, xlib_window as _, atom, atom, 32, PropModeReplace, [0, 1].as_ptr(), 2, ); // Register new error handler. let old_handler = (xlib.XSetErrorHandler)(Some(xembed_error_handler)); // Check for the existence of the target before attempting reparenting. (xlib.XReparentWindow)(xlib_display as _, xlib_window as _, parent_id, 0, 0); // Drain errors and restore original error handler. (xlib.XSync)(xlib_display as _, 0); (xlib.XSetErrorHandler)(old_handler); } } #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] unsafe extern "C" fn xembed_error_handler(_: *mut XDisplay, _: *mut XErrorEvent) -> i32 { log::error!("Could not embed into specified window."); std::process::exit(1); } /// Struct for safe in-place replacement. /// /// This struct allows easily replacing struct fields that provide `self -> Self` methods in-place, /// without having to deal with constantly unwrapping the underlying [`Option`]. struct Replaceable<T>(Option<T>); impl<T> Replaceable<T> { pub fn new(inner: T) -> Self { Self(Some(inner)) } /// Replace the contents of the container. pub fn replace_with<F: FnMut(T) -> T>(&mut self, f: F) { self.0 = self.0.take().map(f); } /// Get immutable access to the wrapped value. pub fn get(&self) -> &T { self.0.as_ref().unwrap() } /// Get mutable access to the wrapped value. pub fn get_mut(&mut self) -> &mut T { self.0.as_mut().unwrap() } } impl<T> Deref for Replaceable<T> { type Target = T; fn deref(&self) -> &Self::Target { self.get() } } impl<T> DerefMut for Replaceable<T> { fn deref_mut(&mut self) -> &mut Self::Target { self.get_mut() } }
33.123412
100
0.621336
6440965747704a73199ade7759111dd4d8dcc4a7
7,388
use mango_orm::*; use mango_orm::{migration::Monitor, test_tool::del_test_db}; use metamorphose::Model; use mongodb::{ bson::{doc, oid::ObjectId}, sync::Client, }; use serde::{Deserialize, Serialize}; // APP NAME // ################################################################################################# mod app_name { use super::*; // Test application settings // ********************************************************************************************* pub const PROJECT_NAME: &str = "project_name"; pub const UNIQUE_PROJECT_KEY: &str = "T2SCaZC3V2HvRQdP"; pub const SERVICE_NAME: &str = "service_name"; pub const DATABASE_NAME: &str = "database_name"; pub const DB_CLIENT_NAME: &str = "default"; const DB_QUERY_DOCS_LIMIT: u32 = 1000; // Create models // ********************************************************************************************* #[Model] #[derive(Serialize, Deserialize, Default)] pub struct TestModel { #[serde(default)] #[field_attrs( widget = "inputDate", value = "1970-02-28", min = "1970-01-01", max = "1970-03-01", unique = true )] pub date: Option<String>, } // Test migration // ********************************************************************************************* // Model list pub fn model_list() -> Result<Vec<Meta>, Box<dyn std::error::Error>> { Ok(vec![TestModel::meta()?]) } // Test, migration service `Mango` pub fn mango_migration() -> Result<(), Box<dyn std::error::Error>> { // Caching MongoDB clients MONGODB_CLIENT_STORE.write()?.insert( "default".to_string(), mongodb::sync::Client::with_uri_str("mongodb://localhost:27017")?, ); // Remove test databases // ( Test databases may remain in case of errors ) del_test_db(PROJECT_NAME, UNIQUE_PROJECT_KEY, &model_list()?)?; // Migration let monitor = Monitor { project_name: PROJECT_NAME, unique_project_key: UNIQUE_PROJECT_KEY, // Register models models: model_list()?, }; monitor.migrat()?; // Add metadata and widgects map to cache. TestModel::to_cache()?; // Ok(()) } } // TEST // ################################################################################################# #[test] fn test_model_date_fields() -> Result<(), Box<dyn std::error::Error>> { // --------------------------------------------------------------------------------------------- app_name::mango_migration()?; // ^ ^ ^ --------------------------------------------------------------------------------------- let mut test_model = app_name::TestModel { date: Some("1970-02-27".to_string()), ..Default::default() }; let mut test_model_2 = app_name::TestModel { date: Some("1970-02-27".to_string()), ..Default::default() }; // Create // --------------------------------------------------------------------------------------------- let result = test_model.save(None, None)?; let result_2 = test_model_2.save(None, None)?; // Validating create assert!(result.is_valid(), "{}", result.hash()?); // Validation of `hash` assert!(test_model.hash.is_some()); // Validation of `unique` assert!(!result_2.is_valid()); // Validation of `hash` assert!(test_model_2.hash.is_none()); // Validating values in widgets // date let map_wigets = result.wig(); assert_eq!( "1970-02-27".to_string(), map_wigets.get("date").unwrap().value ); let map_wigets = app_name::TestModel::form_wig()?; assert_eq!( "1970-02-28".to_string(), map_wigets.get("date").unwrap().value ); let map_wigets = result_2.wig(); assert_eq!( "1970-02-27".to_string(), map_wigets.get("date").unwrap().value ); // Validating values in database { let form_store = FORM_STORE.read()?; let client_store = MONGODB_CLIENT_STORE.read()?; let form_cache: &FormCache = form_store.get(&app_name::TestModel::key()[..]).unwrap(); let meta: &Meta = &form_cache.meta; let client: &Client = client_store.get(meta.db_client_name.as_str()).unwrap(); let object_id = ObjectId::with_string(test_model.hash.clone().unwrap().as_str())?; let coll = client .database(meta.database_name.as_str()) .collection(meta.collection_name.as_str()); let filter = doc! {"_id": object_id}; let doc = coll.find_one(filter, None)?.unwrap(); assert_eq!(1_i64, coll.count_documents(None, None)?); let dt_value: chrono::DateTime<chrono::Utc> = chrono::DateTime::<chrono::Utc>::from_utc( chrono::NaiveDateTime::parse_from_str( &format!("{}T00:00", "1970-02-27".to_string()), "%Y-%m-%dT%H:%M", )?, chrono::Utc, ); assert_eq!(&dt_value, doc.get_datetime("date")?); } // Update // --------------------------------------------------------------------------------------------- let tmp_hash = test_model.hash.clone().unwrap(); let result = test_model.save(None, None)?; // Validating update assert!(result.is_valid(), "{}", result.hash()?); // Validation of `hash` assert!(test_model.hash.is_some()); assert_eq!(tmp_hash, test_model.hash.clone().unwrap()); // Validating values // date let map_wigets = result.wig(); assert_eq!( "1970-02-27".to_string(), map_wigets.get("date").unwrap().value ); let map_wigets = app_name::TestModel::form_wig()?; assert_eq!( "1970-02-28".to_string(), map_wigets.get("date").unwrap().value ); // Validating values in database { let form_store = FORM_STORE.read()?; let client_store = MONGODB_CLIENT_STORE.read()?; let form_cache: &FormCache = form_store.get(&app_name::TestModel::key()[..]).unwrap(); let meta: &Meta = &form_cache.meta; let client: &Client = client_store.get(meta.db_client_name.as_str()).unwrap(); let object_id = ObjectId::with_string(test_model.hash.clone().unwrap().as_str())?; let coll = client .database(meta.database_name.as_str()) .collection(meta.collection_name.as_str()); let filter = doc! {"_id": object_id}; let doc = coll.find_one(filter, None)?.unwrap(); assert_eq!(1_i64, coll.count_documents(None, None)?); let dt_value: chrono::DateTime<chrono::Utc> = chrono::DateTime::<chrono::Utc>::from_utc( chrono::NaiveDateTime::parse_from_str( &format!("{}T00:00", "1970-02-27".to_string()), "%Y-%m-%dT%H:%M", )?, chrono::Utc, ); assert_eq!(&dt_value, doc.get_datetime("date")?); } // --------------------------------------------------------------------------------------------- del_test_db( app_name::PROJECT_NAME, app_name::UNIQUE_PROJECT_KEY, &app_name::model_list()?, )?; // ^ ^ ^ --------------------------------------------------------------------------------------- Ok(()) }
37.502538
100
0.496345
87a13a20fbf979147d39109ec892721443df6b5a
101
#![recursion_limit="1024"] #[macro_use] extern crate diesel; mod schema; pub use self::schema::*;
11.222222
26
0.693069
4b2a291f36aa64d753318fb55cd31f2b573b6ba5
59,022
// Copyright 2019 Zhizhesihai (Beijing) Technology Limited. // // 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, // See the License for the specific language governing permissions and // limitations under the License. use core::codec::field_infos::FieldInfo; use core::codec::postings::blocktree::BlockTermState; use core::codec::postings::for_util::*; use core::codec::postings::posting_format::BLOCK_SIZE; use core::codec::postings::skip_reader::*; use core::codec::segment_infos::{segment_file_name, SegmentReadState}; use core::codec::{codec_util, Codec}; use core::codec::{PostingIterator, PostingIteratorFlags}; use core::search::{DocIterator, Payload, NO_MORE_DOCS}; use core::store::directory::Directory; use core::store::io::{DataInput, IndexInput}; use core::util::DocId; use core::util::UnsignedShift; use error::{ErrorKind::IllegalState, Result}; use std::sync::Arc; /// Filename extension for document number, frequencies, and skip data. /// See chapter: <a href="#Frequencies">Frequencies and Skip Data</a> pub const DOC_EXTENSION: &str = "doc"; /// Filename extension for positions. /// See chapter: <a href="#Positions">Positions</a> pub const POS_EXTENSION: &str = "pos"; /// Filename extension for payloads and offsets. /// See chapter: <a href="#Payloads">Payloads and Offsets</a> pub const PAY_EXTENSION: &str = "pay"; /// Expert: The maximum number of skip levels. Smaller values result in /// slightly smaller indexes, but slower skipping in big posting lists. pub const MAX_SKIP_LEVELS: usize = 10; pub const TERMS_CODEC: &str = "Lucene50PostingsWriterTerms"; pub const DOC_CODEC: &str = "Lucene50PostingsWriterDoc"; pub const POS_CODEC: &str = "Lucene50PostingsWriterPos"; pub const PAY_CODEC: &str = "Lucene50PostingsWriterPay"; // Increment version to change it const VERSION_START: i32 = 0; pub const VERSION_CURRENT: i32 = VERSION_START; fn clone_option_index_input(input: &Option<Box<dyn IndexInput>>) -> Result<Box<dyn IndexInput>> { debug_assert!(input.is_some()); (*input.as_ref().unwrap()).clone() } /// Concrete class that reads docId(maybe frq,pos,offset,payloads) list /// with postings format. /// /// @lucene.experimental pub struct Lucene50PostingsReader { doc_in: Box<dyn IndexInput>, pos_in: Option<Box<dyn IndexInput>>, pay_in: Option<Box<dyn IndexInput>>, pub version: i32, pub for_util: ForUtil, } impl Lucene50PostingsReader { fn clone_pos_in(&self) -> Result<Box<dyn IndexInput>> { clone_option_index_input(&self.pos_in) } fn clone_pay_in(&self) -> Result<Box<dyn IndexInput>> { clone_option_index_input(&self.pay_in) } pub fn open<D: Directory, DW: Directory, C: Codec>( state: &SegmentReadState<'_, D, DW, C>, ) -> Result<Lucene50PostingsReader> { let doc_name = segment_file_name( &state.segment_info.name, &state.segment_suffix, DOC_EXTENSION, ); let mut doc_in = state.directory.open_input(&doc_name, state.context)?; let version = codec_util::check_index_header( doc_in.as_mut(), DOC_CODEC, VERSION_START, VERSION_CURRENT, &state.segment_info.id, &state.segment_suffix, )?; let for_util = ForUtil::with_input(doc_in.as_mut())?; codec_util::retrieve_checksum(doc_in.as_mut())?; let mut pos_in = None; let mut pay_in = None; let doc_in = doc_in; if state.field_infos.has_prox { let prox_name = segment_file_name( &state.segment_info.name, &state.segment_suffix, POS_EXTENSION, ); let mut input = state.directory.open_input(&prox_name, state.context)?; codec_util::check_index_header( input.as_mut(), POS_CODEC, version, version, &state.segment_info.id, &state.segment_suffix, )?; codec_util::retrieve_checksum(input.as_mut())?; pos_in = Some(input); if state.field_infos.has_payloads || state.field_infos.has_offsets { let pay_name = segment_file_name( &state.segment_info.name, &state.segment_suffix, PAY_EXTENSION, ); input = state.directory.open_input(&pay_name, state.context)?; codec_util::check_index_header( input.as_mut(), PAY_CODEC, version, version, &state.segment_info.id, &state.segment_suffix, )?; codec_util::retrieve_checksum(input.as_mut())?; pay_in = Some(input) } } Ok(Lucene50PostingsReader { doc_in, pos_in, pay_in, version, for_util, }) } pub fn init<D: Directory, DW: Directory, C: Codec>( &self, terms_in: &mut dyn IndexInput, state: &SegmentReadState<'_, D, DW, C>, ) -> Result<()> { codec_util::check_index_header( terms_in, TERMS_CODEC, VERSION_START, VERSION_CURRENT, &state.segment_info.id, &state.segment_suffix, )?; let index_block_size = terms_in.read_vint()?; if index_block_size != BLOCK_SIZE { bail!(IllegalState(format!( "index-time BLOCK_SIZE ({}) != read-time BLOCK_SIZE ({})", index_block_size, BLOCK_SIZE ))) } else { Ok(()) } } /// Return a newly created empty TermState pub fn new_term_state(&self) -> BlockTermState { BlockTermState::new() } pub fn postings( &self, field_info: &FieldInfo, state: &BlockTermState, flags: u16, ) -> Result<Lucene50PostingIterator> { let options = &field_info.index_options; let index_has_positions = options.has_positions(); let index_has_offsets = options.has_offsets(); let index_has_payloads = field_info.has_store_payloads; if !index_has_positions || !PostingIteratorFlags::feature_requested(flags, PostingIteratorFlags::POSITIONS) { Ok(Lucene50PostingIterator(Lucene50PostingIterEnum::Doc( BlockDocIterator::new( self.doc_in.clone()?, field_info, state, flags, self.for_util.clone(), )?, ))) } else if (!index_has_offsets || !PostingIteratorFlags::feature_requested(flags, PostingIteratorFlags::OFFSETS)) && (!index_has_payloads || !PostingIteratorFlags::feature_requested(flags, PostingIteratorFlags::PAYLOADS)) { Ok(Lucene50PostingIterator(Lucene50PostingIterEnum::Posting( BlockPostingIterator::new( self.doc_in.clone()?, self.clone_pos_in()?, field_info, state, flags, self.for_util.clone(), )?, ))) } else { debug_assert!(self.pos_in.is_some()); debug_assert!(self.pay_in.is_some()); Ok(Lucene50PostingIterator( Lucene50PostingIterEnum::Everything(EverythingIterator::new( self.doc_in.clone()?, self.clone_pos_in()?, self.clone_pay_in()?, field_info, state, flags, self.for_util.clone(), )?), )) } } pub fn check_integrity(&self) -> Result<()> { // codec_util::checksum_entire_file(self.doc_in.as_ref())?; // // if let Some(ref pos_in) = self.pos_in { // codec_util::checksum_entire_file(pos_in.as_ref())?; // } // if let Some(ref pay_in) = self.pay_in { // codec_util::checksum_entire_file(pay_in.as_ref())?; // } Ok(()) } } pub type Lucene50PostingsReaderRef = Arc<Lucene50PostingsReader>; /// Actually decode metadata for next term /// @see PostingsWriterBase#encodeTerm pub fn lucene50_decode_term<T: DataInput + ?Sized>( longs: &[i64], input: &mut T, field_info: &FieldInfo, state: &mut BlockTermState, absolute: bool, ) -> Result<()> { let options = &field_info.index_options; let field_has_positions = options.has_positions(); let field_has_offsets = options.has_offsets(); let field_has_payloads = field_info.has_store_payloads; if absolute { state.doc_start_fp = 0; state.pos_start_fp = 0; state.pay_start_fp = 0; }; state.doc_start_fp += longs[0]; if field_has_positions { state.pos_start_fp += longs[1]; if field_has_offsets || field_has_payloads { state.pay_start_fp += longs[2]; } } state.singleton_doc_id = if state.doc_freq == 1 { input.read_vint()? } else { -1 }; if field_has_positions { state.last_pos_block_offset = if state.total_term_freq > i64::from(BLOCK_SIZE) { input.read_vlong()? } else { -1 } } state.skip_offset = if state.doc_freq > BLOCK_SIZE { input.read_vlong()? } else { -1 }; Ok(()) } fn read_vint_block( doc_in: &mut dyn IndexInput, doc_buffer: &mut [i32], freq_buffer: &mut [i32], num: i32, index_has_freq: bool, ) -> Result<()> { let num = num as usize; if index_has_freq { for i in 0..num { let code = doc_in.read_vint()? as u32; doc_buffer[i] = (code >> 1) as i32; if (code & 1) != 0 { freq_buffer[i] = 1; } else { freq_buffer[i] = doc_in.read_vint()?; } } } else { for item in doc_buffer.iter_mut().take(num) { *item = doc_in.read_vint()?; } } Ok(()) } struct BlockDocIterator { encoded: [u8; MAX_ENCODED_SIZE], doc_delta_buffer: [i32; MAX_DATA_SIZE], freq_buffer: [i32; MAX_DATA_SIZE], doc_buffer_upto: i32, pub skipper: Option<Lucene50SkipReader>, skipped: bool, start_doc_in: Box<dyn IndexInput>, doc_in: Option<Box<dyn IndexInput>>, index_has_freq: bool, index_has_pos: bool, pub index_has_offsets: bool, index_has_payloads: bool, /// number of docs in this posting list doc_freq: i32, /// sum of freqs in this posting list (or docFreq when omitted) total_term_freq: i64, /// how many docs we've read doc_upto: i32, /// doc we last read doc: DocId, /// accumulator for doc deltas accum: i32, /// freq we last read pub freq: i32, /// Where this term's postings start in the .doc file: doc_term_start_fp: i64, /// Where this term's skip data starts (after /// docTermStartFP) in the .doc file (or -1 if there is /// no skip data for this term): skip_offset: i64, /// docID for next skip point, we won't use skipper if /// target docID is not larger than this next_skip_doc: i32, /// true if the caller actually needs frequencies needs_freq: bool, /// docid when there is a single pulsed posting, otherwise -1 singleton_doc_id: DocId, for_util: ForUtil, } impl BlockDocIterator { pub fn new( start_doc_in: Box<dyn IndexInput>, field_info: &FieldInfo, term_state: &BlockTermState, flags: u16, for_util: ForUtil, ) -> Result<BlockDocIterator> { let options = &field_info.index_options; let mut iterator = BlockDocIterator { encoded: [0u8; MAX_ENCODED_SIZE], start_doc_in, doc_delta_buffer: [0i32; MAX_DATA_SIZE], freq_buffer: [0i32; MAX_DATA_SIZE], doc_buffer_upto: 0, skipped: false, skipper: None, doc_in: None, doc_freq: 0, total_term_freq: 0, doc_upto: 0, doc: 0, accum: 0, freq: 0, doc_term_start_fp: 0, skip_offset: 0, next_skip_doc: 0, needs_freq: false, singleton_doc_id: 0, index_has_freq: options.has_freqs(), index_has_pos: options.has_positions(), index_has_offsets: options.has_offsets(), index_has_payloads: field_info.has_store_payloads, for_util, }; iterator.reset(term_state, flags)?; Ok(iterator) } pub fn reset(&mut self, term_state: &BlockTermState, flags: u16) -> Result<()> { self.doc_freq = term_state.doc_freq; self.total_term_freq = if self.index_has_freq { term_state.total_term_freq } else { i64::from(self.doc_freq) }; self.doc_term_start_fp = term_state.doc_start_fp; self.skip_offset = term_state.skip_offset; self.singleton_doc_id = term_state.singleton_doc_id; if self.doc_freq > 1 { if self.doc_in.is_none() { // lazy init self.doc_in = Some(self.start_doc_in.clone()?); } let start = self.doc_term_start_fp; self.doc_in.as_mut().unwrap().seek(start)?; } self.doc = -1; self.needs_freq = PostingIteratorFlags::feature_requested(flags, PostingIteratorFlags::FREQS); if !self.index_has_freq || !self.needs_freq { self.freq_buffer.iter_mut().map(|x| *x = 1).count(); } self.accum = 0; self.doc_upto = 0; self.next_skip_doc = BLOCK_SIZE - 1; // we won't skip if target is found in first block self.doc_buffer_upto = BLOCK_SIZE; self.skipped = false; Ok(()) } fn refill_docs(&mut self) -> Result<()> { let left = self.doc_freq - self.doc_upto; debug_assert!(left > 0); if left >= BLOCK_SIZE { let doc_in = self.doc_in.as_mut().unwrap(); self.for_util.read_block( doc_in.as_mut(), &mut self.encoded, &mut self.doc_delta_buffer, )?; if self.index_has_freq { if self.needs_freq { self.for_util.read_block( doc_in.as_mut(), &mut self.encoded, &mut self.freq_buffer, )?; } else { self.for_util.skip_block(doc_in.as_mut())?; // skip over freqs } } } else if self.doc_freq == 1 { self.doc_delta_buffer[0] = self.singleton_doc_id; self.freq_buffer[0] = self.total_term_freq as i32; } else { let doc_in = self.doc_in.as_mut().unwrap(); // Read vInts: read_vint_block( doc_in.as_mut(), &mut self.doc_delta_buffer, &mut self.freq_buffer, left, self.index_has_freq, )?; } self.doc_buffer_upto = 0; Ok(()) } } impl PostingIterator for BlockDocIterator { fn freq(&self) -> Result<i32> { debug_assert!(self.freq > 0); Ok(self.freq) } fn next_position(&mut self) -> Result<i32> { Ok(-1) } fn start_offset(&self) -> Result<i32> { Ok(-1) } fn end_offset(&self) -> Result<i32> { Ok(-1) } fn payload(&self) -> Result<Payload> { Ok(Payload::new()) } } impl DocIterator for BlockDocIterator { fn doc_id(&self) -> DocId { self.doc } fn next(&mut self) -> Result<DocId> { if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } if self.doc_buffer_upto == BLOCK_SIZE { self.refill_docs()?; } self.accum += self.doc_delta_buffer[self.doc_buffer_upto as usize]; self.doc_upto += 1; self.doc = self.accum; self.freq = self.freq_buffer[self.doc_buffer_upto as usize]; self.doc_buffer_upto += 1; Ok(self.doc) } fn advance(&mut self, target: DocId) -> Result<DocId> { // TODO: make frq block load lazy/skippable // current skip docID < docIDs generated from current buffer <= next skip docID // we don't need to skip if target is buffered already if self.doc_freq > BLOCK_SIZE && target > self.next_skip_doc { if self.skipper.is_none() { // Lazy init: first time this enum has ever been used for skipping self.skipper = Some(Lucene50SkipReader::new( clone_option_index_input(&self.doc_in)?, MAX_SKIP_LEVELS, self.index_has_pos, self.index_has_offsets, self.index_has_payloads, )); } let skipper = self.skipper.as_mut().unwrap(); if !self.skipped { debug_assert_ne!(self.skip_offset, -1); // This is the first time this enum has skipped // since reset() was called; load the skip data: skipper.init( self.doc_term_start_fp + self.skip_offset, self.doc_term_start_fp, 0, 0, self.doc_freq, )?; self.skipped = true; } // always plus one to fix the result, since skip position in Lucene50SkipReader // is a little different from MultiLevelSkipListReader let new_doc_upto = skipper.skip_to(target)? + 1; if new_doc_upto > self.doc_upto { // Skipper moved debug_assert_eq!(new_doc_upto % BLOCK_SIZE, 0); self.doc_upto = new_doc_upto; // Force to read next block self.doc_buffer_upto = BLOCK_SIZE; self.accum = skipper.doc(); // actually, this is just lastSkipEntry self.doc_in.as_mut().unwrap().seek(skipper.doc_pointer())?; // now point to the // block we want to // search } // next time we call advance, this is used to // foresee whether skipper is necessary. self.next_skip_doc = skipper.next_skip_doc(); } if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } if self.doc_buffer_upto == BLOCK_SIZE { self.refill_docs()?; } // Now scan... this is an inlined/pared down version // of nextDoc(): loop { self.accum += self.doc_delta_buffer[self.doc_buffer_upto as usize]; self.doc_upto += 1; if self.accum >= target { break; } self.doc_buffer_upto += 1; if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } } self.freq = self.freq_buffer[self.doc_buffer_upto as usize]; self.doc_buffer_upto += 1; self.doc = self.accum; Ok(self.doc) } fn cost(&self) -> usize { self.doc_freq as usize } } struct BlockPostingIterator { encoded: [u8; MAX_ENCODED_SIZE], doc_delta_buffer: [i32; MAX_DATA_SIZE], freq_buffer: [i32; MAX_DATA_SIZE], pos_delta_buffer: [i32; MAX_DATA_SIZE], doc_buffer_upto: i32, pos_buffer_upto: i32, skipper: Option<Lucene50SkipReader>, skipped: bool, start_doc_in: Box<dyn IndexInput>, doc_in: Option<Box<dyn IndexInput>>, pos_in: Box<dyn IndexInput>, index_has_pos: bool, index_has_offsets: bool, index_has_payloads: bool, /// number of docs in this posting list doc_freq: i32, /// number of positions in this posting list total_term_freq: i64, /// how many docs we've read doc_upto: i32, /// doc we last read doc: DocId, /// accumulator for doc deltas accum: i32, /// freq we last read freq: i32, /// current position position: i32, /// how many positions "behind" we are; nextPosition must /// skip these to "catch up": pos_pending_count: i32, /// Lazy pos seek: if != -1 then we must seek to this FP /// before reading positions: pos_pending_fp: i64, /// Where this term's postings start in the .doc file: doc_term_start_fp: i64, /// Where this term's postings start in the .pos file: pos_term_start_fp: i64, /// Where this term's payloads/offsets start in the .pay /// file: pay_term_start_fp: i64, /// File pointer where the last (vInt encoded) pos delta /// block is. We need this to know whether to bulk /// decode vs vInt decode the block: last_pos_block_fp: i64, /// Where this term's skip data starts (after /// docTermStartFP) in the .doc file (or -1 if there is /// no skip data for this term): skip_offset: i64, next_skip_doc: i32, /// docid when there is a single pulsed posting, otherwise -1 singleton_doc_id: i32, for_util: ForUtil, } impl BlockPostingIterator { pub fn new( start_doc_in: Box<dyn IndexInput>, pos_in: Box<dyn IndexInput>, field_info: &FieldInfo, term_state: &BlockTermState, _flags: u16, for_util: ForUtil, ) -> Result<BlockPostingIterator> { let options = &field_info.index_options; let mut iterator = BlockPostingIterator { encoded: [0; MAX_ENCODED_SIZE], start_doc_in, doc_delta_buffer: [0i32; MAX_DATA_SIZE], freq_buffer: [0i32; MAX_DATA_SIZE], pos_delta_buffer: [0i32; MAX_DATA_SIZE], doc_buffer_upto: 0, pos_buffer_upto: 0, skipped: false, skipper: None, doc_in: None, doc_freq: 0, pos_in, total_term_freq: 0, doc_upto: 0, doc: 0, accum: 0, freq: 0, position: 0, pos_pending_count: 0, pos_pending_fp: 0, doc_term_start_fp: 0, pos_term_start_fp: 0, pay_term_start_fp: 0, last_pos_block_fp: 0, skip_offset: 0, next_skip_doc: 0, singleton_doc_id: 0, index_has_pos: options.has_positions(), index_has_offsets: options.has_offsets(), index_has_payloads: field_info.has_store_payloads, for_util, }; iterator.reset(term_state)?; Ok(iterator) } pub fn reset(&mut self, term_state: &BlockTermState) -> Result<()> { self.doc_freq = term_state.doc_freq; self.doc_term_start_fp = term_state.doc_start_fp; self.pos_term_start_fp = term_state.pos_start_fp; self.pay_term_start_fp = term_state.pay_start_fp; self.skip_offset = term_state.skip_offset; self.total_term_freq = term_state.total_term_freq; self.singleton_doc_id = term_state.singleton_doc_id; if self.doc_freq > 1 { if self.doc_in.is_none() { // lazy init self.doc_in = Some(self.start_doc_in.clone()?); } let start = self.doc_term_start_fp; if let Some(ref mut doc_in) = self.doc_in { doc_in.seek(start)?; } } self.pos_pending_fp = self.pos_term_start_fp; self.pos_pending_count = 0; self.last_pos_block_fp = if term_state.total_term_freq < i64::from(BLOCK_SIZE) { self.pos_term_start_fp } else if term_state.total_term_freq == i64::from(BLOCK_SIZE) { -1 } else { self.pos_term_start_fp + term_state.last_pos_block_offset }; self.doc = -1; self.accum = 0; self.doc_upto = 0; self.next_skip_doc = if self.doc_freq > BLOCK_SIZE { // we won't skip if target is found in first block BLOCK_SIZE - 1 } else { // not enough docs for skipping NO_MORE_DOCS }; self.doc_buffer_upto = BLOCK_SIZE; self.skipped = false; Ok(()) } fn refill_docs(&mut self) -> Result<()> { let left = self.doc_freq - self.doc_upto; if left >= BLOCK_SIZE { let doc_in = self.doc_in.as_mut().unwrap(); self.for_util.read_block( doc_in.as_mut(), &mut self.encoded, &mut self.doc_delta_buffer, )?; self.for_util .read_block(doc_in.as_mut(), &mut self.encoded, &mut self.freq_buffer)?; } else if self.doc_freq == 1 { self.doc_delta_buffer[0] = self.singleton_doc_id; self.freq_buffer[0] = self.total_term_freq as i32; } else { // Read vInts: let doc_in = self.doc_in.as_mut().unwrap(); read_vint_block( doc_in.as_mut(), &mut self.doc_delta_buffer, &mut self.freq_buffer, left, true, )?; } self.doc_buffer_upto = 0; Ok(()) } fn refill_positions(&mut self) -> Result<()> { let pos_in = &mut self.pos_in; if pos_in.file_pointer() == self.last_pos_block_fp { let count = (self.total_term_freq % i64::from(BLOCK_SIZE)) as usize; let mut payload_length = 0; for i in 0..count { let code = pos_in.read_vint()?; if self.index_has_payloads { if (code & 1) != 0 { payload_length = pos_in.read_vint()?; } self.pos_delta_buffer[i] = code.unsigned_shift(1); if payload_length != 0 { let fp = pos_in.file_pointer() + i64::from(payload_length); pos_in.seek(fp)?; } } else { self.pos_delta_buffer[i] = code; } if self.index_has_offsets && pos_in.read_vint()? & 1 != 0 { // offset length changed pos_in.read_vint()?; } } } else { self.for_util.read_block( pos_in.as_mut(), &mut self.encoded, &mut self.pos_delta_buffer, )?; } Ok(()) } // TODO: in theory we could avoid loading frq block // when not needed, ie, use skip data to load how far to // seek the pos pointer ... instead of having to load frq // blocks only to sum up how many positions to skip fn skip_positions(&mut self) -> Result<()> { // Skip positions now: let mut to_skip = self.pos_pending_count - self.freq; let left_in_block = BLOCK_SIZE - self.pos_buffer_upto; if to_skip < left_in_block { self.pos_buffer_upto += to_skip; } else { to_skip -= left_in_block; { let pos_in = &mut self.pos_in; while to_skip >= BLOCK_SIZE { debug_assert!(pos_in.file_pointer() != self.last_pos_block_fp); self.for_util.skip_block(pos_in.as_mut())?; to_skip -= BLOCK_SIZE; } } self.refill_positions()?; self.pos_buffer_upto = to_skip; } self.position = 0; Ok(()) } } impl PostingIterator for BlockPostingIterator { fn freq(&self) -> Result<i32> { Ok(self.freq) } fn next_position(&mut self) -> Result<i32> { debug_assert!(self.pos_pending_count > 0); if self.pos_pending_fp != -1 { self.pos_in.seek(self.pos_pending_fp)?; self.pos_pending_fp = -1; // Force buffer refill: self.pos_buffer_upto = BLOCK_SIZE; } if self.pos_pending_count > self.freq { self.skip_positions()?; self.pos_pending_count = self.freq; } if self.pos_buffer_upto == BLOCK_SIZE { self.refill_positions()?; self.pos_buffer_upto = 0; } self.position += self.pos_delta_buffer[self.pos_buffer_upto as usize]; self.pos_buffer_upto += 1; self.pos_pending_count -= 1; Ok(self.position) } fn start_offset(&self) -> Result<i32> { Ok(-1) } fn end_offset(&self) -> Result<i32> { Ok(-1) } fn payload(&self) -> Result<Payload> { Ok(Payload::new()) } } impl DocIterator for BlockPostingIterator { fn doc_id(&self) -> DocId { self.doc } fn next(&mut self) -> Result<DocId> { if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } if self.doc_buffer_upto == BLOCK_SIZE { self.refill_docs()?; } self.accum += self.doc_delta_buffer[self.doc_buffer_upto as usize]; self.freq = self.freq_buffer[self.doc_buffer_upto as usize]; self.pos_pending_count += self.freq; self.doc_buffer_upto += 1; self.doc_upto += 1; self.doc = self.accum; self.position = 0; Ok(self.doc) } fn advance(&mut self, target: DocId) -> Result<i32> { // TODO: make frq block load lazy/skippable if target > self.next_skip_doc { if self.skipper.is_none() { // Lazy init: first time this enum has ever been used for skipping self.skipper = Some(Lucene50SkipReader::new( clone_option_index_input(&self.doc_in)?, MAX_SKIP_LEVELS, self.index_has_pos, self.index_has_offsets, self.index_has_payloads, )); } let skipper = self.skipper.as_mut().unwrap(); if !self.skipped { // This is the first time this enum has skipped // since reset() was called; load the skip data: skipper.init( self.doc_term_start_fp + self.skip_offset, self.doc_term_start_fp, self.pos_term_start_fp, self.pay_term_start_fp, self.doc_freq, )?; self.skipped = true; } // always plus one to fix the result, since skip position in Lucene50SkipReader // is a little different from MultiLevelSkipListReader let new_doc_upto: i32 = skipper.skip_to(target)? + 1; if new_doc_upto > self.doc_upto { // Skipper moved debug_assert!(new_doc_upto % BLOCK_SIZE == 0); self.doc_upto = new_doc_upto; // Force to read next block self.doc_buffer_upto = BLOCK_SIZE; self.accum = skipper.doc(); // actually, this is just lastSkipEntry self.doc_in.as_mut().unwrap().seek(skipper.doc_pointer())?; // now point to the block we want to search self.pos_pending_fp = skipper.pos_pointer(); self.pos_pending_count = skipper.pos_buffer_upto(); } // next time we call advance, this is used to // foresee whether skipper is necessary. self.next_skip_doc = skipper.next_skip_doc(); } if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } if self.doc_buffer_upto == BLOCK_SIZE { self.refill_docs()?; } // Now scan... this is an inlined/pared down version // of nextDoc(): loop { self.accum += self.doc_delta_buffer[self.doc_buffer_upto as usize]; self.freq = self.freq_buffer[self.doc_buffer_upto as usize]; self.pos_pending_count += self.freq; self.doc_buffer_upto += 1; self.doc_upto += 1; if self.accum >= target { break; } if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } } self.position = 0; self.doc = self.accum; Ok(self.doc) } fn cost(&self) -> usize { self.doc_freq as usize } } // Also handles payloads + offsets struct EverythingIterator { encoded: [u8; MAX_ENCODED_SIZE], doc_delta_buffer: [i32; MAX_DATA_SIZE], freq_buffer: [i32; MAX_DATA_SIZE], pos_delta_buffer: [i32; MAX_DATA_SIZE], payload_length_buffer: [i32; MAX_DATA_SIZE], offset_start_delta_buffer: [i32; MAX_DATA_SIZE], offset_length_buffer: [i32; MAX_DATA_SIZE], payload_bytes: Vec<u8>, payload_byte_upto: i32, payload_length: i32, last_start_offset: i32, start_offset: i32, end_offset: i32, doc_buffer_upto: i32, pos_buffer_upto: i32, skipper: Option<Lucene50SkipReader>, skipped: bool, start_doc_in: Box<dyn IndexInput>, doc_in: Option<Box<dyn IndexInput>>, pos_in: Box<dyn IndexInput>, pay_in: Box<dyn IndexInput>, index_has_offsets: bool, index_has_payloads: bool, // number of docs in this posting list doc_freq: i32, // number of positions in this posting list total_term_freq: i64, // how many docs we've read doc_upto: i32, // doc we last read doc: DocId, // accumulator for doc deltas accum: i32, // freq we last read freq: i32, // current position position: i32, // how many positions "behind" we are, nextPosition must // skip these to "catch up": pos_pending_count: i32, // Lazy pos seek: if != -1 then we must seek to this FP // before reading positions: pos_pending_fp: i64, // Lazy pay seek: if != -1 then we must seek to this FP // before reading payloads/offsets: pay_pending_fp: i64, // Where this term's postings start in the .doc file: doc_term_start_fp: i64, // Where this term's postings start in the .pos file: pos_term_start_fp: i64, // Where this term's payloads/offsets start in the .pay // file: pay_term_start_fp: i64, // File pointer where the last (vInt encoded) pos delta // block is. We need this to know whether to bulk // decode vs vInt decode the block: last_pos_block_fp: i64, // Where this term's skip data starts (after // docTermStartFP) in the .doc file (or -1 if there is // no skip data for this term): skip_offset: i64, next_skip_doc: i32, needs_offsets: bool, // true if we actually need offsets needs_payloads: bool, // true if we actually need payloads singleton_doc_id: i32, // docid when there is a single pulsed posting, otherwise -1 for_util: ForUtil, } impl<'a> EverythingIterator { //#[allow(too_many_arguments)] pub fn new( start_doc_in: Box<dyn IndexInput>, pos_in: Box<dyn IndexInput>, pay_in: Box<dyn IndexInput>, field_info: &FieldInfo, term_state: &BlockTermState, flags: u16, for_util: ForUtil, ) -> Result<EverythingIterator> { let encoded = [0u8; MAX_ENCODED_SIZE]; let index_has_offsets = field_info.index_options.has_offsets(); let offset_start_delta_buffer = [0; MAX_DATA_SIZE]; let offset_length_buffer = [0; MAX_DATA_SIZE]; let (start_offset, end_offset) = if index_has_offsets { (0, 0) } else { (-1, -1) }; let index_has_payloads = field_info.has_store_payloads; let payload_bytes = if index_has_payloads { vec![0 as u8; 128] } else { vec![] }; let payload_length_buffer = [0; MAX_DATA_SIZE]; let doc_delta_buffer = [0i32; MAX_DATA_SIZE]; let freq_buffer = [0i32; MAX_DATA_SIZE]; let pos_delta_buffer = [0i32; MAX_DATA_SIZE]; let mut iterator = EverythingIterator { start_doc_in, pay_in, pos_in, encoded, index_has_offsets, offset_start_delta_buffer, offset_length_buffer, start_offset, end_offset, index_has_payloads, payload_length_buffer, payload_bytes, doc_delta_buffer, freq_buffer, pos_delta_buffer, doc_in: None, accum: 0, doc: 0, doc_buffer_upto: 0, doc_term_start_fp: 0, doc_upto: 0, doc_freq: 0, freq: 0, last_pos_block_fp: 0, last_start_offset: 0, needs_offsets: false, needs_payloads: false, next_skip_doc: 0, pay_pending_fp: 0, pay_term_start_fp: 0, payload_byte_upto: 0, payload_length: 0, pos_buffer_upto: 0, pos_pending_count: 0, pos_pending_fp: 0, pos_term_start_fp: 0, position: 0, singleton_doc_id: 0, skip_offset: 0, skipper: None, skipped: false, total_term_freq: 0, for_util, }; iterator.reset(term_state, flags)?; Ok(iterator) } pub fn reset(&mut self, term_state: &BlockTermState, flags: u16) -> Result<()> { self.doc_freq = term_state.doc_freq; self.doc_term_start_fp = term_state.doc_start_fp; self.pos_term_start_fp = term_state.pos_start_fp; self.pay_term_start_fp = term_state.pay_start_fp; self.skip_offset = term_state.skip_offset; self.total_term_freq = term_state.total_term_freq; self.singleton_doc_id = term_state.singleton_doc_id; if self.doc_freq > 1 { if self.doc_in.is_none() { // lazy init self.doc_in = Some(self.start_doc_in.clone()?); } if let Some(ref mut doc_in) = self.doc_in { doc_in.seek(self.doc_term_start_fp)?; } } self.pos_pending_fp = self.pos_term_start_fp; self.pay_pending_fp = self.pay_term_start_fp; self.pos_pending_count = 0; if term_state.total_term_freq < i64::from(BLOCK_SIZE) { self.last_pos_block_fp = self.pos_term_start_fp; } else if term_state.total_term_freq == i64::from(BLOCK_SIZE) { self.last_pos_block_fp = -1; } else { self.last_pos_block_fp = self.pos_term_start_fp + term_state.last_pos_block_offset; } self.needs_offsets = PostingIteratorFlags::feature_requested(flags, PostingIteratorFlags::OFFSETS); self.needs_payloads = PostingIteratorFlags::feature_requested(flags, PostingIteratorFlags::PAYLOADS); self.doc = -1; self.accum = 0; self.doc_upto = 0; self.next_skip_doc = if self.doc_freq > BLOCK_SIZE { // we won't skip if target is found in first block BLOCK_SIZE - 1 } else { // not enough docs for skipping NO_MORE_DOCS }; self.doc_buffer_upto = BLOCK_SIZE; self.skipped = false; Ok(()) } pub fn refill_docs(&mut self) -> Result<()> { let left = self.doc_freq - self.doc_upto; if left >= BLOCK_SIZE { let doc_in = self.doc_in.as_mut().unwrap(); self.for_util.read_block( doc_in.as_mut(), &mut self.encoded, &mut self.doc_delta_buffer, )?; self.for_util .read_block(doc_in.as_mut(), &mut self.encoded, &mut self.freq_buffer)?; } else if self.doc_freq == 1 { self.doc_delta_buffer[0] = self.singleton_doc_id; self.freq_buffer[0] = self.total_term_freq as i32; } else { let doc_in = self.doc_in.as_mut().unwrap(); read_vint_block( doc_in.as_mut(), &mut self.doc_delta_buffer, &mut self.freq_buffer, left, true, )?; } self.doc_buffer_upto = 0; Ok(()) } pub fn refill_positions(&mut self) -> Result<()> { let pos_in = &mut self.pos_in; if pos_in.file_pointer() == self.last_pos_block_fp { let count = (self.total_term_freq % i64::from(BLOCK_SIZE)) as usize; let mut payload_length = 0i32; let mut offset_length = 0i32; let payload_byte_upto = 0i32; for i in 0..count { let code = pos_in.read_vint()?; if self.index_has_payloads { if (code & 1) != 0 { payload_length = pos_in.read_vint()?; } self.payload_length_buffer[i] = payload_length; self.pos_delta_buffer[i] = ((code as u32) >> 1) as i32; if payload_length != 0 { if self.payload_byte_upto + payload_length > self.payload_bytes.len() as i32 { self.payload_bytes .resize((payload_byte_upto + payload_length) as usize, 0); } pos_in.read_exact( &mut self.payload_bytes[self.payload_byte_upto as usize ..(self.payload_byte_upto + payload_length) as usize], )?; self.payload_byte_upto += payload_length; } } else { self.pos_delta_buffer[i] = code; } if self.index_has_offsets { let delta_code = pos_in.read_vint()?; if delta_code & 1 != 0 { offset_length = pos_in.read_vint()?; } self.offset_start_delta_buffer[i] = ((delta_code as u32) >> 1) as i32; self.offset_length_buffer[i] = offset_length; } } self.payload_byte_upto = 0; } else { self.for_util.read_block( pos_in.as_mut(), self.encoded.as_mut(), self.pos_delta_buffer.as_mut(), )?; let pay_in = &mut self.pay_in; if self.index_has_payloads { if self.needs_payloads { self.for_util.read_block( pay_in.as_mut(), &mut self.encoded, self.payload_length_buffer.as_mut(), )?; let num_bytes = pay_in.read_vint()? as usize; if num_bytes > self.payload_bytes.len() { self.payload_bytes.resize(num_bytes, 0); } pay_in.read_exact(&mut self.payload_bytes[0..num_bytes])?; } else { // this works, because when writing a vint block we always force the first // length to be written self.for_util.skip_block(pay_in.as_mut())?; // skip over lengths let num_bytes = pay_in.read_vint()?; // read length of payload_bytes let fp = pay_in.file_pointer(); pay_in.seek(fp + i64::from(num_bytes))?; // skip over payload_bytes } self.payload_byte_upto = 0; } if self.index_has_offsets { if self.needs_offsets { self.for_util.read_block( pay_in.as_mut(), &mut self.encoded, self.offset_start_delta_buffer.as_mut(), )?; self.for_util.read_block( pay_in.as_mut(), &mut self.encoded, self.offset_length_buffer.as_mut(), )?; } else { // this works, because when writing a vint block we always force the first // length to be written self.for_util.skip_block(pay_in.as_mut())?; // skip over starts self.for_util.skip_block(pay_in.as_mut())?; // skip over lengths } } } Ok(()) } // TODO: in theory we could avoid loading frq block // when not needed, ie, use skip data to load how far to // seek the pos pointer ... instead of having to load frq // blocks only to sum up how many positions to skip pub fn skip_positions(&mut self) -> Result<()> { // Skip positions now: let mut to_skip = self.pos_pending_count - self.freq; let left_in_block = BLOCK_SIZE - self.pos_buffer_upto; if to_skip < left_in_block { let end = self.pos_buffer_upto + to_skip; while self.pos_buffer_upto < end { if self.index_has_payloads { self.payload_byte_upto += self.payload_length_buffer[self.pos_buffer_upto as usize]; } self.pos_buffer_upto += 1; } } else { to_skip -= left_in_block; while to_skip >= BLOCK_SIZE { self.for_util.skip_block(self.pos_in.as_mut())?; if self.index_has_payloads { // Skip payload_length block: let pay_in = &mut self.pay_in; self.for_util.skip_block(pay_in.as_mut())?; // Skip payload_bytes block: let num_bytes = pay_in.read_vint()?; let fp = pay_in.file_pointer(); pay_in.seek(fp + i64::from(num_bytes))?; } if self.index_has_offsets { let pay_in = &mut self.pay_in; self.for_util.skip_block(pay_in.as_mut())?; self.for_util.skip_block(pay_in.as_mut())?; } to_skip -= BLOCK_SIZE; } self.refill_positions()?; self.payload_byte_upto = 0; self.pos_buffer_upto = 0; while self.pos_buffer_upto < to_skip { if self.index_has_payloads { self.payload_byte_upto += self.payload_length_buffer[self.pos_buffer_upto as usize]; } self.pos_buffer_upto += 1; } } self.position = 0; self.last_start_offset = 0; Ok(()) } #[allow(dead_code)] pub fn check_integrity(&self) -> Result<()> { // if let Some(ref doc_in) = self.doc_in { // codec_util::checksum_entire_file(doc_in.as_ref())?; // } // // codec_util::checksum_entire_file(self.pos_in.as_ref())?; // codec_util::checksum_entire_file(self.pay_in.as_ref())?; Ok(()) } } impl PostingIterator for EverythingIterator { fn freq(&self) -> Result<i32> { Ok(self.freq) } fn next_position(&mut self) -> Result<i32> { debug_assert!(self.pos_pending_count > 0); if self.pos_pending_fp != -1 { self.pos_in.seek(self.pos_pending_fp)?; self.pos_pending_fp = -1; if self.pay_pending_fp != -1 { self.pay_in.seek(self.pay_pending_fp)?; self.pay_pending_fp = -1; } // Force buffer refill: self.pos_buffer_upto = BLOCK_SIZE; } if self.pos_pending_count > self.freq { self.skip_positions()?; self.pos_pending_count = self.freq; } if self.pos_buffer_upto == BLOCK_SIZE { self.refill_positions()?; self.pos_buffer_upto = 0; } self.position += self.pos_delta_buffer[self.pos_buffer_upto as usize]; if self.index_has_payloads { debug_assert!(!self.payload_length_buffer.is_empty()); // debug_assert!(!self.payload_bytes.is_empty()); self.payload_length = self.payload_length_buffer[self.pos_buffer_upto as usize]; self.payload_byte_upto += self.payload_length; } if self.index_has_offsets { debug_assert!(!self.offset_start_delta_buffer.is_empty()); debug_assert!(!self.offset_length_buffer.is_empty()); self.start_offset = self.last_start_offset + self.offset_start_delta_buffer[self.pos_buffer_upto as usize]; self.end_offset = self.start_offset + self.offset_length_buffer[self.pos_buffer_upto as usize]; self.last_start_offset = self.start_offset; } self.pos_buffer_upto += 1; self.pos_pending_count -= 1; Ok(self.position) } fn start_offset(&self) -> Result<i32> { Ok(self.start_offset) } fn end_offset(&self) -> Result<i32> { Ok(self.end_offset) } fn payload(&self) -> Result<Payload> { if self.payload_length == 0 { Ok(vec![]) } else { let start = self.payload_byte_upto as usize; let end = start + self.payload_length as usize; Ok(self.payload_bytes[start..end].to_vec()) } } } impl DocIterator for EverythingIterator { fn doc_id(&self) -> DocId { self.doc } fn next(&mut self) -> Result<DocId> { if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } if self.doc_buffer_upto == BLOCK_SIZE { self.refill_docs()?; } self.accum += self.doc_delta_buffer[self.doc_buffer_upto as usize]; self.freq = self.freq_buffer[self.doc_buffer_upto as usize]; self.pos_pending_count += self.freq; self.doc_buffer_upto += 1; self.doc_upto += 1; self.doc = self.accum; self.position = 0; self.last_start_offset = 0; Ok(self.doc) } fn advance(&mut self, target: DocId) -> Result<DocId> { // TODO: make frq block load lazy/skippable if target > self.next_skip_doc { if self.skipper.is_none() { // Lazy init: first time this enum has ever been used for skipping self.skipper = Some(Lucene50SkipReader::new( IndexInput::clone(self.doc_in.as_mut().unwrap().as_mut())?, MAX_SKIP_LEVELS, true, self.index_has_offsets, self.index_has_payloads, )); } if !self.skipped { // This is the first time this enum has skipped // since reset() was called; load the skip data: if let Some(ref mut skipper) = self.skipper { skipper.init( self.doc_term_start_fp + self.skip_offset, self.doc_term_start_fp, self.pos_term_start_fp, self.pay_term_start_fp, self.doc_freq, )?; } self.skipped = true; } let new_doc_upto: i32 = self.skipper.as_mut().unwrap().skip_to(target)? + 1; if new_doc_upto > self.doc_upto { // Skipper moved self.doc_upto = new_doc_upto; // Force to read next block self.doc_buffer_upto = BLOCK_SIZE; let skipper = self.skipper.as_ref().unwrap(); self.accum = skipper.doc(); self.doc_in.as_mut().unwrap().seek(skipper.doc_pointer())?; self.pos_pending_fp = skipper.pos_pointer(); self.pay_pending_fp = skipper.pay_pointer(); self.pos_pending_count = skipper.pos_buffer_upto(); self.last_start_offset = 0; // new document self.payload_byte_upto = skipper.payload_byte_upto(); } self.next_skip_doc = self.skipper.as_ref().unwrap().next_skip_doc(); } if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } if self.doc_buffer_upto == BLOCK_SIZE { self.refill_docs()?; } // Now scan: loop { self.accum += self.doc_delta_buffer[self.doc_buffer_upto as usize]; self.freq = self.freq_buffer[self.doc_buffer_upto as usize]; self.pos_pending_count += self.freq; self.doc_buffer_upto += 1; self.doc_upto += 1; if self.accum >= target { break; } if self.doc_upto == self.doc_freq { self.doc = NO_MORE_DOCS; return Ok(self.doc); } } self.position = 0; self.last_start_offset = 0; self.doc = self.accum; Ok(self.doc) } fn cost(&self) -> usize { self.doc_freq as usize } } /// `PostingIterator` impl for `Lucene50PostingsReader` pub struct Lucene50PostingIterator(Lucene50PostingIterEnum); enum Lucene50PostingIterEnum { Doc(BlockDocIterator), Posting(BlockPostingIterator), Everything(EverythingIterator), } impl PostingIterator for Lucene50PostingIterator { fn freq(&self) -> Result<i32> { match &self.0 { Lucene50PostingIterEnum::Doc(i) => i.freq(), Lucene50PostingIterEnum::Posting(i) => i.freq(), Lucene50PostingIterEnum::Everything(i) => i.freq(), } } fn next_position(&mut self) -> Result<i32> { match &mut self.0 { Lucene50PostingIterEnum::Doc(i) => i.next_position(), Lucene50PostingIterEnum::Posting(i) => i.next_position(), Lucene50PostingIterEnum::Everything(i) => i.next_position(), } } fn start_offset(&self) -> Result<i32> { match &self.0 { Lucene50PostingIterEnum::Doc(i) => i.start_offset(), Lucene50PostingIterEnum::Posting(i) => i.start_offset(), Lucene50PostingIterEnum::Everything(i) => i.start_offset(), } } fn end_offset(&self) -> Result<i32> { match &self.0 { Lucene50PostingIterEnum::Doc(i) => i.end_offset(), Lucene50PostingIterEnum::Posting(i) => i.end_offset(), Lucene50PostingIterEnum::Everything(i) => i.end_offset(), } } fn payload(&self) -> Result<Payload> { match &self.0 { Lucene50PostingIterEnum::Doc(i) => i.payload(), Lucene50PostingIterEnum::Posting(i) => i.payload(), Lucene50PostingIterEnum::Everything(i) => i.payload(), } } } impl DocIterator for Lucene50PostingIterator { fn doc_id(&self) -> DocId { match &self.0 { Lucene50PostingIterEnum::Doc(i) => i.doc_id(), Lucene50PostingIterEnum::Posting(i) => i.doc_id(), Lucene50PostingIterEnum::Everything(i) => i.doc_id(), } } fn next(&mut self) -> Result<DocId> { match &mut self.0 { Lucene50PostingIterEnum::Doc(i) => i.next(), Lucene50PostingIterEnum::Posting(i) => i.next(), Lucene50PostingIterEnum::Everything(i) => i.next(), } } fn advance(&mut self, target: i32) -> Result<DocId> { match &mut self.0 { Lucene50PostingIterEnum::Doc(i) => i.advance(target), Lucene50PostingIterEnum::Posting(i) => i.advance(target), Lucene50PostingIterEnum::Everything(i) => i.advance(target), } } fn slow_advance(&mut self, target: i32) -> Result<DocId> { match &mut self.0 { Lucene50PostingIterEnum::Doc(i) => i.slow_advance(target), Lucene50PostingIterEnum::Posting(i) => i.slow_advance(target), Lucene50PostingIterEnum::Everything(i) => i.slow_advance(target), } } fn cost(&self) -> usize { match &self.0 { Lucene50PostingIterEnum::Doc(i) => i.cost(), Lucene50PostingIterEnum::Posting(i) => i.cost(), Lucene50PostingIterEnum::Everything(i) => i.cost(), } } fn matches(&mut self) -> Result<bool> { match &mut self.0 { Lucene50PostingIterEnum::Doc(i) => i.matches(), Lucene50PostingIterEnum::Posting(i) => i.matches(), Lucene50PostingIterEnum::Everything(i) => i.matches(), } } fn match_cost(&self) -> f32 { match &self.0 { Lucene50PostingIterEnum::Doc(i) => i.match_cost(), Lucene50PostingIterEnum::Posting(i) => i.match_cost(), Lucene50PostingIterEnum::Everything(i) => i.match_cost(), } } fn approximate_next(&mut self) -> Result<DocId> { match &mut self.0 { Lucene50PostingIterEnum::Doc(i) => i.approximate_next(), Lucene50PostingIterEnum::Posting(i) => i.approximate_next(), Lucene50PostingIterEnum::Everything(i) => i.approximate_next(), } } fn approximate_advance(&mut self, target: i32) -> Result<DocId> { match &mut self.0 { Lucene50PostingIterEnum::Doc(i) => i.approximate_advance(target), Lucene50PostingIterEnum::Posting(i) => i.approximate_advance(target), Lucene50PostingIterEnum::Everything(i) => i.approximate_advance(target), } } }
33.707596
119
0.549626
8fedd69b6a663e5bc2cfdfa9073220d57a07149f
62
mod dispatcher; pub use dispatcher::WasmExecutionDispatcher;
15.5
44
0.83871
e648e5a04665f435ebf13fba2e9284bd3f4d993b
1,513
#![feature(asm)] #![feature(default_free_fn)] #![feature(alloc_error_handler)] #![feature(const_panic)] #![no_main] #![no_std] #[macro_use] extern crate alloc; extern crate rv64; mod cpu; mod kalloc; mod kvm; mod memorylayout; mod param; mod plic; mod proc; mod riscv; mod start; mod trap; mod uart; mod vm; use crate::cpu::get_cpuid; use crate::kalloc::init_heap; use crate::kvm::{init_kvm, init_page}; use crate::plic::{init_plic, init_hartplic}; use crate::proc::init_proc; use crate::uart::UART; use crate::trap::{init_harttrap, intr_on, intr_off}; use linked_list_allocator::LockedHeap; use alloc::alloc::Layout; #[no_mangle] pub fn main() -> ! { if get_cpuid() == 0 { let mut m_uart = UART.lock(); m_uart.puts("rrxv6 start\n"); drop(m_uart); init_heap(); // initialize physical memory allocator init_kvm(); // initialize kernel page table init_page(); // initialize virtual memory init_proc(); // initialize process table init_harttrap(); // install kernel trap vector init_plic(); // initialize PLIC interrupt controller init_hartplic(); // ask PLIC for device interrupt let mut m_uart = UART.lock(); m_uart.puts("OS started\n"); drop(m_uart); } intr_on(); loop {} } #[global_allocator] static ALLOCATOR: LockedHeap = LockedHeap::empty(); #[alloc_error_handler] fn alloc_error_handler(layout: Layout) -> ! { panic!("allocation error {:?}", layout); }
22.58209
64
0.652346
4a5ff4aceeeff9c6387d428f62fadf2561fe3ad5
35,235
// Std use std::{ borrow::Cow, cmp, collections::BTreeMap, io::{self, Write}, usize, }; // Internal use crate::{ build::{App, AppSettings, Arg, ArgSettings}, output::{fmt::Colorizer, Usage}, parse::Parser, util::VecMap, INTERNAL_ERROR_MSG, }; // Third party use indexmap::IndexSet; use unicode_width::UnicodeWidthStr; pub(crate) fn dimensions() -> Option<(usize, usize)> { #[cfg(not(feature = "wrap_help"))] return None; #[cfg(feature = "wrap_help")] terminal_size::terminal_size().map(|(w, h)| (w.0.into(), h.0.into())) } fn str_width(s: &str) -> usize { UnicodeWidthStr::width(s) } const TAB: &str = " "; pub(crate) enum HelpWriter<'writer> { Normal(&'writer mut dyn Write), Buffer(&'writer mut Colorizer), } /// `clap` Help Writer. /// /// Wraps a writer stream providing different methods to generate help for `clap` objects. pub(crate) struct Help<'help, 'app, 'parser, 'writer> { writer: HelpWriter<'writer>, parser: &'parser Parser<'help, 'app>, next_line_help: bool, hide_pv: bool, term_w: usize, longest: usize, force_next_line: bool, use_long: bool, } // Public Functions impl<'help, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { const DEFAULT_TEMPLATE: &'static str = "\ {before-help}{bin} {version}\n\ {author-with-newline}{about-with-newline}\n\ USAGE:\n {usage}\n\ \n\ {all-args}{after-help}\ "; const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\ {before-help}{bin} {version}\n\ {author-with-newline}{about-with-newline}\n\ USAGE:\n {usage}{after-help}\ "; /// Create a new `Help` instance. pub(crate) fn new( w: HelpWriter<'writer>, parser: &'parser Parser<'help, 'app>, use_long: bool, ) -> Self { debug!("Help::new"); let term_w = match parser.app.term_w { Some(0) => usize::MAX, Some(w) => w, None => cmp::min( dimensions().map_or(100, |(w, _)| w), match parser.app.max_w { None | Some(0) => usize::MAX, Some(mw) => mw, }, ), }; let nlh = parser.is_set(AppSettings::NextLineHelp); let hide_pv = parser.is_set(AppSettings::HidePossibleValuesInHelp); Help { writer: w, parser, next_line_help: nlh, hide_pv, term_w, longest: 0, force_next_line: false, use_long, } } /// Writes the parser help to the wrapped stream. pub(crate) fn write_help(&mut self) -> io::Result<()> { debug!("Help::write_help"); if let Some(h) = self.parser.app.help_str { self.none(h)?; } else if let Some(tmpl) = self.parser.app.template { self.write_templated_help(tmpl)?; } else { let flags = self.parser.has_flags(); let pos = self.parser.has_positionals(); let opts = self.parser.has_opts(); let subcmds = self.parser.has_subcommands(); if flags || opts || pos || subcmds { self.write_templated_help(Self::DEFAULT_TEMPLATE)?; } else { self.write_templated_help(Self::DEFAULT_NO_ARGS_TEMPLATE)?; } } self.none("\n")?; Ok(()) } } macro_rules! write_method { ($_self:ident, $msg:ident, $meth:ident) => { match &mut $_self.writer { HelpWriter::Buffer(c) => { c.$meth(($msg).into()); Ok(()) } HelpWriter::Normal(w) => w.write_all($msg.as_ref()), } }; } macro_rules! write_nspaces { ($_self:ident, $num:expr) => {{ debug!("Help::write_nspaces!: num={}", $num); for _ in 0..$num { $_self.none(" ")?; } }}; } // Methods to write Arg help. impl<'help, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { fn good<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { write_method!(self, msg, good) } fn warning<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { write_method!(self, msg, warning) } fn none<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { write_method!(self, msg, none) } /// Writes help for each argument in the order they were declared to the wrapped stream. fn write_args_unsorted(&mut self, args: &[&Arg<'help>]) -> io::Result<()> { debug!("Help::write_args_unsorted"); // The shortest an arg can legally be is 2 (i.e. '-x') self.longest = 2; let mut arg_v = Vec::with_capacity(10); let use_long = self.use_long; for arg in args.iter().filter(|arg| should_show_arg(use_long, *arg)) { if arg.longest_filter() { self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str())); } arg_v.push(arg) } let mut first = true; let arg_c = arg_v.len(); for (i, arg) in arg_v.iter().enumerate() { if first { first = false; } else { self.none("\n")?; } self.write_arg(arg, i < arg_c)?; } Ok(()) } /// Sorts arguments by length and display order and write their help to the wrapped stream. fn write_args(&mut self, args: &[&Arg<'help>]) -> io::Result<()> { debug!("Help::write_args"); // The shortest an arg can legally be is 2 (i.e. '-x') self.longest = 2; let mut ord_m = VecMap::new(); let use_long = self.use_long; // Determine the longest for arg in args.iter().filter(|arg| { // If it's NextLineHelp we don't care to compute how long it is because it may be // NextLineHelp on purpose simply *because* it's so long and would throw off all other // args alignment should_show_arg(use_long, *arg) }) { if arg.longest_filter() { debug!("Help::write_args: Current Longest...{}", self.longest); self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str())); debug!("Help::write_args: New Longest...{}", self.longest); } let btm = ord_m.entry(arg.disp_ord).or_insert(BTreeMap::new()); // We use name here for alphabetic sorting // @TODO @maybe perhaps we could do some sort of ordering off of keys? btm.insert(arg.name, arg); } let mut first = true; for btm in ord_m.values() { for arg in btm.values() { if first { first = false; } else { self.none("\n")?; } self.write_arg(arg, false)?; } } Ok(()) } /// Writes help for an argument to the wrapped stream. fn write_arg(&mut self, arg: &Arg<'help>, prevent_nlh: bool) -> io::Result<()> { debug!("Help::write_arg"); self.short(arg)?; self.long(arg)?; let spec_vals = self.val(arg)?; self.help(arg, &*spec_vals, prevent_nlh)?; Ok(()) } /// Writes argument's short command to the wrapped stream. fn short(&mut self, arg: &Arg<'help>) -> io::Result<()> { debug!("Help::short"); self.none(TAB)?; if let Some(s) = arg.short { self.good(&format!("-{}", s)) } else if arg.has_switch() { self.none(TAB) } else { Ok(()) } } /// Writes argument's long command to the wrapped stream. fn long(&mut self, arg: &Arg<'help>) -> io::Result<()> { debug!("Help::long"); if !arg.has_switch() { return Ok(()); } if arg.is_set(ArgSettings::TakesValue) { if let Some(l) = arg.long { if arg.short.is_some() { self.none(", ")?; } self.good(&format!("--{}", l))? } let sep = if arg.is_set(ArgSettings::RequireEquals) { "=" } else { " " }; self.none(sep)?; } else if let Some(l) = arg.long { if arg.short.is_some() { self.none(", ")?; } self.good(&format!("--{}", l))?; } Ok(()) } /// Writes argument's possible values to the wrapped stream. fn val(&mut self, arg: &Arg) -> Result<String, io::Error> { debug!("Help::val: arg={}", arg.name); let mult = arg.is_set(ArgSettings::MultipleValues) || arg.is_set(ArgSettings::MultipleOccurrences); if arg.is_set(ArgSettings::TakesValue) || arg.index.is_some() { let delim = if arg.is_set(ArgSettings::RequireDelimiter) { arg.val_delim.expect(INTERNAL_ERROR_MSG) } else { ' ' }; if !arg.val_names.is_empty() { let mut it = arg.val_names.iter().peekable(); while let Some((_, val)) = it.next() { self.good(&format!("<{}>", val))?; if it.peek().is_some() { self.none(&delim.to_string())?; } } let num = arg.val_names.len(); if mult && num == 1 { self.good("...")?; } } else if let Some(num) = arg.num_vals { let mut it = (0..num).peekable(); while let Some(_) = it.next() { self.good(&format!("<{}>", arg.name))?; if it.peek().is_some() { self.none(&delim.to_string())?; } } if mult && num == 1 { self.good("...")?; } } else if arg.has_switch() { self.good(&format!("<{}>", arg.name))?; if mult { self.good("...")?; } } else { self.good(&arg.to_string())?; } } let spec_vals = self.spec_vals(arg); let h = arg.about.unwrap_or(""); let h_w = str_width(h) + str_width(&*spec_vals); let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp); let taken = self.longest + 12; self.force_next_line = !nlh && self.term_w >= taken && (taken as f32 / self.term_w as f32) > 0.40 && h_w > (self.term_w - taken); debug!("Help::val: Has switch..."); if self.use_long { // long help prints messages on the next line so it don't need to align text debug!("Help::val: printing long help so skip aligment"); } else if arg.has_switch() { debug!("Yes"); debug!("Help::val: force_next_line...{:?}", self.force_next_line); debug!("Help::val: nlh...{:?}", nlh); debug!("Help::val: taken...{}", taken); debug!( "val: help_width > (width - taken)...{} > ({} - {})", h_w, self.term_w, taken ); debug!("Help::val: longest...{}", self.longest); debug!("Help::val: next_line..."); if !(nlh || self.force_next_line) { debug!("No"); let self_len = str_width(arg.to_string().as_str()); // subtract ourself let mut spcs = self.longest - self_len; // Since we're writing spaces from the tab point we first need to know if we // had a long and short, or just short if arg.long.is_some() { // Only account 4 after the val spcs += 4; } else { // Only account for ', --' + 4 after the val spcs += 8; } write_nspaces!(self, spcs); } else { debug!("Yes"); } } else if !(nlh || self.force_next_line) { debug!("No, and not next_line"); write_nspaces!( self, self.longest + 4 - (str_width(arg.to_string().as_str())) ); } else { debug!("No"); } Ok(spec_vals) } fn write_before_after_help(&mut self, h: &str) -> io::Result<()> { debug!("Help::write_before_after_help"); let mut help = String::from(h); // determine if our help fits or needs to wrap debug!( "Help::write_before_after_help: Term width...{}", self.term_w ); let too_long = str_width(h) >= self.term_w; debug!("Help::write_before_after_help: Too long..."); if too_long { debug!("Yes"); debug!("Help::write_before_after_help: help: {}", help); debug!( "Help::write_before_after_help: help width: {}", str_width(&*help) ); // Determine how many newlines we need to insert debug!( "Help::write_before_after_help: Usable space: {}", self.term_w ); help = wrap_help(&help, self.term_w); } else { debug!("No"); } self.none(&help)?; Ok(()) } /// Writes argument's help to the wrapped stream. fn help(&mut self, arg: &Arg, spec_vals: &str, prevent_nlh: bool) -> io::Result<()> { debug!("Help::help"); let h = if self.use_long { arg.long_about.unwrap_or_else(|| arg.about.unwrap_or("")) } else { arg.about.unwrap_or_else(|| arg.long_about.unwrap_or("")) }; let mut help = String::from(h) + spec_vals; let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp) || self.use_long; debug!("Help::help: Next Line...{:?}", nlh); let spcs = if nlh || self.force_next_line { 12 // "tab" * 3 } else { self.longest + 12 }; let too_long = spcs + str_width(h) + str_width(&*spec_vals) >= self.term_w; // Is help on next line, if so then indent if nlh || self.force_next_line { self.none(&format!("\n{}{}{}", TAB, TAB, TAB))?; } debug!("Help::help: Too long..."); if too_long && spcs <= self.term_w { debug!("Yes"); debug!("Help::help: help...{}", help); debug!("Help::help: help width...{}", str_width(&*help)); // Determine how many newlines we need to insert let avail_chars = self.term_w - spcs; debug!("Help::help: Usable space...{}", avail_chars); help = wrap_help(&help, avail_chars); } else { debug!("No"); } if let Some(part) = help.lines().next() { self.none(part)?; } for part in help.lines().skip(1) { self.none("\n")?; if nlh || self.force_next_line { self.none(&format!("{}{}{}", TAB, TAB, TAB))?; } else if arg.has_switch() { write_nspaces!(self, self.longest + 12); } else { write_nspaces!(self, self.longest + 8); } self.none(part)?; } if !prevent_nlh && (nlh || self.force_next_line) { self.none("\n")?; } Ok(()) } fn spec_vals(&self, a: &Arg) -> String { debug!("Help::spec_vals: a={}", a); let mut spec_vals = vec![]; if let Some(ref env) = a.env { debug!( "Help::spec_vals: Found environment variable...[{:?}:{:?}]", env.0, env.1 ); let env_val = if !a.is_set(ArgSettings::HideEnvValues) { format!( "={}", env.1 .as_ref() .map_or(Cow::Borrowed(""), |val| val.to_string_lossy()) ) } else { String::new() }; let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val); spec_vals.push(env_info); } if !a.is_set(ArgSettings::HideDefaultValue) && !a.default_vals.is_empty() { debug!( "Help::spec_vals: Found default value...[{:?}]", a.default_vals ); let pvs = a .default_vals .iter() .map(|&pvs| pvs.to_string_lossy()) .collect::<Vec<_>>() .join(" "); spec_vals.push(format!("[default: {}]", pvs)); } if !a.aliases.is_empty() { debug!("Help::spec_vals: Found aliases...{:?}", a.aliases); let als = a .aliases .iter() .filter(|&als| als.1) // visible .map(|&als| als.0) // name .collect::<Vec<_>>() .join(", "); if !als.is_empty() { spec_vals.push(format!("[aliases: {}]", als)); } } if !a.short_aliases.is_empty() { debug!( "Help::spec_vals: Found short aliases...{:?}", a.short_aliases ); let als = a .short_aliases .iter() .filter(|&als| als.1) // visible .map(|&als| als.0.to_string()) // name .collect::<Vec<_>>() .join(", "); if !als.is_empty() { spec_vals.push(format!("[short aliases: {}]", als)); } } if !self.hide_pv && !a.is_set(ArgSettings::HidePossibleValues) && !a.possible_vals.is_empty() { debug!( "Help::spec_vals: Found possible vals...{:?}", a.possible_vals ); spec_vals.push(format!("[possible values: {}]", a.possible_vals.join(", "))); } let prefix = if !spec_vals.is_empty() && !a.get_about().unwrap_or("").is_empty() { " " } else { "" }; prefix.to_string() + &spec_vals.join(" ") } } /// Methods to write a single subcommand impl<'help, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { fn write_subcommand(&mut self, sc_str: &str, app: &App<'help>) -> io::Result<()> { debug!("Help::write_subcommand"); self.none(TAB)?; self.good(sc_str)?; let spec_vals = self.sc_val(sc_str, app)?; self.sc_help(app, &*spec_vals)?; Ok(()) } fn sc_val(&mut self, sc_str: &str, app: &App) -> Result<String, io::Error> { debug!("Help::sc_val: app={}", app.name); let spec_vals = self.sc_spec_vals(app); let h = app.about.unwrap_or(""); let h_w = str_width(h) + str_width(&*spec_vals); let nlh = self.next_line_help; let taken = self.longest + 12; self.force_next_line = !nlh && self.term_w >= taken && (taken as f32 / self.term_w as f32) > 0.40 && h_w > (self.term_w - taken); if !(nlh || self.force_next_line) { write_nspaces!(self, self.longest + 4 - (str_width(sc_str))); } Ok(spec_vals) } fn sc_spec_vals(&self, a: &App) -> String { debug!("Help::sc_spec_vals: a={}", a.name); let mut spec_vals = vec![]; if !a.aliases.is_empty() || !a.short_flag_aliases.is_empty() { debug!("Help::spec_vals: Found aliases...{:?}", a.aliases); debug!( "Help::spec_vals: Found short flag aliases...{:?}", a.short_flag_aliases ); let mut short_als = a .get_visible_short_flag_aliases() .map(|a| format!("-{}", a)) .collect::<Vec<_>>(); let als = a.get_visible_aliases().map(|s| s.to_string()); short_als.extend(als); let all_als = short_als.join(", "); if !all_als.is_empty() { spec_vals.push(format!(" [aliases: {}]", all_als)); } } spec_vals.join(" ") } fn sc_help(&mut self, app: &App<'help>, spec_vals: &str) -> io::Result<()> { debug!("Help::sc_help"); let h = if self.use_long { app.long_about.unwrap_or_else(|| app.about.unwrap_or("")) } else { app.about.unwrap_or_else(|| app.long_about.unwrap_or("")) }; let mut help = String::from(h) + spec_vals; let nlh = self.next_line_help || self.use_long; debug!("Help::sc_help: Next Line...{:?}", nlh); let spcs = if nlh || self.force_next_line { 12 // "tab" * 3 } else { self.longest + 12 }; let too_long = spcs + str_width(h) + str_width(&*spec_vals) >= self.term_w; // Is help on next line, if so then indent if nlh || self.force_next_line { self.none(&format!("\n{}{}{}", TAB, TAB, TAB))?; } debug!("Help::sc_help: Too long..."); if too_long && spcs <= self.term_w { debug!("Yes"); debug!("Help::sc_help: help...{}", help); debug!("Help::sc_help: help width...{}", str_width(&*help)); // Determine how many newlines we need to insert let avail_chars = self.term_w - spcs; debug!("Help::sc_help: Usable space...{}", avail_chars); help = wrap_help(&help, avail_chars); } else { debug!("No"); } if let Some(part) = help.lines().next() { self.none(part)?; } for part in help.lines().skip(1) { self.none("\n")?; if nlh || self.force_next_line { self.none(&format!("{}{}{}", TAB, TAB, TAB))?; } else { write_nspaces!(self, self.longest + 8); } self.none(part)?; } if !help.contains('\n') && (nlh || self.force_next_line) { self.none("\n")?; } Ok(()) } } // Methods to write Parser help. impl<'help, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { /// Writes help for all arguments (options, flags, args, subcommands) /// including titles of a Parser Object to the wrapped stream. pub(crate) fn write_all_args(&mut self) -> io::Result<()> { debug!("Help::write_all_args"); let flags = self.parser.has_flags(); let pos = self .parser .app .get_positionals() .filter(|arg| should_show_arg(self.use_long, arg)) .any(|_| true); let opts = self .parser .app .get_opts_with_no_heading() .filter(|arg| should_show_arg(self.use_long, arg)) .collect::<Vec<_>>(); let subcmds = self.parser.has_visible_subcommands(); let custom_headings = self .parser .app .args .args .iter() .filter_map(|arg| arg.help_heading) .collect::<IndexSet<_>>(); let mut first = if pos { self.warning("ARGS:\n")?; self.write_args_unsorted(&self.parser.app.get_positionals().collect::<Vec<_>>())?; false } else { true }; let unified_help = self.parser.is_set(AppSettings::UnifiedHelpMessage); if unified_help && (flags || !opts.is_empty()) { let opts_flags = self .parser .app .args .args .iter() .filter(|a| a.has_switch()) .collect::<Vec<_>>(); if !first { self.none("\n\n")?; } self.warning("OPTIONS:\n")?; self.write_args(&*opts_flags)?; first = false; } else { if flags { if !first { self.none("\n\n")?; } self.warning("FLAGS:\n")?; let flags_v: Vec<_> = self.parser.app.get_flags_with_no_heading().collect(); self.write_args(&flags_v)?; first = false; } if !opts.is_empty() { if !first { self.none("\n\n")?; } self.warning("OPTIONS:\n")?; self.write_args(&opts)?; first = false; } if !custom_headings.is_empty() { for heading in custom_headings { if !first { self.none("\n\n")?; } self.warning(&*format!("{}:\n", heading))?; let args = self .parser .app .args .args .iter() .filter(|a| { if let Some(help_heading) = a.help_heading { return help_heading == heading; } false }) .collect::<Vec<_>>(); self.write_args(&*args)?; first = false } } } if subcmds { if !first { self.none("\n\n")?; } self.warning(self.parser.app.subcommand_header.unwrap_or("SUBCOMMANDS"))?; self.warning(":\n")?; self.write_subcommands(&self.parser.app)?; } Ok(()) } /// Writes help for subcommands of a Parser Object to the wrapped stream. fn write_subcommands(&mut self, app: &App<'help>) -> io::Result<()> { debug!("Help::write_subcommands"); // The shortest an arg can legally be is 2 (i.e. '-x') self.longest = 2; let mut ord_m = VecMap::new(); for sc in app .subcommands .iter() .filter(|s| !s.is_set(AppSettings::Hidden)) { let btm = ord_m.entry(sc.disp_ord).or_insert(BTreeMap::new()); let mut sc_str = String::new(); sc_str.push_str(&sc.short_flag.map_or(String::new(), |c| format!("-{}, ", c))); sc_str.push_str(&sc.long_flag.map_or(String::new(), |c| format!("--{}, ", c))); sc_str.push_str(&sc.name); self.longest = cmp::max(self.longest, str_width(&sc_str)); btm.insert(sc_str, sc.clone()); } debug!("Help::write_subcommands longest = {}", self.longest); let mut first = true; for btm in ord_m.values() { for (sc_str, sc) in btm { if first { first = false; } else { self.none("\n")?; } self.write_subcommand(sc_str, sc)?; } } Ok(()) } /// Writes binary name of a Parser Object to the wrapped stream. fn write_bin_name(&mut self) -> io::Result<()> { debug!("Help::write_bin_name"); let term_w = self.term_w; macro_rules! write_name { () => {{ self.good(&*wrap_help(&self.parser.app.name, term_w))?; }}; } if let Some(bn) = self.parser.app.bin_name.as_ref() { if bn.contains(' ') { // In case we're dealing with subcommands i.e. git mv is translated to git-mv self.good(&bn.replace(" ", "-"))? } else { write_name!(); } } else { write_name!(); } Ok(()) } } // Methods to write Parser help using templates. impl<'help, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { /// Write help to stream for the parser in the format defined by the template. /// /// For details about the template language see [`App::help_template`]. /// /// [`App::help_template`]: ./struct.App.html#method.help_template fn write_templated_help(&mut self, template: &str) -> io::Result<()> { debug!("Help::write_templated_help"); // The strategy is to copy the template from the reader to wrapped stream // until a tag is found. Depending on its value, the appropriate content is copied // to the wrapped stream. // The copy from template is then resumed, repeating this sequence until reading // the complete template. macro_rules! tags { ( match $part:ident { $( $tag:expr => $action:stmt )* } ) => { match $part { $( part if part.starts_with(concat!($tag, "}")) => { $action let rest = &part[$tag.len()+1..]; self.none(rest)?; } )* // Unknown tag, write it back. part => { self.none("{")?; self.none(part)?; } } }; } let mut parts = template.split('{'); if let Some(first) = parts.next() { self.none(first)?; } for part in parts { tags! { match part { "bin" => { self.write_bin_name()?; } "version" => { if let Some(s) = self.parser.app.version { self.none(s)?; } } "author" => { if let Some(s) = self.parser.app.author { self.none(&wrap_help(s, self.term_w))?; } } "author-with-newline" => { if let Some(s) = self.parser.app.author { self.none(&wrap_help(s, self.term_w))?; self.none("\n")?; } } "about" => { let about = if self.use_long { self.parser.app.long_about.or(self.parser.app.about) } else { self.parser.app.about }; if let Some(output) = about { self.none(wrap_help(output, self.term_w))?; } } "about-with-newline" => { let about = if self.use_long { self.parser.app.long_about.or(self.parser.app.about) } else { self.parser.app.about }; if let Some(output) = about { self.none(wrap_help(output, self.term_w))?; self.none("\n")?; } } "usage" => { self.none(Usage::new(self.parser).create_usage_no_title(&[]))?; } "all-args" => { self.write_all_args()?; } "unified" => { let opts_flags = self .parser .app .args .args .iter() .filter(|a| a.has_switch()) .collect::<Vec<_>>(); self.write_args(&opts_flags)?; } "flags" => { self.write_args(&self.parser.app.get_flags_with_no_heading().collect::<Vec<_>>())?; } "options" => { self.write_args(&self.parser.app.get_opts_with_no_heading().collect::<Vec<_>>())?; } "positionals" => { self.write_args(&self.parser.app.get_positionals().collect::<Vec<_>>())?; } "subcommands" => { self.write_subcommands(self.parser.app)?; } "after-help" => { let after_help = if self.use_long { self.parser .app .after_long_help .or(self.parser.app.after_help) } else { self.parser.app.after_help }; if let Some(output) = after_help { self.none("\n\n")?; self.write_before_after_help(output)?; } } "before-help" => { let before_help = if self.use_long { self.parser .app .before_long_help .or(self.parser.app.before_help) } else { self.parser.app.before_help }; if let Some(output) = before_help { self.write_before_after_help(output)?; self.none("\n\n")?; } } } } } Ok(()) } } fn should_show_arg(use_long: bool, arg: &Arg) -> bool { debug!("should_show_arg: use_long={:?}, arg={}", use_long, arg.name); if arg.is_set(ArgSettings::Hidden) { return false; } (!arg.is_set(ArgSettings::HiddenLongHelp) && use_long) || (!arg.is_set(ArgSettings::HiddenShortHelp) && !use_long) || arg.is_set(ArgSettings::NextLineHelp) } fn wrap_help(help: &str, avail_chars: usize) -> String { let wrapper = textwrap::Wrapper::new(avail_chars).break_words(false); help.lines() .map(|line| wrapper.fill(line)) .collect::<Vec<String>>() .join("\n") } #[cfg(test)] mod test { use super::wrap_help; #[test] fn wrap_help_last_word() { let help = String::from("foo bar baz"); assert_eq!(wrap_help(&help, 5), "foo\nbar\nbaz"); } }
34.275292
107
0.449354
01f3b106d346e306bb59457fa0d994df99a96d48
3,119
use proc_macro2::{Literal, TokenStream as TokenStream2}; use super::repr::Repr; use super::{DeriveData, ToVariantTrait}; pub(crate) fn expand_to_variant( trait_kind: ToVariantTrait, derive_data: DeriveData, ) -> Result<TokenStream2, syn::Error> { let DeriveData { ident, repr, mut generics, } = derive_data; let trait_path = trait_kind.trait_path(); let to_variant_fn = trait_kind.to_variant_fn(); let to_variant_receiver = trait_kind.to_variant_receiver(); let derived = crate::automatically_derived(); for param in generics.type_params_mut() { param.default = None; } let return_expr = match repr { Repr::Struct(var_repr) => { let destructure_pattern = var_repr.destructure_pattern(); let to_variant = var_repr.make_to_variant_expr(trait_kind)?; quote! { { let #ident #destructure_pattern = self; #to_variant } } } Repr::Enum(variants) => { if variants.is_empty() { quote! { unreachable!("this is an uninhabitable enum"); } } else { let match_arms = variants .iter() .map(|(var_ident, var_repr)| { let destructure_pattern = var_repr.destructure_pattern(); let to_variant = var_repr.make_to_variant_expr(trait_kind)?; let var_ident_string = format!("{}", var_ident); let var_ident_string_literal = Literal::string(&var_ident_string); let tokens = quote! { #ident::#var_ident #destructure_pattern => { let __dict = ::gdnative::core_types::Dictionary::new(); let __key = ::gdnative::core_types::ToVariant::to_variant( &::gdnative::core_types::GodotString::from(#var_ident_string_literal) ); let __value = #to_variant; __dict.insert(&__key, &__value); ::gdnative::core_types::ToVariant::to_variant(&__dict.into_shared()) } }; Ok(tokens) }).collect::<Result<Vec<_>,syn::Error>>()?; quote! { match #to_variant_receiver { #( #match_arms ),* } } } } }; let where_clause = &generics.where_clause; let result = quote! { #derived impl #generics #trait_path for #ident #generics #where_clause { fn #to_variant_fn(#to_variant_receiver) -> ::gdnative::core_types::Variant { use #trait_path; use ::gdnative::core_types::FromVariant; #return_expr } } }; Ok(result) }
35.443182
105
0.491504
16a539cddbe01d57aedca9d35473d0af13944a5a
3,783
use anyhow::*; use image::GenericImageView; pub struct Texture { pub texture: wgpu::Texture, pub view: wgpu::TextureView, pub sampler: wgpu::Sampler, } impl Texture { pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; pub fn create_depth_texture( device: &wgpu::Device, sc_desc: &wgpu::SwapChainDescriptor, label: &str, ) -> Self { let size = wgpu::Extent3d { width: sc_desc.width, height: sc_desc.height, depth: 1, }; let desc = wgpu::TextureDescriptor { label: Some(label), size, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: Self::DEPTH_FORMAT, usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT | wgpu::TextureUsage::SAMPLED, }; let texture = device.create_texture(&desc); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Nearest, compare: Some(wgpu::CompareFunction::GreaterEqual), lod_min_clamp: -100.0, lod_max_clamp: 100.0, ..Default::default() }); Self { texture, view, sampler, } } pub fn from_bytes( device: &wgpu::Device, queue: &wgpu::Queue, bytes: &[u8], label: &str, ) -> Result<Self> { let img = image::load_from_memory(bytes)?; Self::from_image(device, queue, &img, Some(label)) } pub fn from_image( device: &wgpu::Device, queue: &wgpu::Queue, img: &image::DynamicImage, label: Option<&str>, ) -> Result<Self> { let rgba = img.as_rgba8().unwrap(); let dimensions = img.dimensions(); let size = wgpu::Extent3d { width: dimensions.0, height: dimensions.1, depth: 1, }; let texture = device.create_texture(&wgpu::TextureDescriptor { label, size, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST, }); queue.write_texture( wgpu::TextureCopyView { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, }, rgba, wgpu::TextureDataLayout { offset: 0, bytes_per_row: 4 * dimensions.0, rows_per_image: dimensions.1, }, size, ); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Nearest, mipmap_filter: wgpu::FilterMode::Nearest, ..Default::default() }); Ok(Self { texture, view, sampler, }) } }
31.008197
87
0.546127
0ec4be7b5183aa221f633a31be848c8509da3985
34,525
//! The main (and only) Sharded gossiping strategy #![warn(missing_docs)] use crate::agent_store::AgentInfoSigned; use crate::gossip::simple_bloom::{decode_bloom_filter, encode_bloom_filter}; use crate::types::event::*; use crate::types::gossip::*; use crate::types::*; use ghost_actor::dependencies::tracing; use governor::clock::DefaultClock; use governor::state::{InMemoryState, NotKeyed}; use governor::RateLimiter; use kitsune_p2p_timestamp::Timestamp; use kitsune_p2p_types::codec::Codec; use kitsune_p2p_types::config::*; use kitsune_p2p_types::dht_arc::{ArcInterval, DhtArcSet}; use kitsune_p2p_types::metrics::*; use kitsune_p2p_types::tx2::tx2_api::*; use kitsune_p2p_types::tx2::tx2_utils::*; use kitsune_p2p_types::*; use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::atomic::AtomicBool; use std::sync::Arc; use std::time::{Duration, SystemTime}; use tokio::time::Instant; use self::bandwidth::BandwidthThrottle; use self::metrics::Metrics; use self::state_map::RoundStateMap; use super::simple_bloom::{HowToConnect, MetaOpKey}; pub use bandwidth::BandwidthThrottles; mod accept; mod agents; mod bloom; mod initiate; mod ops; mod state_map; mod store; mod bandwidth; mod metrics; mod next_target; #[cfg(all(test, feature = "test_utils"))] mod tests; /// max send buffer size (keep it under 16384 with a little room for overhead) /// (this is not a tuning_param because it must be coordinated /// with the constant in PoolBuf which cannot be set at runtime) const MAX_SEND_BUF_BYTES: usize = 16000; /// The maximum number of different nodes that will be /// gossiped with if gossip is triggered. const MAX_TRIGGERS: u8 = 2; /// The timeout for a gossip round if there is no contact. One minute. const ROUND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); type BloomFilter = bloomfilter::Bloom<Arc<MetaOpKey>>; type EventSender = futures::channel::mpsc::Sender<event::KitsuneP2pEvent>; struct TimedBloomFilter { /// The bloom filter for the time window. /// If this is none then we have no hashes /// for this time window. bloom: Option<BloomFilter>, /// The time window for this bloom filter. time: TimeWindow, } /// Gossip has two distinct variants which share a lot of similarities but /// are fundamentally different and serve different purposes #[derive(Debug, Clone, Copy)] pub enum GossipType { /// The Recent gossip type is aimed at rapidly syncing the most recent /// data. It runs frequently and expects frequent diffs at each round. Recent, /// The Historical gossip type is aimed at comprehensively syncing the /// entire common history of two nodes, filling in gaps in the historical /// data. It runs less frequently, and expects diffs to be infrequent /// at each round. Historical, } /// The entry point for the sharded gossip strategy. /// /// This struct encapsulates the network communication concerns, mainly /// managing the incoming and outgoing gossip queues. It contains a struct /// which handles all other (local) aspects of gossip. pub struct ShardedGossip { /// ShardedGossipLocal handles the non-networking concerns of gossip gossip: ShardedGossipLocal, // The endpoint to use for all outgoing comms ep_hnd: Tx2EpHnd<wire::Wire>, /// The internal mutable state inner: Share<ShardedGossipState>, /// Bandwidth for incoming and outgoing gossip. bandwidth: Arc<BandwidthThrottle>, } /// Basic statistic for gossip loop processing performance. struct Stats { start: Instant, avg_processing_time: std::time::Duration, max_processing_time: std::time::Duration, count: u32, } impl Stats { /// Reset the stats. fn reset() -> Self { Stats { start: Instant::now(), avg_processing_time: std::time::Duration::default(), max_processing_time: std::time::Duration::default(), count: 0, } } } impl ShardedGossip { /// Constructor pub fn new( tuning_params: KitsuneP2pTuningParams, space: Arc<KitsuneSpace>, ep_hnd: Tx2EpHnd<wire::Wire>, evt_sender: EventSender, gossip_type: GossipType, bandwidth: Arc<BandwidthThrottle>, ) -> Arc<Self> { let this = Arc::new(Self { ep_hnd, inner: Share::new(Default::default()), gossip: ShardedGossipLocal { tuning_params, space, evt_sender, inner: Share::new(ShardedGossipLocalState::default()), gossip_type, closing: AtomicBool::new(false), }, bandwidth, }); metric_task({ let this = this.clone(); async move { let mut stats = Stats::reset(); while !this .gossip .closing .load(std::sync::atomic::Ordering::Relaxed) { tokio::time::sleep(std::time::Duration::from_millis(10)).await; this.run_one_iteration().await; this.stats(&mut stats); } KitsuneResult::Ok(()) } }); this } async fn process_outgoing(&self, outgoing: Outgoing) -> KitsuneResult<()> { let (_endpoint, how, gossip) = outgoing; let s = tracing::trace_span!("process_outgoing", cert = ?_endpoint.cert(), agents = ?self.gossip.show_local_agents()); s.in_scope(|| tracing::trace!(?gossip)); let gossip = gossip.encode_vec().map_err(KitsuneError::other)?; let bytes = gossip.len(); let gossip = wire::Wire::gossip( self.gossip.space.clone(), gossip.into(), self.gossip.gossip_type.into(), ); let timeout = self.gossip.tuning_params.implicit_timeout(); let con = match how { HowToConnect::Con(con, remote_url) => { if con.is_closed() { self.ep_hnd.get_connection(remote_url, timeout).await? } else { con } } HowToConnect::Url(url) => self.ep_hnd.get_connection(url, timeout).await?, }; // Wait for enough available outgoing bandwidth here before // actually sending the gossip. self.bandwidth.outgoing_bytes(bytes).await; con.notify(&gossip, timeout).await?; Ok(()) } async fn process_incoming_outgoing(&self) -> KitsuneResult<()> { let (incoming, outgoing) = self.pop_queues()?; if let Some((con, remote_url, msg, bytes)) = incoming { self.bandwidth.incoming_bytes(bytes).await; let outgoing = match self.gossip.process_incoming(con.peer_cert(), msg).await { Ok(r) => r, Err(e) => { self.gossip.remove_state(&con.peer_cert(), true).await?; vec![ShardedGossipWire::error(e.to_string())] } }; self.inner.share_mut(|i, _| { i.outgoing.extend(outgoing.into_iter().map(|msg| { ( GossipTgt::new(Vec::with_capacity(0), con.peer_cert()), HowToConnect::Con(con.clone(), remote_url.clone()), msg, ) })); Ok(()) })?; } if let Some(outgoing) = outgoing { let cert = outgoing.0.cert().clone(); if let Err(err) = self.process_outgoing(outgoing).await { self.gossip.remove_state(&cert, true).await?; tracing::error!( "Gossip failed to send outgoing message because of: {:?}", err ); } } if self.gossip.should_local_sync()? { self.gossip.local_sync().await?; } Ok(()) } async fn run_one_iteration(&self) { match self.gossip.try_initiate().await { Ok(Some(outgoing)) => { if let Err(err) = self.inner.share_mut(|i, _| { i.outgoing.push_back(outgoing); Ok(()) }) { tracing::error!( "Gossip failed to get share nut when trying to initiate with {:?}", err ); } } Ok(None) => (), Err(err) => tracing::error!("Gossip failed when trying to initiate with {:?}", err), } if let Err(err) = self.process_incoming_outgoing().await { tracing::error!("Gossip failed to process a message because of: {:?}", err); } self.gossip.record_timeouts(); } fn pop_queues(&self) -> KitsuneResult<(Option<Incoming>, Option<Outgoing>)> { self.inner.share_mut(move |inner, _| { let incoming = inner.incoming.pop_front(); let outgoing = inner.outgoing.pop_front(); Ok((incoming, outgoing)) }) } /// Log the statistics for the gossip loop. fn stats(&self, stats: &mut Stats) { if let GossipType::Recent = self.gossip.gossip_type { let elapsed = stats.start.elapsed(); stats.avg_processing_time += elapsed; stats.max_processing_time = std::cmp::max(stats.max_processing_time, elapsed); stats.count += 1; if elapsed.as_secs() > 5 { stats.avg_processing_time = stats .avg_processing_time .checked_div(stats.count) .unwrap_or_default(); let _ = self.gossip.inner.share_mut(|i, _| { let s = tracing::trace_span!("gossip_metrics"); s.in_scope(|| tracing::trace!("{}\nStats over last 5s:\n\tAverage processing time {:?}\n\tIteration count: {}\n\tMax gossip processing time: {:?}", i.metrics, stats.avg_processing_time, stats.count, stats.max_processing_time)); Ok(()) }); *stats = Stats::reset(); } } } } /// The parts of sharded gossip which are concerned only with the gossiping node: /// - managing local state /// - making requests to the local backend /// - processing incoming messages to produce outgoing messages (which actually) /// get sent by the enclosing `ShardedGossip` pub struct ShardedGossipLocal { gossip_type: GossipType, tuning_params: KitsuneP2pTuningParams, space: Arc<KitsuneSpace>, evt_sender: EventSender, inner: Share<ShardedGossipLocalState>, closing: AtomicBool, } /// Incoming gossip. type Incoming = (Tx2ConHnd<wire::Wire>, TxUrl, ShardedGossipWire, usize); /// Outgoing gossip. type Outgoing = (GossipTgt, HowToConnect, ShardedGossipWire); type StateKey = Tx2Cert; /// The internal mutable state for [`ShardedGossipLocal`] #[derive(Default)] pub struct ShardedGossipLocalState { /// The list of agents on this node local_agents: HashSet<Arc<KitsuneAgent>>, /// If Some, we are in the process of trying to initiate gossip with this target. initiate_tgt: Option<(GossipTgt, u32, Option<tokio::time::Instant>)>, round_map: RoundStateMap, /// Metrics that track remote node states and help guide /// the next node to gossip with. metrics: Metrics, #[allow(dead_code)] /// Last moment we locally synced. last_local_sync: Option<Instant>, /// Trigger local sync to run on the next iteration. trigger_local_sync: bool, } impl ShardedGossipLocalState { fn remove_state(&mut self, state_key: &StateKey, error: bool) -> Option<RoundState> { // Check if the round to be removed matches the current initiate_tgt let init_tgt = self .initiate_tgt .as_ref() .map(|tgt| tgt.0.cert() == state_key) .unwrap_or(false); if init_tgt { self.initiate_tgt = None; } let r = self.round_map.remove(state_key); if r.is_some() { if error { self.metrics.record_error(state_key.clone()); } else { self.metrics.record_success(state_key.clone()); } } else if init_tgt && error { self.metrics.record_error(state_key.clone()); } r } fn check_tgt_expired(&mut self) { if let Some((cert, when_initiated)) = self .initiate_tgt .as_ref() .map(|tgt| (tgt.0.cert().clone(), tgt.2)) { // Check if no current round exists and we've timed out the initiate. let no_current_round_exist = !self.round_map.round_exists(&cert); match when_initiated { Some(when_initiated) if no_current_round_exist && when_initiated.elapsed() > ROUND_TIMEOUT => { self.metrics.record_error(cert); self.initiate_tgt = None; } None if no_current_round_exist => { self.initiate_tgt = None; } _ => (), } } } fn new_integrated_data(&mut self) -> KitsuneResult<()> { let s = tracing::trace_span!("gossip_trigger", agents = ?self.show_local_agents()); s.in_scope(|| self.log_state()); self.metrics.record_force_initiate(); self.trigger_local_sync = true; Ok(()) } fn show_local_agents(&self) -> &HashSet<Arc<KitsuneAgent>> { &self.local_agents } fn log_state(&self) { tracing::trace!( ?self.round_map, ?self.initiate_tgt, ) } } /// The internal mutable state for [`ShardedGossip`] #[derive(Default)] pub struct ShardedGossipState { incoming: VecDeque<Incoming>, outgoing: VecDeque<Outgoing>, } /// The state representing a single active ongoing "round" of gossip with a /// remote node #[derive(Debug, Clone)] pub struct RoundState { /// The common ground with our gossip partner for the purposes of this round common_arc_set: Arc<DhtArcSet>, /// Number of ops blooms we have sent for this round, which is also the /// number of MissingOps sets we expect in response num_sent_ops_blooms: u8, /// We've received the last op bloom filter from our partner /// (the one with `finished` == true) received_all_incoming_ops_blooms: bool, /// Round start time created_at: Instant, /// Last moment we had any contact for this round. last_touch: Instant, /// Amount of time before a round is considered expired. round_timeout: std::time::Duration, } impl ShardedGossipLocal { const TGT_FP: f64 = 0.01; /// This should give us just under 16MB for the bloom filter. /// Based on a compression of 75%. const UPPER_HASHES_BOUND: usize = 500; /// Calculate the time range for a gossip round. fn calculate_time_ranges(&self) -> Vec<TimeWindow> { const NOW: Duration = Duration::from_secs(0); const HOUR: Duration = Duration::from_secs(60 * 60); const DAY: Duration = Duration::from_secs(60 * 60 * 24); const WEEK: Duration = Duration::from_secs(60 * 60 * 24 * 7); const MONTH: Duration = Duration::from_secs(60 * 60 * 24 * 7 * 30); const START_OF_TIME: Duration = Duration::MAX; match self.gossip_type { GossipType::Recent => { vec![time_range(HOUR, NOW)] } GossipType::Historical => { vec![ time_range(DAY, HOUR), time_range(WEEK, DAY), time_range(MONTH, WEEK), time_range(START_OF_TIME, MONTH), ] } } } fn new_state(&self, common_arc_set: Arc<DhtArcSet>) -> KitsuneResult<RoundState> { Ok(RoundState { common_arc_set, num_sent_ops_blooms: 0, received_all_incoming_ops_blooms: false, created_at: Instant::now(), last_touch: Instant::now(), round_timeout: ROUND_TIMEOUT, }) } async fn get_state(&self, id: &StateKey) -> KitsuneResult<Option<RoundState>> { self.inner .share_mut(|i, _| Ok(i.round_map.get(id).cloned())) } async fn remove_state(&self, id: &StateKey, error: bool) -> KitsuneResult<Option<RoundState>> { self.inner.share_mut(|i, _| Ok(i.remove_state(id, error))) } async fn remove_target(&self, id: &StateKey, error: bool) -> KitsuneResult<()> { self.inner.share_mut(|i, _| { if i.initiate_tgt .as_ref() .map(|tgt| tgt.0.cert() == id) .unwrap_or(false) { i.initiate_tgt = None; if error { i.metrics.record_error(id.clone()); } else { i.metrics.record_success(id.clone()); } } Ok(()) }) } async fn incoming_ops_finished( &self, state_id: &StateKey, ) -> KitsuneResult<Option<RoundState>> { self.inner.share_mut(|i, _| { let finished = i .round_map .get_mut(state_id) .map(|state| { state.received_all_incoming_ops_blooms = true; state.num_sent_ops_blooms == 0 }) .unwrap_or(true); if finished { Ok(i.remove_state(state_id, false)) } else { Ok(i.round_map.get(state_id).cloned()) } }) } async fn decrement_ops_blooms(&self, state_id: &StateKey) -> KitsuneResult<Option<RoundState>> { self.inner.share_mut(|i, _| { let update_state = |state: &mut RoundState| { let num_ops_blooms = state.num_sent_ops_blooms.saturating_sub(1); state.num_sent_ops_blooms = num_ops_blooms; state.num_sent_ops_blooms == 0 && state.received_all_incoming_ops_blooms }; if i.round_map .get_mut(state_id) .map(update_state) .unwrap_or(true) { Ok(i.remove_state(state_id, false)) } else { Ok(i.round_map.get(state_id).cloned()) } }) } async fn process_incoming( &self, cert: Tx2Cert, msg: ShardedGossipWire, ) -> KitsuneResult<Vec<ShardedGossipWire>> { let s = tracing::trace_span!("process_incoming", ?cert, agents = ?self.show_local_agents(), ?msg); s.in_scope(|| self.log_state()); // If we don't have the state for a message then the other node will need to timeout. Ok(match msg { ShardedGossipWire::Initiate(Initiate { intervals, id }) => { self.incoming_initiate(cert, intervals, id).await? } ShardedGossipWire::Accept(Accept { intervals }) => { self.incoming_accept(cert, intervals).await? } ShardedGossipWire::Agents(Agents { filter }) => { if let Some(state) = self.get_state(&cert).await? { let filter = decode_bloom_filter(&filter); self.incoming_agents(state, filter).await? } else { Vec::with_capacity(0) } } ShardedGossipWire::MissingAgents(MissingAgents { agents }) => { if let Some(state) = self.get_state(&cert).await? { self.incoming_missing_agents(state, agents.as_slice()) .await?; } Vec::with_capacity(0) } ShardedGossipWire::Ops(Ops { missing_hashes, finished, }) => { let state = if finished { self.incoming_ops_finished(&cert).await? } else { self.get_state(&cert).await? }; match state { Some(state) => match missing_hashes { EncodedTimedBloomFilter::NoOverlap => Vec::with_capacity(0), EncodedTimedBloomFilter::MissingAllHashes { time_window } => { let filter = TimedBloomFilter { bloom: None, time: time_window, }; self.incoming_ops(state, filter).await? } EncodedTimedBloomFilter::HaveHashes { filter, time_window, } => { let filter = TimedBloomFilter { bloom: Some(decode_bloom_filter(&filter)), time: time_window, }; self.incoming_ops(state, filter).await? } }, None => Vec::with_capacity(0), } } ShardedGossipWire::MissingOps(MissingOps { ops, finished }) => { let state = if finished { self.decrement_ops_blooms(&cert).await? } else { self.get_state(&cert).await? }; if let Some(state) = state { self.incoming_missing_ops(state, ops).await?; } Vec::with_capacity(0) } ShardedGossipWire::NoAgents(_) => { self.remove_state(&cert, true).await?; Vec::with_capacity(0) } ShardedGossipWire::AlreadyInProgress(_) => { self.remove_target(&cert, false).await?; Vec::with_capacity(0) } ShardedGossipWire::Error(Error { message }) => { tracing::warn!("gossiping with: {:?} and got error: {}", cert, message); self.remove_state(&cert, true).await?; Vec::with_capacity(0) } }) } async fn local_sync(&self) -> KitsuneResult<()> { let local_agents = self.inner.share_mut(|i, _| Ok(i.local_agents.clone()))?; let agent_arcs = store::local_agent_arcs(&self.evt_sender, &self.space, &local_agents).await?; let arcs: Vec<_> = agent_arcs.iter().map(|(_, arc)| arc.clone()).collect(); let arcset = local_sync_arcset(arcs.as_slice()); let op_hashes = store::all_op_hashes_within_arcset( &self.evt_sender, &self.space, agent_arcs.as_slice(), &arcset, full_time_window(), usize::MAX, true, ) .await? .map(|(ops, _window)| ops) .unwrap_or_default(); let ops: Vec<_> = store::fetch_ops( &self.evt_sender, &self.space, local_agents.iter(), op_hashes, ) .await? .into_iter() .collect(); store::put_ops(&self.evt_sender, &self.space, agent_arcs, ops).await?; Ok(()) } /// Check if we should locally sync fn should_local_sync(&self) -> KitsuneResult<bool> { // Historical gossip should not locally sync. if matches!(self.gossip_type, GossipType::Historical) || self.tuning_params.gossip_single_storage_arc_per_space { return Ok(false); } let update_last_sync = |i: &mut ShardedGossipLocalState, _: &mut bool| { if i.local_agents.len() < 2 { Ok(false) } else if i.trigger_local_sync { // We are force triggering a local sync. i.trigger_local_sync = false; i.last_local_sync = Some(Instant::now()); let s = tracing::trace_span!("trigger",agents = ?i.show_local_agents(), i.trigger_local_sync); s.in_scope(|| tracing::trace!("Force local sync")); Ok(true) } else if i .last_local_sync .as_ref() .map(|s| s.elapsed().as_millis() as u32) .unwrap_or(u32::MAX) >= self.tuning_params.gossip_local_sync_delay_ms { // It's been long enough since the last local sync. i.last_local_sync = Some(Instant::now()); Ok(true) } else { // Otherwise it's not time to sync. Ok(false) } }; self.inner.share_mut(update_last_sync) } /// Record all timed out rounds into metrics fn record_timeouts(&self) { self.inner .share_mut(|i, _| { for cert in i.round_map.take_timed_out_rounds() { i.metrics.record_error(cert); } Ok(()) }) .ok(); } fn show_local_agents(&self) -> HashSet<Arc<KitsuneAgent>> { self.inner .share_mut(|i, _| Ok(i.local_agents.clone())) .unwrap_or_default() } fn log_state(&self) { self.inner .share_mut(|i, _| { i.log_state(); Ok(()) }) .ok(); } } /// Calculates the arcset used during local sync. This arcset determines the /// minimum set of ops to be spread across all local agents in order to reach /// local consistency fn local_sync_arcset(arcs: &[ArcInterval]) -> DhtArcSet { arcs.iter() .enumerate() // For each agent's arc, .map(|(i, arc_i)| { // find the union of all arcs *other* than this one, let other_arcset = arcs .iter() .enumerate() .filter_map(|(j, arc_j)| { if i == j { None } else { Some(DhtArcSet::from(arc_j)) } }) .fold(DhtArcSet::new_empty(), |a, b| DhtArcSet::union(&a, &b)); // and return the intersection of this arc with the union of the others. DhtArcSet::from(arc_i).intersection(&other_arcset) }) // and take the union of all of the intersections .fold(DhtArcSet::new_empty(), |a, b| DhtArcSet::union(&a, &b)) } impl RoundState { fn increment_sent_ops_blooms(&mut self) -> u8 { self.num_sent_ops_blooms += 1; self.num_sent_ops_blooms } } /// Time range from now into the past. /// Start must be < end. fn time_range(start: Duration, end: Duration) -> TimeWindow { // TODO: write in terms of chrono::now() let now = SystemTime::now(); let start = now .checked_sub(start) .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok()) .map(|t| Timestamp::from_micros(t.as_micros() as i64)) .unwrap_or(Timestamp::MIN); let end = now .checked_sub(end) .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok()) .map(|t| Timestamp::from_micros(t.as_micros() as i64)) .unwrap_or(Timestamp::MAX); start..end } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] /// An encoded timed bloom filter of missing op hashes. pub enum EncodedTimedBloomFilter { /// I have no overlap with your agents /// Pleas don't send any ops. NoOverlap, /// I have overlap and I have no hashes. /// Please send all your ops. MissingAllHashes { /// The time window that we are missing hashes for. time_window: TimeWindow, }, /// I have overlap and I have some hashes. /// Please send any missing ops. HaveHashes { /// The encoded bloom filter. filter: PoolBuf, /// The time window these hashes are for. time_window: TimeWindow, }, } kitsune_p2p_types::write_codec_enum! { /// SimpleBloom Gossip Wire Protocol Codec codec ShardedGossipWire { /// Initiate a round of gossip with a remote node Initiate(0x10) { /// The list of arc intervals (equivalent to a [`DhtArcSet`]) /// for all local agents intervals.0: Vec<ArcInterval>, /// A random number to resolve concurrent initiates. id.1: u32, }, /// Accept an incoming round of gossip from a remote node Accept(0x20) { /// The list of arc intervals (equivalent to a [`DhtArcSet`]) /// for all local agents intervals.0: Vec<ArcInterval>, }, /// Send Agent Info Bloom Agents(0x30) { /// The bloom filter for agent data filter.0: PoolBuf, }, /// Any agents that were missing from the remote bloom. MissingAgents(0x40) { /// The missing agents agents.0: Vec<Arc<AgentInfoSigned>>, }, /// Send Ops Bloom Ops(0x50) { /// The bloom filter for op data missing_hashes.0: EncodedTimedBloomFilter, /// Is this the last bloom to be sent? finished.1: bool, }, /// Any ops that were missing from the remote bloom. MissingOps(0x60) { /// The missing ops ops.0: Vec<(Arc<KitsuneOpHash>, Vec<u8>)>, /// Is this the last chunk of ops to be sent in response /// to the bloom filter that we're responding to? finished.1: bool, }, /// The node you are trying to gossip with has no agents anymore. NoAgents(0x80) { }, /// You have sent a stale initiate to a node /// that already has an active round with you. AlreadyInProgress(0x90) { }, /// The node you are gossiping with has hit an error condition /// and failed to respond to a request. Error(0x11) { /// The error message. message.0: String, }, } } impl AsGossipModule for ShardedGossip { fn incoming_gossip( &self, con: Tx2ConHnd<wire::Wire>, remote_url: TxUrl, gossip_data: Box<[u8]>, ) -> KitsuneResult<()> { use kitsune_p2p_types::codec::*; let (bytes, gossip) = ShardedGossipWire::decode_ref(&gossip_data).map_err(KitsuneError::other)?; self.inner.share_mut(move |i, _| { i.incoming .push_back((con, remote_url, gossip, bytes as usize)); if i.incoming.len() > 20 { tracing::warn!( "Overloaded with incoming gossip.. {} messages", i.incoming.len() ); } Ok(()) }) } fn local_agent_join(&self, a: Arc<KitsuneAgent>) { let _ = self.gossip.inner.share_mut(move |i, _| { i.new_integrated_data()?; i.local_agents.insert(a); let s = tracing::trace_span!("gossip_trigger", agents = ?i.show_local_agents(), msg = "New agent joining"); s.in_scope(|| i.log_state()); Ok(()) }); } fn local_agent_leave(&self, a: Arc<KitsuneAgent>) { let _ = self.gossip.inner.share_mut(move |i, _| { i.local_agents.remove(&a); Ok(()) }); } fn close(&self) { self.gossip .closing .store(true, std::sync::atomic::Ordering::Relaxed); } fn new_integrated_data(&self) { let _ = self.gossip.inner.share_mut(move |i, _| { i.new_integrated_data()?; let s = tracing::trace_span!("gossip_trigger", agents = ?i.show_local_agents(), msg = "New integrated data"); s.in_scope(|| i.log_state()); Ok(()) }); } } struct ShardedRecentGossipFactory { bandwidth: Arc<BandwidthThrottle>, } impl ShardedRecentGossipFactory { fn new(bandwidth: Arc<BandwidthThrottle>) -> Self { Self { bandwidth } } } impl AsGossipModuleFactory for ShardedRecentGossipFactory { fn spawn_gossip_task( &self, tuning_params: KitsuneP2pTuningParams, space: Arc<KitsuneSpace>, ep_hnd: Tx2EpHnd<wire::Wire>, evt_sender: futures::channel::mpsc::Sender<event::KitsuneP2pEvent>, ) -> GossipModule { GossipModule(ShardedGossip::new( tuning_params, space, ep_hnd, evt_sender, GossipType::Recent, self.bandwidth.clone(), )) } } struct ShardedHistoricalGossipFactory { bandwidth: Arc<BandwidthThrottle>, } impl ShardedHistoricalGossipFactory { fn new(bandwidth: Arc<BandwidthThrottle>) -> Self { Self { bandwidth } } } impl AsGossipModuleFactory for ShardedHistoricalGossipFactory { fn spawn_gossip_task( &self, tuning_params: KitsuneP2pTuningParams, space: Arc<KitsuneSpace>, ep_hnd: Tx2EpHnd<wire::Wire>, evt_sender: futures::channel::mpsc::Sender<event::KitsuneP2pEvent>, ) -> GossipModule { GossipModule(ShardedGossip::new( tuning_params, space, ep_hnd, evt_sender, GossipType::Historical, self.bandwidth.clone(), )) } } /// Create a recent [`GossipModuleFactory`] pub fn recent_factory(bandwidth: Arc<BandwidthThrottle>) -> GossipModuleFactory { GossipModuleFactory(Arc::new(ShardedRecentGossipFactory::new(bandwidth))) } /// Create a [`GossipModuleFactory`] pub fn historical_factory(bandwidth: Arc<BandwidthThrottle>) -> GossipModuleFactory { GossipModuleFactory(Arc::new(ShardedHistoricalGossipFactory::new(bandwidth))) } #[allow(dead_code)] fn clamp64(u: u64) -> i64 { if u > i64::MAX as u64 { i64::MAX } else { u as i64 } } impl From<GossipType> for GossipModuleType { fn from(g: GossipType) -> Self { match g { GossipType::Recent => GossipModuleType::ShardedRecent, GossipType::Historical => GossipModuleType::ShardedHistorical, } } }
34.421735
247
0.555134
9cb6eff1d95fcdaa2ab7559e43b723b6d66b449a
766,060
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] /* automatically generated by rust-bindgen */ pub const TRUE: u32 = 1; pub const FALSE: u32 = 0; pub const NULL: u32 = 0; pub const DAQmx_Buf_Input_BufSize: u32 = 6252; pub const DAQmx_Buf_Input_OnbrdBufSize: u32 = 8970; pub const DAQmx_Buf_Output_BufSize: u32 = 6253; pub const DAQmx_Buf_Output_OnbrdBufSize: u32 = 8971; pub const DAQmx_SelfCal_Supported: u32 = 6240; pub const DAQmx_SelfCal_LastTemp: u32 = 6244; pub const DAQmx_ExtCal_RecommendedInterval: u32 = 6248; pub const DAQmx_ExtCal_LastTemp: u32 = 6247; pub const DAQmx_Cal_UserDefinedInfo: u32 = 6241; pub const DAQmx_Cal_UserDefinedInfo_MaxSize: u32 = 6428; pub const DAQmx_Cal_DevTemp: u32 = 8763; pub const DAQmx_Cal_AccConnectionCount: u32 = 12267; pub const DAQmx_Cal_RecommendedAccConnectionCountLimit: u32 = 12268; pub const DAQmx_AI_Max: u32 = 6109; pub const DAQmx_AI_Min: u32 = 6110; pub const DAQmx_AI_CustomScaleName: u32 = 6112; pub const DAQmx_AI_MeasType: u32 = 1685; pub const DAQmx_AI_Voltage_Units: u32 = 4244; pub const DAQmx_AI_Voltage_dBRef: u32 = 10672; pub const DAQmx_AI_Voltage_ACRMS_Units: u32 = 6114; pub const DAQmx_AI_Temp_Units: u32 = 4147; pub const DAQmx_AI_Thrmcpl_Type: u32 = 4176; pub const DAQmx_AI_Thrmcpl_ScaleType: u32 = 10704; pub const DAQmx_AI_Thrmcpl_CJCSrc: u32 = 4149; pub const DAQmx_AI_Thrmcpl_CJCVal: u32 = 4150; pub const DAQmx_AI_Thrmcpl_CJCChan: u32 = 4148; pub const DAQmx_AI_RTD_Type: u32 = 4146; pub const DAQmx_AI_RTD_R0: u32 = 4144; pub const DAQmx_AI_RTD_A: u32 = 4112; pub const DAQmx_AI_RTD_B: u32 = 4113; pub const DAQmx_AI_RTD_C: u32 = 4115; pub const DAQmx_AI_Thrmstr_A: u32 = 6345; pub const DAQmx_AI_Thrmstr_B: u32 = 6347; pub const DAQmx_AI_Thrmstr_C: u32 = 6346; pub const DAQmx_AI_Thrmstr_R1: u32 = 4193; pub const DAQmx_AI_ForceReadFromChan: u32 = 6392; pub const DAQmx_AI_Current_Units: u32 = 1793; pub const DAQmx_AI_Current_ACRMS_Units: u32 = 6115; pub const DAQmx_AI_Strain_Units: u32 = 2433; pub const DAQmx_AI_StrainGage_ForceReadFromChan: u32 = 12282; pub const DAQmx_AI_StrainGage_GageFactor: u32 = 2452; pub const DAQmx_AI_StrainGage_PoissonRatio: u32 = 2456; pub const DAQmx_AI_StrainGage_Cfg: u32 = 2434; pub const DAQmx_AI_RosetteStrainGage_RosetteType: u32 = 12286; pub const DAQmx_AI_RosetteStrainGage_Orientation: u32 = 12284; pub const DAQmx_AI_RosetteStrainGage_StrainChans: u32 = 12283; pub const DAQmx_AI_RosetteStrainGage_RosetteMeasType: u32 = 12285; pub const DAQmx_AI_Resistance_Units: u32 = 2389; pub const DAQmx_AI_Freq_Units: u32 = 2054; pub const DAQmx_AI_Freq_ThreshVoltage: u32 = 2069; pub const DAQmx_AI_Freq_Hyst: u32 = 2068; pub const DAQmx_AI_LVDT_Units: u32 = 2320; pub const DAQmx_AI_LVDT_Sensitivity: u32 = 2361; pub const DAQmx_AI_LVDT_SensitivityUnits: u32 = 8602; pub const DAQmx_AI_RVDT_Units: u32 = 2167; pub const DAQmx_AI_RVDT_Sensitivity: u32 = 2307; pub const DAQmx_AI_RVDT_SensitivityUnits: u32 = 8603; pub const DAQmx_AI_EddyCurrentProxProbe_Units: u32 = 10944; pub const DAQmx_AI_EddyCurrentProxProbe_Sensitivity: u32 = 10942; pub const DAQmx_AI_EddyCurrentProxProbe_SensitivityUnits: u32 = 10943; pub const DAQmx_AI_SoundPressure_MaxSoundPressureLvl: u32 = 8762; pub const DAQmx_AI_SoundPressure_Units: u32 = 5416; pub const DAQmx_AI_SoundPressure_dBRef: u32 = 10673; pub const DAQmx_AI_Microphone_Sensitivity: u32 = 5430; pub const DAQmx_AI_Accel_Units: u32 = 1651; pub const DAQmx_AI_Accel_dBRef: u32 = 10674; pub const DAQmx_AI_Accel_4WireDCVoltage_Sensitivity: u32 = 12565; pub const DAQmx_AI_Accel_4WireDCVoltage_SensitivityUnits: u32 = 12566; pub const DAQmx_AI_Accel_Sensitivity: u32 = 1682; pub const DAQmx_AI_Accel_SensitivityUnits: u32 = 8604; pub const DAQmx_AI_Accel_Charge_Sensitivity: u32 = 12563; pub const DAQmx_AI_Accel_Charge_SensitivityUnits: u32 = 12564; pub const DAQmx_AI_Velocity_Units: u32 = 12276; pub const DAQmx_AI_Velocity_IEPESensor_dBRef: u32 = 12277; pub const DAQmx_AI_Velocity_IEPESensor_Sensitivity: u32 = 12278; pub const DAQmx_AI_Velocity_IEPESensor_SensitivityUnits: u32 = 12279; pub const DAQmx_AI_Force_Units: u32 = 12149; pub const DAQmx_AI_Force_IEPESensor_Sensitivity: u32 = 12161; pub const DAQmx_AI_Force_IEPESensor_SensitivityUnits: u32 = 12162; pub const DAQmx_AI_Pressure_Units: u32 = 12150; pub const DAQmx_AI_Torque_Units: u32 = 12151; pub const DAQmx_AI_Bridge_Units: u32 = 12178; pub const DAQmx_AI_Bridge_ElectricalUnits: u32 = 12167; pub const DAQmx_AI_Bridge_PhysicalUnits: u32 = 12168; pub const DAQmx_AI_Bridge_ScaleType: u32 = 12169; pub const DAQmx_AI_Bridge_TwoPointLin_First_ElectricalVal: u32 = 12170; pub const DAQmx_AI_Bridge_TwoPointLin_First_PhysicalVal: u32 = 12171; pub const DAQmx_AI_Bridge_TwoPointLin_Second_ElectricalVal: u32 = 12172; pub const DAQmx_AI_Bridge_TwoPointLin_Second_PhysicalVal: u32 = 12173; pub const DAQmx_AI_Bridge_Table_ElectricalVals: u32 = 12174; pub const DAQmx_AI_Bridge_Table_PhysicalVals: u32 = 12175; pub const DAQmx_AI_Bridge_Poly_ForwardCoeff: u32 = 12176; pub const DAQmx_AI_Bridge_Poly_ReverseCoeff: u32 = 12177; pub const DAQmx_AI_Charge_Units: u32 = 12562; pub const DAQmx_AI_Is_TEDS: u32 = 10627; pub const DAQmx_AI_TEDS_Units: u32 = 8672; pub const DAQmx_AI_Coupling: u32 = 100; pub const DAQmx_AI_Impedance: u32 = 98; pub const DAQmx_AI_TermCfg: u32 = 4247; pub const DAQmx_AI_InputSrc: u32 = 8600; pub const DAQmx_AI_ResistanceCfg: u32 = 6273; pub const DAQmx_AI_LeadWireResistance: u32 = 6126; pub const DAQmx_AI_Bridge_Cfg: u32 = 135; pub const DAQmx_AI_Bridge_NomResistance: u32 = 6124; pub const DAQmx_AI_Bridge_InitialVoltage: u32 = 6125; pub const DAQmx_AI_Bridge_InitialRatio: u32 = 12166; pub const DAQmx_AI_Bridge_ShuntCal_Enable: u32 = 148; pub const DAQmx_AI_Bridge_ShuntCal_Select: u32 = 8661; pub const DAQmx_AI_Bridge_ShuntCal_ShuntCalASrc: u32 = 12490; pub const DAQmx_AI_Bridge_ShuntCal_GainAdjust: u32 = 6463; pub const DAQmx_AI_Bridge_ShuntCal_ShuntCalAResistance: u32 = 12152; pub const DAQmx_AI_Bridge_ShuntCal_ShuntCalAActualResistance: u32 = 12153; pub const DAQmx_AI_Bridge_ShuntCal_ShuntCalBResistance: u32 = 12154; pub const DAQmx_AI_Bridge_ShuntCal_ShuntCalBActualResistance: u32 = 12155; pub const DAQmx_AI_Bridge_Balance_CoarsePot: u32 = 6129; pub const DAQmx_AI_Bridge_Balance_FinePot: u32 = 6388; pub const DAQmx_AI_CurrentShunt_Loc: u32 = 6130; pub const DAQmx_AI_CurrentShunt_Resistance: u32 = 6131; pub const DAQmx_AI_Excit_Sense: u32 = 12541; pub const DAQmx_AI_Excit_Src: u32 = 6132; pub const DAQmx_AI_Excit_Val: u32 = 6133; pub const DAQmx_AI_Excit_UseForScaling: u32 = 6140; pub const DAQmx_AI_Excit_UseMultiplexed: u32 = 8576; pub const DAQmx_AI_Excit_ActualVal: u32 = 6275; pub const DAQmx_AI_Excit_DCorAC: u32 = 6139; pub const DAQmx_AI_Excit_VoltageOrCurrent: u32 = 6134; pub const DAQmx_AI_Excit_IdleOutputBehavior: u32 = 12472; pub const DAQmx_AI_ACExcit_Freq: u32 = 257; pub const DAQmx_AI_ACExcit_SyncEnable: u32 = 258; pub const DAQmx_AI_ACExcit_WireMode: u32 = 6349; pub const DAQmx_AI_SensorPower_Voltage: u32 = 12649; pub const DAQmx_AI_SensorPower_Cfg: u32 = 12650; pub const DAQmx_AI_SensorPower_Type: u32 = 12651; pub const DAQmx_AI_OpenThrmcplDetectEnable: u32 = 12146; pub const DAQmx_AI_Thrmcpl_LeadOffsetVoltage: u32 = 12216; pub const DAQmx_AI_Atten: u32 = 6145; pub const DAQmx_AI_ProbeAtten: u32 = 10888; pub const DAQmx_AI_Lowpass_Enable: u32 = 6146; pub const DAQmx_AI_Lowpass_CutoffFreq: u32 = 6147; pub const DAQmx_AI_Lowpass_SwitchCap_ClkSrc: u32 = 6276; pub const DAQmx_AI_Lowpass_SwitchCap_ExtClkFreq: u32 = 6277; pub const DAQmx_AI_Lowpass_SwitchCap_ExtClkDiv: u32 = 6278; pub const DAQmx_AI_Lowpass_SwitchCap_OutClkDiv: u32 = 6279; pub const DAQmx_AI_DigFltr_Enable: u32 = 12477; pub const DAQmx_AI_DigFltr_Type: u32 = 12478; pub const DAQmx_AI_DigFltr_Response: u32 = 12479; pub const DAQmx_AI_DigFltr_Order: u32 = 12480; pub const DAQmx_AI_DigFltr_Lowpass_CutoffFreq: u32 = 12481; pub const DAQmx_AI_DigFltr_Highpass_CutoffFreq: u32 = 12482; pub const DAQmx_AI_DigFltr_Bandpass_CenterFreq: u32 = 12483; pub const DAQmx_AI_DigFltr_Bandpass_Width: u32 = 12484; pub const DAQmx_AI_DigFltr_Notch_CenterFreq: u32 = 12485; pub const DAQmx_AI_DigFltr_Notch_Width: u32 = 12486; pub const DAQmx_AI_DigFltr_Coeff: u32 = 12487; pub const DAQmx_AI_Filter_Enable: u32 = 12659; pub const DAQmx_AI_Filter_Freq: u32 = 12660; pub const DAQmx_AI_Filter_Response: u32 = 12661; pub const DAQmx_AI_Filter_Order: u32 = 12662; pub const DAQmx_AI_FilterDelay: u32 = 12269; pub const DAQmx_AI_FilterDelayUnits: u32 = 12401; pub const DAQmx_AI_RemoveFilterDelay: u32 = 12221; pub const DAQmx_AI_FilterDelayAdjustment: u32 = 12404; pub const DAQmx_AI_AveragingWinSize: u32 = 12270; pub const DAQmx_AI_ResolutionUnits: u32 = 5988; pub const DAQmx_AI_Resolution: u32 = 5989; pub const DAQmx_AI_RawSampSize: u32 = 8922; pub const DAQmx_AI_RawSampJustification: u32 = 80; pub const DAQmx_AI_ADCTimingMode: u32 = 10745; pub const DAQmx_AI_ADCCustomTimingMode: u32 = 12139; pub const DAQmx_AI_Dither_Enable: u32 = 104; pub const DAQmx_AI_ChanCal_HasValidCalInfo: u32 = 8855; pub const DAQmx_AI_ChanCal_EnableCal: u32 = 8856; pub const DAQmx_AI_ChanCal_ApplyCalIfExp: u32 = 8857; pub const DAQmx_AI_ChanCal_ScaleType: u32 = 8860; pub const DAQmx_AI_ChanCal_Table_PreScaledVals: u32 = 8861; pub const DAQmx_AI_ChanCal_Table_ScaledVals: u32 = 8862; pub const DAQmx_AI_ChanCal_Poly_ForwardCoeff: u32 = 8863; pub const DAQmx_AI_ChanCal_Poly_ReverseCoeff: u32 = 8864; pub const DAQmx_AI_ChanCal_OperatorName: u32 = 8867; pub const DAQmx_AI_ChanCal_Desc: u32 = 8868; pub const DAQmx_AI_ChanCal_Verif_RefVals: u32 = 8865; pub const DAQmx_AI_ChanCal_Verif_AcqVals: u32 = 8866; pub const DAQmx_AI_Rng_High: u32 = 6165; pub const DAQmx_AI_Rng_Low: u32 = 6166; pub const DAQmx_AI_DCOffset: u32 = 10889; pub const DAQmx_AI_Gain: u32 = 6168; pub const DAQmx_AI_SampAndHold_Enable: u32 = 6170; pub const DAQmx_AI_AutoZeroMode: u32 = 5984; pub const DAQmx_AI_ChopEnable: u32 = 12611; pub const DAQmx_AI_DataXferMaxRate: u32 = 12567; pub const DAQmx_AI_DataXferMech: u32 = 6177; pub const DAQmx_AI_DataXferReqCond: u32 = 6283; pub const DAQmx_AI_DataXferCustomThreshold: u32 = 8972; pub const DAQmx_AI_UsbXferReqSize: u32 = 10894; pub const DAQmx_AI_UsbXferReqCount: u32 = 12288; pub const DAQmx_AI_MemMapEnable: u32 = 6284; pub const DAQmx_AI_RawDataCompressionType: u32 = 8920; pub const DAQmx_AI_LossyLSBRemoval_CompressedSampSize: u32 = 8921; pub const DAQmx_AI_DevScalingCoeff: u32 = 6448; pub const DAQmx_AI_EnhancedAliasRejectionEnable: u32 = 8852; pub const DAQmx_AI_OpenChanDetectEnable: u32 = 12543; pub const DAQmx_AO_Max: u32 = 4486; pub const DAQmx_AO_Min: u32 = 4487; pub const DAQmx_AO_CustomScaleName: u32 = 4488; pub const DAQmx_AO_OutputType: u32 = 4360; pub const DAQmx_AO_Voltage_Units: u32 = 4484; pub const DAQmx_AO_Voltage_CurrentLimit: u32 = 10781; pub const DAQmx_AO_Current_Units: u32 = 4361; pub const DAQmx_AO_FuncGen_Type: u32 = 10776; pub const DAQmx_AO_FuncGen_Freq: u32 = 10777; pub const DAQmx_AO_FuncGen_Amplitude: u32 = 10778; pub const DAQmx_AO_FuncGen_Offset: u32 = 10779; pub const DAQmx_AO_FuncGen_Square_DutyCycle: u32 = 10780; pub const DAQmx_AO_FuncGen_ModulationType: u32 = 10786; pub const DAQmx_AO_FuncGen_FMDeviation: u32 = 10787; pub const DAQmx_AO_OutputImpedance: u32 = 5264; pub const DAQmx_AO_LoadImpedance: u32 = 289; pub const DAQmx_AO_IdleOutputBehavior: u32 = 8768; pub const DAQmx_AO_TermCfg: u32 = 6286; pub const DAQmx_AO_ResolutionUnits: u32 = 6187; pub const DAQmx_AO_Resolution: u32 = 6188; pub const DAQmx_AO_DAC_Rng_High: u32 = 6190; pub const DAQmx_AO_DAC_Rng_Low: u32 = 6189; pub const DAQmx_AO_DAC_Ref_ConnToGnd: u32 = 304; pub const DAQmx_AO_DAC_Ref_AllowConnToGnd: u32 = 6192; pub const DAQmx_AO_DAC_Ref_Src: u32 = 306; pub const DAQmx_AO_DAC_Ref_ExtSrc: u32 = 8786; pub const DAQmx_AO_DAC_Ref_Val: u32 = 6194; pub const DAQmx_AO_DAC_Offset_Src: u32 = 8787; pub const DAQmx_AO_DAC_Offset_ExtSrc: u32 = 8788; pub const DAQmx_AO_DAC_Offset_Val: u32 = 8789; pub const DAQmx_AO_ReglitchEnable: u32 = 307; pub const DAQmx_AO_FilterDelay: u32 = 12405; pub const DAQmx_AO_FilterDelayUnits: u32 = 12406; pub const DAQmx_AO_FilterDelayAdjustment: u32 = 12402; pub const DAQmx_AO_Gain: u32 = 280; pub const DAQmx_AO_UseOnlyOnBrdMem: u32 = 6202; pub const DAQmx_AO_DataXferMech: u32 = 308; pub const DAQmx_AO_DataXferReqCond: u32 = 6204; pub const DAQmx_AO_UsbXferReqSize: u32 = 10895; pub const DAQmx_AO_UsbXferReqCount: u32 = 12289; pub const DAQmx_AO_MemMapEnable: u32 = 6287; pub const DAQmx_AO_DevScalingCoeff: u32 = 6449; pub const DAQmx_AO_EnhancedImageRejectionEnable: u32 = 8769; pub const DAQmx_DI_InvertLines: u32 = 1939; pub const DAQmx_DI_NumLines: u32 = 8568; pub const DAQmx_DI_DigFltr_Enable: u32 = 8662; pub const DAQmx_DI_DigFltr_MinPulseWidth: u32 = 8663; pub const DAQmx_DI_DigFltr_EnableBusMode: u32 = 12030; pub const DAQmx_DI_DigFltr_TimebaseSrc: u32 = 11988; pub const DAQmx_DI_DigFltr_TimebaseRate: u32 = 11989; pub const DAQmx_DI_DigSync_Enable: u32 = 11990; pub const DAQmx_DI_Tristate: u32 = 6288; pub const DAQmx_DI_LogicFamily: u32 = 10605; pub const DAQmx_DI_DataXferMech: u32 = 8803; pub const DAQmx_DI_DataXferReqCond: u32 = 8804; pub const DAQmx_DI_UsbXferReqSize: u32 = 10896; pub const DAQmx_DI_UsbXferReqCount: u32 = 12290; pub const DAQmx_DI_MemMapEnable: u32 = 10602; pub const DAQmx_DI_AcquireOn: u32 = 10598; pub const DAQmx_DO_OutputDriveType: u32 = 4407; pub const DAQmx_DO_InvertLines: u32 = 4403; pub const DAQmx_DO_NumLines: u32 = 8569; pub const DAQmx_DO_Tristate: u32 = 6387; pub const DAQmx_DO_LineStates_StartState: u32 = 10610; pub const DAQmx_DO_LineStates_PausedState: u32 = 10599; pub const DAQmx_DO_LineStates_DoneState: u32 = 10600; pub const DAQmx_DO_LogicFamily: u32 = 10606; pub const DAQmx_DO_Overcurrent_Limit: u32 = 10885; pub const DAQmx_DO_Overcurrent_AutoReenable: u32 = 10886; pub const DAQmx_DO_Overcurrent_ReenablePeriod: u32 = 10887; pub const DAQmx_DO_UseOnlyOnBrdMem: u32 = 8805; pub const DAQmx_DO_DataXferMech: u32 = 8806; pub const DAQmx_DO_DataXferReqCond: u32 = 8807; pub const DAQmx_DO_UsbXferReqSize: u32 = 10897; pub const DAQmx_DO_UsbXferReqCount: u32 = 12291; pub const DAQmx_DO_MemMapEnable: u32 = 10603; pub const DAQmx_DO_GenerateOn: u32 = 10601; pub const DAQmx_CI_Max: u32 = 6300; pub const DAQmx_CI_Min: u32 = 6301; pub const DAQmx_CI_CustomScaleName: u32 = 6302; pub const DAQmx_CI_MeasType: u32 = 6304; pub const DAQmx_CI_Freq_Units: u32 = 6305; pub const DAQmx_CI_Freq_Term: u32 = 6306; pub const DAQmx_CI_Freq_TermCfg: u32 = 12439; pub const DAQmx_CI_Freq_LogicLvlBehavior: u32 = 12440; pub const DAQmx_CI_Freq_DigFltr_Enable: u32 = 8679; pub const DAQmx_CI_Freq_DigFltr_MinPulseWidth: u32 = 8680; pub const DAQmx_CI_Freq_DigFltr_TimebaseSrc: u32 = 8681; pub const DAQmx_CI_Freq_DigFltr_TimebaseRate: u32 = 8682; pub const DAQmx_CI_Freq_DigSync_Enable: u32 = 8683; pub const DAQmx_CI_Freq_StartingEdge: u32 = 1945; pub const DAQmx_CI_Freq_MeasMeth: u32 = 324; pub const DAQmx_CI_Freq_EnableAveraging: u32 = 11984; pub const DAQmx_CI_Freq_MeasTime: u32 = 325; pub const DAQmx_CI_Freq_Div: u32 = 327; pub const DAQmx_CI_Period_Units: u32 = 6307; pub const DAQmx_CI_Period_Term: u32 = 6308; pub const DAQmx_CI_Period_TermCfg: u32 = 12441; pub const DAQmx_CI_Period_LogicLvlBehavior: u32 = 12442; pub const DAQmx_CI_Period_DigFltr_Enable: u32 = 8684; pub const DAQmx_CI_Period_DigFltr_MinPulseWidth: u32 = 8685; pub const DAQmx_CI_Period_DigFltr_TimebaseSrc: u32 = 8686; pub const DAQmx_CI_Period_DigFltr_TimebaseRate: u32 = 8687; pub const DAQmx_CI_Period_DigSync_Enable: u32 = 8688; pub const DAQmx_CI_Period_StartingEdge: u32 = 2130; pub const DAQmx_CI_Period_MeasMeth: u32 = 6444; pub const DAQmx_CI_Period_EnableAveraging: u32 = 11985; pub const DAQmx_CI_Period_MeasTime: u32 = 6445; pub const DAQmx_CI_Period_Div: u32 = 6446; pub const DAQmx_CI_CountEdges_Term: u32 = 6343; pub const DAQmx_CI_CountEdges_TermCfg: u32 = 12443; pub const DAQmx_CI_CountEdges_LogicLvlBehavior: u32 = 12444; pub const DAQmx_CI_CountEdges_DigFltr_Enable: u32 = 8694; pub const DAQmx_CI_CountEdges_DigFltr_MinPulseWidth: u32 = 8695; pub const DAQmx_CI_CountEdges_DigFltr_TimebaseSrc: u32 = 8696; pub const DAQmx_CI_CountEdges_DigFltr_TimebaseRate: u32 = 8697; pub const DAQmx_CI_CountEdges_DigSync_Enable: u32 = 8698; pub const DAQmx_CI_CountEdges_Dir: u32 = 1686; pub const DAQmx_CI_CountEdges_DirTerm: u32 = 8673; pub const DAQmx_CI_CountEdges_CountDir_TermCfg: u32 = 12445; pub const DAQmx_CI_CountEdges_CountDir_LogicLvlBehavior: u32 = 12446; pub const DAQmx_CI_CountEdges_CountDir_DigFltr_Enable: u32 = 8689; pub const DAQmx_CI_CountEdges_CountDir_DigFltr_MinPulseWidth: u32 = 8690; pub const DAQmx_CI_CountEdges_CountDir_DigFltr_TimebaseSrc: u32 = 8691; pub const DAQmx_CI_CountEdges_CountDir_DigFltr_TimebaseRate: u32 = 8692; pub const DAQmx_CI_CountEdges_CountDir_DigSync_Enable: u32 = 8693; pub const DAQmx_CI_CountEdges_InitialCnt: u32 = 1688; pub const DAQmx_CI_CountEdges_ActiveEdge: u32 = 1687; pub const DAQmx_CI_CountEdges_CountReset_Enable: u32 = 12207; pub const DAQmx_CI_CountEdges_CountReset_ResetCount: u32 = 12208; pub const DAQmx_CI_CountEdges_CountReset_Term: u32 = 12209; pub const DAQmx_CI_CountEdges_CountReset_TermCfg: u32 = 12447; pub const DAQmx_CI_CountEdges_CountReset_LogicLvlBehavior: u32 = 12448; pub const DAQmx_CI_CountEdges_CountReset_DigFltr_Enable: u32 = 12211; pub const DAQmx_CI_CountEdges_CountReset_DigFltr_MinPulseWidth: u32 = 12212; pub const DAQmx_CI_CountEdges_CountReset_DigFltr_TimebaseSrc: u32 = 12213; pub const DAQmx_CI_CountEdges_CountReset_DigFltr_TimebaseRate: u32 = 12214; pub const DAQmx_CI_CountEdges_CountReset_DigSync_Enable: u32 = 12215; pub const DAQmx_CI_CountEdges_CountReset_ActiveEdge: u32 = 12210; pub const DAQmx_CI_CountEdges_Gate_Enable: u32 = 12525; pub const DAQmx_CI_CountEdges_Gate_Term: u32 = 12526; pub const DAQmx_CI_CountEdges_Gate_TermCfg: u32 = 12527; pub const DAQmx_CI_CountEdges_Gate_LogicLvlBehavior: u32 = 12528; pub const DAQmx_CI_CountEdges_Gate_DigFltrEnable: u32 = 12529; pub const DAQmx_CI_CountEdges_Gate_DigFltrMinPulseWidth: u32 = 12530; pub const DAQmx_CI_CountEdges_Gate_DigFltrTimebaseSrc: u32 = 12531; pub const DAQmx_CI_CountEdges_Gate_DigFltrTimebaseRate: u32 = 12532; pub const DAQmx_CI_CountEdges_GateWhen: u32 = 12533; pub const DAQmx_CI_DutyCycle_Term: u32 = 12429; pub const DAQmx_CI_DutyCycle_TermCfg: u32 = 12449; pub const DAQmx_CI_DutyCycle_LogicLvlBehavior: u32 = 12450; pub const DAQmx_CI_DutyCycle_DigFltr_Enable: u32 = 12430; pub const DAQmx_CI_DutyCycle_DigFltr_MinPulseWidth: u32 = 12431; pub const DAQmx_CI_DutyCycle_DigFltr_TimebaseSrc: u32 = 12432; pub const DAQmx_CI_DutyCycle_DigFltr_TimebaseRate: u32 = 12433; pub const DAQmx_CI_DutyCycle_StartingEdge: u32 = 12434; pub const DAQmx_CI_AngEncoder_Units: u32 = 6310; pub const DAQmx_CI_AngEncoder_PulsesPerRev: u32 = 2165; pub const DAQmx_CI_AngEncoder_InitialAngle: u32 = 2177; pub const DAQmx_CI_LinEncoder_Units: u32 = 6313; pub const DAQmx_CI_LinEncoder_DistPerPulse: u32 = 2321; pub const DAQmx_CI_LinEncoder_InitialPos: u32 = 2325; pub const DAQmx_CI_Encoder_DecodingType: u32 = 8678; pub const DAQmx_CI_Encoder_AInputTerm: u32 = 8605; pub const DAQmx_CI_Encoder_AInputTermCfg: u32 = 12451; pub const DAQmx_CI_Encoder_AInputLogicLvlBehavior: u32 = 12452; pub const DAQmx_CI_Encoder_AInput_DigFltr_Enable: u32 = 8699; pub const DAQmx_CI_Encoder_AInput_DigFltr_MinPulseWidth: u32 = 8700; pub const DAQmx_CI_Encoder_AInput_DigFltr_TimebaseSrc: u32 = 8701; pub const DAQmx_CI_Encoder_AInput_DigFltr_TimebaseRate: u32 = 8702; pub const DAQmx_CI_Encoder_AInput_DigSync_Enable: u32 = 8703; pub const DAQmx_CI_Encoder_BInputTerm: u32 = 8606; pub const DAQmx_CI_Encoder_BInputTermCfg: u32 = 12453; pub const DAQmx_CI_Encoder_BInputLogicLvlBehavior: u32 = 12454; pub const DAQmx_CI_Encoder_BInput_DigFltr_Enable: u32 = 8704; pub const DAQmx_CI_Encoder_BInput_DigFltr_MinPulseWidth: u32 = 8705; pub const DAQmx_CI_Encoder_BInput_DigFltr_TimebaseSrc: u32 = 8706; pub const DAQmx_CI_Encoder_BInput_DigFltr_TimebaseRate: u32 = 8707; pub const DAQmx_CI_Encoder_BInput_DigSync_Enable: u32 = 8708; pub const DAQmx_CI_Encoder_ZInputTerm: u32 = 8607; pub const DAQmx_CI_Encoder_ZInputTermCfg: u32 = 12455; pub const DAQmx_CI_Encoder_ZInputLogicLvlBehavior: u32 = 12456; pub const DAQmx_CI_Encoder_ZInput_DigFltr_Enable: u32 = 8709; pub const DAQmx_CI_Encoder_ZInput_DigFltr_MinPulseWidth: u32 = 8710; pub const DAQmx_CI_Encoder_ZInput_DigFltr_TimebaseSrc: u32 = 8711; pub const DAQmx_CI_Encoder_ZInput_DigFltr_TimebaseRate: u32 = 8712; pub const DAQmx_CI_Encoder_ZInput_DigSync_Enable: u32 = 8713; pub const DAQmx_CI_Encoder_ZIndexEnable: u32 = 2192; pub const DAQmx_CI_Encoder_ZIndexVal: u32 = 2184; pub const DAQmx_CI_Encoder_ZIndexPhase: u32 = 2185; pub const DAQmx_CI_PulseWidth_Units: u32 = 2083; pub const DAQmx_CI_PulseWidth_Term: u32 = 6314; pub const DAQmx_CI_PulseWidth_TermCfg: u32 = 12457; pub const DAQmx_CI_PulseWidth_LogicLvlBehavior: u32 = 12458; pub const DAQmx_CI_PulseWidth_DigFltr_Enable: u32 = 8714; pub const DAQmx_CI_PulseWidth_DigFltr_MinPulseWidth: u32 = 8715; pub const DAQmx_CI_PulseWidth_DigFltr_TimebaseSrc: u32 = 8716; pub const DAQmx_CI_PulseWidth_DigFltr_TimebaseRate: u32 = 8717; pub const DAQmx_CI_PulseWidth_DigSync_Enable: u32 = 8718; pub const DAQmx_CI_PulseWidth_StartingEdge: u32 = 2085; pub const DAQmx_CI_Timestamp_Units: u32 = 8883; pub const DAQmx_CI_Timestamp_InitialSeconds: u32 = 8884; pub const DAQmx_CI_GPS_SyncMethod: u32 = 4242; pub const DAQmx_CI_GPS_SyncSrc: u32 = 4243; pub const DAQmx_CI_Velocity_AngEncoder_Units: u32 = 12504; pub const DAQmx_CI_Velocity_AngEncoder_PulsesPerRev: u32 = 12505; pub const DAQmx_CI_Velocity_LinEncoder_Units: u32 = 12506; pub const DAQmx_CI_Velocity_LinEncoder_DistPerPulse: u32 = 12507; pub const DAQmx_CI_Velocity_Encoder_DecodingType: u32 = 12508; pub const DAQmx_CI_Velocity_Encoder_AInputTerm: u32 = 12509; pub const DAQmx_CI_Velocity_Encoder_AInputTermCfg: u32 = 12510; pub const DAQmx_CI_Velocity_Encoder_AInputLogicLvlBehavior: u32 = 12511; pub const DAQmx_CI_Velocity_Encoder_AInputDigFltr_Enable: u32 = 12512; pub const DAQmx_CI_Velocity_Encoder_AInputDigFltr_MinPulseWidth: u32 = 12513; pub const DAQmx_CI_Velocity_Encoder_AInputDigFltr_TimebaseSrc: u32 = 12514; pub const DAQmx_CI_Velocity_Encoder_AInputDigFltr_TimebaseRate: u32 = 12515; pub const DAQmx_CI_Velocity_Encoder_BInputTerm: u32 = 12516; pub const DAQmx_CI_Velocity_Encoder_BInputTermCfg: u32 = 12517; pub const DAQmx_CI_Velocity_Encoder_BInputLogicLvlBehavior: u32 = 12518; pub const DAQmx_CI_Velocity_Encoder_BInputDigFltr_Enable: u32 = 12519; pub const DAQmx_CI_Velocity_Encoder_BInputDigFltr_MinPulseWidth: u32 = 12520; pub const DAQmx_CI_Velocity_Encoder_BInputDigFltr_TimebaseSrc: u32 = 12521; pub const DAQmx_CI_Velocity_Encoder_BInputDigFltr_TimebaseRate: u32 = 12522; pub const DAQmx_CI_Velocity_MeasTime: u32 = 12523; pub const DAQmx_CI_Velocity_Div: u32 = 12524; pub const DAQmx_CI_TwoEdgeSep_Units: u32 = 6316; pub const DAQmx_CI_TwoEdgeSep_FirstTerm: u32 = 6317; pub const DAQmx_CI_TwoEdgeSep_FirstTermCfg: u32 = 12459; pub const DAQmx_CI_TwoEdgeSep_FirstLogicLvlBehavior: u32 = 12460; pub const DAQmx_CI_TwoEdgeSep_First_DigFltr_Enable: u32 = 8719; pub const DAQmx_CI_TwoEdgeSep_First_DigFltr_MinPulseWidth: u32 = 8720; pub const DAQmx_CI_TwoEdgeSep_First_DigFltr_TimebaseSrc: u32 = 8721; pub const DAQmx_CI_TwoEdgeSep_First_DigFltr_TimebaseRate: u32 = 8722; pub const DAQmx_CI_TwoEdgeSep_First_DigSync_Enable: u32 = 8723; pub const DAQmx_CI_TwoEdgeSep_FirstEdge: u32 = 2099; pub const DAQmx_CI_TwoEdgeSep_SecondTerm: u32 = 6318; pub const DAQmx_CI_TwoEdgeSep_SecondTermCfg: u32 = 12461; pub const DAQmx_CI_TwoEdgeSep_SecondLogicLvlBehavior: u32 = 12462; pub const DAQmx_CI_TwoEdgeSep_Second_DigFltr_Enable: u32 = 8724; pub const DAQmx_CI_TwoEdgeSep_Second_DigFltr_MinPulseWidth: u32 = 8725; pub const DAQmx_CI_TwoEdgeSep_Second_DigFltr_TimebaseSrc: u32 = 8726; pub const DAQmx_CI_TwoEdgeSep_Second_DigFltr_TimebaseRate: u32 = 8727; pub const DAQmx_CI_TwoEdgeSep_Second_DigSync_Enable: u32 = 8728; pub const DAQmx_CI_TwoEdgeSep_SecondEdge: u32 = 2100; pub const DAQmx_CI_SemiPeriod_Units: u32 = 6319; pub const DAQmx_CI_SemiPeriod_Term: u32 = 6320; pub const DAQmx_CI_SemiPeriod_TermCfg: u32 = 12463; pub const DAQmx_CI_SemiPeriod_LogicLvlBehavior: u32 = 12464; pub const DAQmx_CI_SemiPeriod_DigFltr_Enable: u32 = 8729; pub const DAQmx_CI_SemiPeriod_DigFltr_MinPulseWidth: u32 = 8730; pub const DAQmx_CI_SemiPeriod_DigFltr_TimebaseSrc: u32 = 8731; pub const DAQmx_CI_SemiPeriod_DigFltr_TimebaseRate: u32 = 8732; pub const DAQmx_CI_SemiPeriod_DigSync_Enable: u32 = 8733; pub const DAQmx_CI_SemiPeriod_StartingEdge: u32 = 8958; pub const DAQmx_CI_Pulse_Freq_Units: u32 = 12043; pub const DAQmx_CI_Pulse_Freq_Term: u32 = 12036; pub const DAQmx_CI_Pulse_Freq_TermCfg: u32 = 12465; pub const DAQmx_CI_Pulse_Freq_LogicLvlBehavior: u32 = 12466; pub const DAQmx_CI_Pulse_Freq_DigFltr_Enable: u32 = 12038; pub const DAQmx_CI_Pulse_Freq_DigFltr_MinPulseWidth: u32 = 12039; pub const DAQmx_CI_Pulse_Freq_DigFltr_TimebaseSrc: u32 = 12040; pub const DAQmx_CI_Pulse_Freq_DigFltr_TimebaseRate: u32 = 12041; pub const DAQmx_CI_Pulse_Freq_DigSync_Enable: u32 = 12042; pub const DAQmx_CI_Pulse_Freq_Start_Edge: u32 = 12037; pub const DAQmx_CI_Pulse_Time_Units: u32 = 12051; pub const DAQmx_CI_Pulse_Time_Term: u32 = 12044; pub const DAQmx_CI_Pulse_Time_TermCfg: u32 = 12467; pub const DAQmx_CI_Pulse_Time_LogicLvlBehavior: u32 = 12468; pub const DAQmx_CI_Pulse_Time_DigFltr_Enable: u32 = 12046; pub const DAQmx_CI_Pulse_Time_DigFltr_MinPulseWidth: u32 = 12047; pub const DAQmx_CI_Pulse_Time_DigFltr_TimebaseSrc: u32 = 12048; pub const DAQmx_CI_Pulse_Time_DigFltr_TimebaseRate: u32 = 12049; pub const DAQmx_CI_Pulse_Time_DigSync_Enable: u32 = 12050; pub const DAQmx_CI_Pulse_Time_StartEdge: u32 = 12045; pub const DAQmx_CI_Pulse_Ticks_Term: u32 = 12052; pub const DAQmx_CI_Pulse_Ticks_TermCfg: u32 = 12469; pub const DAQmx_CI_Pulse_Ticks_LogicLvlBehavior: u32 = 12470; pub const DAQmx_CI_Pulse_Ticks_DigFltr_Enable: u32 = 12054; pub const DAQmx_CI_Pulse_Ticks_DigFltr_MinPulseWidth: u32 = 12055; pub const DAQmx_CI_Pulse_Ticks_DigFltr_TimebaseSrc: u32 = 12056; pub const DAQmx_CI_Pulse_Ticks_DigFltr_TimebaseRate: u32 = 12057; pub const DAQmx_CI_Pulse_Ticks_DigSync_Enable: u32 = 12058; pub const DAQmx_CI_Pulse_Ticks_StartEdge: u32 = 12053; pub const DAQmx_CI_CtrTimebaseSrc: u32 = 323; pub const DAQmx_CI_CtrTimebaseRate: u32 = 6322; pub const DAQmx_CI_CtrTimebaseActiveEdge: u32 = 322; pub const DAQmx_CI_CtrTimebase_DigFltr_Enable: u32 = 8817; pub const DAQmx_CI_CtrTimebase_DigFltr_MinPulseWidth: u32 = 8818; pub const DAQmx_CI_CtrTimebase_DigFltr_TimebaseSrc: u32 = 8819; pub const DAQmx_CI_CtrTimebase_DigFltr_TimebaseRate: u32 = 8820; pub const DAQmx_CI_CtrTimebase_DigSync_Enable: u32 = 8821; pub const DAQmx_CI_ThreshVoltage: u32 = 12471; pub const DAQmx_CI_Count: u32 = 328; pub const DAQmx_CI_OutputState: u32 = 329; pub const DAQmx_CI_TCReached: u32 = 336; pub const DAQmx_CI_CtrTimebaseMasterTimebaseDiv: u32 = 6323; pub const DAQmx_CI_SampClkOverrunBehavior: u32 = 12435; pub const DAQmx_CI_SampClkOverrunSentinelVal: u32 = 12436; pub const DAQmx_CI_DataXferMech: u32 = 512; pub const DAQmx_CI_DataXferReqCond: u32 = 12027; pub const DAQmx_CI_UsbXferReqSize: u32 = 10898; pub const DAQmx_CI_UsbXferReqCount: u32 = 12292; pub const DAQmx_CI_MemMapEnable: u32 = 11986; pub const DAQmx_CI_NumPossiblyInvalidSamps: u32 = 6460; pub const DAQmx_CI_DupCountPrevent: u32 = 8620; pub const DAQmx_CI_Prescaler: u32 = 8761; pub const DAQmx_CI_MaxMeasPeriod: u32 = 12437; pub const DAQmx_CO_OutputType: u32 = 6325; pub const DAQmx_CO_Pulse_IdleState: u32 = 4464; pub const DAQmx_CO_Pulse_Term: u32 = 6369; pub const DAQmx_CO_Pulse_Time_Units: u32 = 6358; pub const DAQmx_CO_Pulse_HighTime: u32 = 6330; pub const DAQmx_CO_Pulse_LowTime: u32 = 6331; pub const DAQmx_CO_Pulse_Time_InitialDelay: u32 = 6332; pub const DAQmx_CO_Pulse_DutyCyc: u32 = 4470; pub const DAQmx_CO_Pulse_Freq_Units: u32 = 6357; pub const DAQmx_CO_Pulse_Freq: u32 = 4472; pub const DAQmx_CO_Pulse_Freq_InitialDelay: u32 = 665; pub const DAQmx_CO_Pulse_HighTicks: u32 = 4457; pub const DAQmx_CO_Pulse_LowTicks: u32 = 4465; pub const DAQmx_CO_Pulse_Ticks_InitialDelay: u32 = 664; pub const DAQmx_CO_CtrTimebaseSrc: u32 = 825; pub const DAQmx_CO_CtrTimebaseRate: u32 = 6338; pub const DAQmx_CO_CtrTimebaseActiveEdge: u32 = 833; pub const DAQmx_CO_CtrTimebase_DigFltr_Enable: u32 = 8822; pub const DAQmx_CO_CtrTimebase_DigFltr_MinPulseWidth: u32 = 8823; pub const DAQmx_CO_CtrTimebase_DigFltr_TimebaseSrc: u32 = 8824; pub const DAQmx_CO_CtrTimebase_DigFltr_TimebaseRate: u32 = 8825; pub const DAQmx_CO_CtrTimebase_DigSync_Enable: u32 = 8826; pub const DAQmx_CO_Count: u32 = 659; pub const DAQmx_CO_OutputState: u32 = 660; pub const DAQmx_CO_AutoIncrCnt: u32 = 661; pub const DAQmx_CO_CtrTimebaseMasterTimebaseDiv: u32 = 6339; pub const DAQmx_CO_PulseDone: u32 = 6414; pub const DAQmx_CO_EnableInitialDelayOnRetrigger: u32 = 11977; pub const DAQmx_CO_ConstrainedGenMode: u32 = 10738; pub const DAQmx_CO_UseOnlyOnBrdMem: u32 = 11979; pub const DAQmx_CO_DataXferMech: u32 = 11980; pub const DAQmx_CO_DataXferReqCond: u32 = 11981; pub const DAQmx_CO_UsbXferReqSize: u32 = 10899; pub const DAQmx_CO_UsbXferReqCount: u32 = 12293; pub const DAQmx_CO_MemMapEnable: u32 = 11987; pub const DAQmx_CO_Prescaler: u32 = 8813; pub const DAQmx_CO_RdyForNewVal: u32 = 8959; pub const DAQmx_ChanType: u32 = 6271; pub const DAQmx_PhysicalChanName: u32 = 6389; pub const DAQmx_ChanDescr: u32 = 6438; pub const DAQmx_ChanIsGlobal: u32 = 8964; pub const DAQmx_Chan_SyncUnlockBehavior: u32 = 12604; pub const DAQmx_Dev_IsSimulated: u32 = 8906; pub const DAQmx_Dev_ProductCategory: u32 = 10665; pub const DAQmx_Dev_ProductType: u32 = 1585; pub const DAQmx_Dev_ProductNum: u32 = 8989; pub const DAQmx_Dev_SerialNum: u32 = 1586; pub const DAQmx_Dev_Accessory_ProductTypes: u32 = 12141; pub const DAQmx_Dev_Accessory_ProductNums: u32 = 12142; pub const DAQmx_Dev_Accessory_SerialNums: u32 = 12143; pub const DAQmx_Carrier_SerialNum: u32 = 10890; pub const DAQmx_FieldDAQ_DevName: u32 = 12657; pub const DAQmx_FieldDAQ_BankDevNames: u32 = 12664; pub const DAQmx_Dev_Chassis_ModuleDevNames: u32 = 10678; pub const DAQmx_Dev_AnlgTrigSupported: u32 = 10628; pub const DAQmx_Dev_DigTrigSupported: u32 = 10629; pub const DAQmx_Dev_TimeTrigSupported: u32 = 12319; pub const DAQmx_Dev_AI_PhysicalChans: u32 = 8990; pub const DAQmx_Dev_AI_SupportedMeasTypes: u32 = 12242; pub const DAQmx_Dev_AI_MaxSingleChanRate: u32 = 10636; pub const DAQmx_Dev_AI_MaxMultiChanRate: u32 = 10637; pub const DAQmx_Dev_AI_MinRate: u32 = 10638; pub const DAQmx_Dev_AI_SimultaneousSamplingSupported: u32 = 10639; pub const DAQmx_Dev_AI_NumSampTimingEngines: u32 = 12643; pub const DAQmx_Dev_AI_SampModes: u32 = 12252; pub const DAQmx_Dev_AI_NumSyncPulseSrcs: u32 = 12644; pub const DAQmx_Dev_AI_TrigUsage: u32 = 10630; pub const DAQmx_Dev_AI_VoltageRngs: u32 = 10640; pub const DAQmx_Dev_AI_VoltageIntExcitDiscreteVals: u32 = 10697; pub const DAQmx_Dev_AI_VoltageIntExcitRangeVals: u32 = 10698; pub const DAQmx_Dev_AI_ChargeRngs: u32 = 12561; pub const DAQmx_Dev_AI_CurrentRngs: u32 = 10641; pub const DAQmx_Dev_AI_CurrentIntExcitDiscreteVals: u32 = 10699; pub const DAQmx_Dev_AI_BridgeRngs: u32 = 12240; pub const DAQmx_Dev_AI_ResistanceRngs: u32 = 10773; pub const DAQmx_Dev_AI_FreqRngs: u32 = 10642; pub const DAQmx_Dev_AI_Gains: u32 = 10643; pub const DAQmx_Dev_AI_Couplings: u32 = 10644; pub const DAQmx_Dev_AI_LowpassCutoffFreqDiscreteVals: u32 = 10645; pub const DAQmx_Dev_AI_LowpassCutoffFreqRangeVals: u32 = 10703; pub const DAQmx_AI_DigFltr_Types: u32 = 12551; pub const DAQmx_Dev_AI_DigFltr_LowpassCutoffFreqDiscreteVals: u32 = 12488; pub const DAQmx_Dev_AI_DigFltr_LowpassCutoffFreqRangeVals: u32 = 12489; pub const DAQmx_Dev_AO_PhysicalChans: u32 = 8991; pub const DAQmx_Dev_AO_SupportedOutputTypes: u32 = 12243; pub const DAQmx_Dev_AO_MaxRate: u32 = 10647; pub const DAQmx_Dev_AO_MinRate: u32 = 10648; pub const DAQmx_Dev_AO_SampClkSupported: u32 = 10646; pub const DAQmx_Dev_AO_NumSampTimingEngines: u32 = 12645; pub const DAQmx_Dev_AO_SampModes: u32 = 12253; pub const DAQmx_Dev_AO_NumSyncPulseSrcs: u32 = 12646; pub const DAQmx_Dev_AO_TrigUsage: u32 = 10631; pub const DAQmx_Dev_AO_VoltageRngs: u32 = 10651; pub const DAQmx_Dev_AO_CurrentRngs: u32 = 10652; pub const DAQmx_Dev_AO_Gains: u32 = 10653; pub const DAQmx_Dev_DI_Lines: u32 = 8992; pub const DAQmx_Dev_DI_Ports: u32 = 8993; pub const DAQmx_Dev_DI_MaxRate: u32 = 10649; pub const DAQmx_Dev_DI_NumSampTimingEngines: u32 = 12647; pub const DAQmx_Dev_DI_TrigUsage: u32 = 10632; pub const DAQmx_Dev_DO_Lines: u32 = 8994; pub const DAQmx_Dev_DO_Ports: u32 = 8995; pub const DAQmx_Dev_DO_MaxRate: u32 = 10650; pub const DAQmx_Dev_DO_NumSampTimingEngines: u32 = 12648; pub const DAQmx_Dev_DO_TrigUsage: u32 = 10633; pub const DAQmx_Dev_CI_PhysicalChans: u32 = 8996; pub const DAQmx_Dev_CI_SupportedMeasTypes: u32 = 12244; pub const DAQmx_Dev_CI_TrigUsage: u32 = 10634; pub const DAQmx_Dev_CI_SampClkSupported: u32 = 10654; pub const DAQmx_Dev_CI_SampModes: u32 = 12254; pub const DAQmx_Dev_CI_MaxSize: u32 = 10655; pub const DAQmx_Dev_CI_MaxTimebase: u32 = 10656; pub const DAQmx_Dev_CO_PhysicalChans: u32 = 8997; pub const DAQmx_Dev_CO_SupportedOutputTypes: u32 = 12245; pub const DAQmx_Dev_CO_SampClkSupported: u32 = 12123; pub const DAQmx_Dev_CO_SampModes: u32 = 12255; pub const DAQmx_Dev_CO_TrigUsage: u32 = 10635; pub const DAQmx_Dev_CO_MaxSize: u32 = 10657; pub const DAQmx_Dev_CO_MaxTimebase: u32 = 10658; pub const DAQmx_Dev_TEDS_HWTEDSSupported: u32 = 12246; pub const DAQmx_Dev_NumDMAChans: u32 = 9020; pub const DAQmx_Dev_BusType: u32 = 8998; pub const DAQmx_Dev_PCI_BusNum: u32 = 8999; pub const DAQmx_Dev_PCI_DevNum: u32 = 9000; pub const DAQmx_Dev_PXI_ChassisNum: u32 = 9001; pub const DAQmx_Dev_PXI_SlotNum: u32 = 9002; pub const DAQmx_Dev_CompactDAQ_ChassisDevName: u32 = 10679; pub const DAQmx_Dev_CompactDAQ_SlotNum: u32 = 10680; pub const DAQmx_Dev_CompactRIO_ChassisDevName: u32 = 12641; pub const DAQmx_Dev_CompactRIO_SlotNum: u32 = 12642; pub const DAQmx_Dev_TCPIP_Hostname: u32 = 10891; pub const DAQmx_Dev_TCPIP_EthernetIP: u32 = 10892; pub const DAQmx_Dev_TCPIP_WirelessIP: u32 = 10893; pub const DAQmx_Dev_Terminals: u32 = 10816; pub const DAQmx_Dev_NumTimeTrigs: u32 = 12609; pub const DAQmx_Dev_NumTimestampEngines: u32 = 12610; pub const DAQmx_Exported_AIConvClk_OutputTerm: u32 = 5767; pub const DAQmx_Exported_AIConvClk_Pulse_Polarity: u32 = 5768; pub const DAQmx_Exported_10MHzRefClk_OutputTerm: u32 = 8814; pub const DAQmx_Exported_20MHzTimebase_OutputTerm: u32 = 5719; pub const DAQmx_Exported_SampClk_OutputBehavior: u32 = 6251; pub const DAQmx_Exported_SampClk_OutputTerm: u32 = 5731; pub const DAQmx_Exported_SampClk_DelayOffset: u32 = 8644; pub const DAQmx_Exported_SampClk_Pulse_Polarity: u32 = 5732; pub const DAQmx_Exported_SampClkTimebase_OutputTerm: u32 = 6393; pub const DAQmx_Exported_DividedSampClkTimebase_OutputTerm: u32 = 8609; pub const DAQmx_Exported_AdvTrig_OutputTerm: u32 = 5701; pub const DAQmx_Exported_AdvTrig_Pulse_Polarity: u32 = 5702; pub const DAQmx_Exported_AdvTrig_Pulse_WidthUnits: u32 = 5703; pub const DAQmx_Exported_AdvTrig_Pulse_Width: u32 = 5704; pub const DAQmx_Exported_PauseTrig_OutputTerm: u32 = 5653; pub const DAQmx_Exported_PauseTrig_Lvl_ActiveLvl: u32 = 5654; pub const DAQmx_Exported_RefTrig_OutputTerm: u32 = 1424; pub const DAQmx_Exported_RefTrig_Pulse_Polarity: u32 = 1425; pub const DAQmx_Exported_StartTrig_OutputTerm: u32 = 1412; pub const DAQmx_Exported_StartTrig_Pulse_Polarity: u32 = 1413; pub const DAQmx_Exported_AdvCmpltEvent_OutputTerm: u32 = 5713; pub const DAQmx_Exported_AdvCmpltEvent_Delay: u32 = 5975; pub const DAQmx_Exported_AdvCmpltEvent_Pulse_Polarity: u32 = 5714; pub const DAQmx_Exported_AdvCmpltEvent_Pulse_Width: u32 = 5716; pub const DAQmx_Exported_AIHoldCmpltEvent_OutputTerm: u32 = 6381; pub const DAQmx_Exported_AIHoldCmpltEvent_PulsePolarity: u32 = 6382; pub const DAQmx_Exported_ChangeDetectEvent_OutputTerm: u32 = 8599; pub const DAQmx_Exported_ChangeDetectEvent_Pulse_Polarity: u32 = 8963; pub const DAQmx_Exported_CtrOutEvent_OutputTerm: u32 = 5911; pub const DAQmx_Exported_CtrOutEvent_OutputBehavior: u32 = 5967; pub const DAQmx_Exported_CtrOutEvent_Pulse_Polarity: u32 = 5912; pub const DAQmx_Exported_CtrOutEvent_Toggle_IdleState: u32 = 6250; pub const DAQmx_Exported_HshkEvent_OutputTerm: u32 = 8890; pub const DAQmx_Exported_HshkEvent_OutputBehavior: u32 = 8891; pub const DAQmx_Exported_HshkEvent_Delay: u32 = 8892; pub const DAQmx_Exported_HshkEvent_Interlocked_AssertedLvl: u32 = 8893; pub const DAQmx_Exported_HshkEvent_Interlocked_AssertOnStart: u32 = 8894; pub const DAQmx_Exported_HshkEvent_Interlocked_DeassertDelay: u32 = 8895; pub const DAQmx_Exported_HshkEvent_Pulse_Polarity: u32 = 8896; pub const DAQmx_Exported_HshkEvent_Pulse_Width: u32 = 8897; pub const DAQmx_Exported_RdyForXferEvent_OutputTerm: u32 = 8885; pub const DAQmx_Exported_RdyForXferEvent_Lvl_ActiveLvl: u32 = 8886; pub const DAQmx_Exported_RdyForXferEvent_DeassertCond: u32 = 10595; pub const DAQmx_Exported_RdyForXferEvent_DeassertCondCustomThreshold: u32 = 10596; pub const DAQmx_Exported_DataActiveEvent_OutputTerm: u32 = 5683; pub const DAQmx_Exported_DataActiveEvent_Lvl_ActiveLvl: u32 = 5684; pub const DAQmx_Exported_RdyForStartEvent_OutputTerm: u32 = 5641; pub const DAQmx_Exported_RdyForStartEvent_Lvl_ActiveLvl: u32 = 5969; pub const DAQmx_Exported_SyncPulseEvent_OutputTerm: u32 = 8764; pub const DAQmx_Exported_WatchdogExpiredEvent_OutputTerm: u32 = 8618; pub const DAQmx_PersistedChan_Author: u32 = 8912; pub const DAQmx_PersistedChan_AllowInteractiveEditing: u32 = 8913; pub const DAQmx_PersistedChan_AllowInteractiveDeletion: u32 = 8914; pub const DAQmx_PersistedScale_Author: u32 = 8916; pub const DAQmx_PersistedScale_AllowInteractiveEditing: u32 = 8917; pub const DAQmx_PersistedScale_AllowInteractiveDeletion: u32 = 8918; pub const DAQmx_PersistedTask_Author: u32 = 8908; pub const DAQmx_PersistedTask_AllowInteractiveEditing: u32 = 8909; pub const DAQmx_PersistedTask_AllowInteractiveDeletion: u32 = 8910; pub const DAQmx_PhysicalChan_AI_SupportedMeasTypes: u32 = 12247; pub const DAQmx_PhysicalChan_AI_TermCfgs: u32 = 9026; pub const DAQmx_PhysicalChan_AI_InputSrcs: u32 = 12248; pub const DAQmx_PhysicalChan_AI_SensorPower_Types: u32 = 12665; pub const DAQmx_PhysicalChan_AI_SensorPower_VoltageRangeVals: u32 = 12666; pub const DAQmx_PhysicalChan_AI_PowerControl_Voltage: u32 = 12652; pub const DAQmx_PhysicalChan_AI_PowerControl_Enable: u32 = 12653; pub const DAQmx_PhysicalChan_AI_PowerControl_Type: u32 = 12654; pub const DAQmx_PhysicalChan_AI_SensorPower_OpenChan: u32 = 12668; pub const DAQmx_PhysicalChan_AI_SensorPower_Overcurrent: u32 = 12669; pub const DAQmx_PhysicalChan_AO_SupportedOutputTypes: u32 = 12249; pub const DAQmx_PhysicalChan_AO_SupportedPowerUpOutputTypes: u32 = 12366; pub const DAQmx_PhysicalChan_AO_TermCfgs: u32 = 10659; pub const DAQmx_PhysicalChan_AO_ManualControlEnable: u32 = 10782; pub const DAQmx_PhysicalChan_AO_ManualControl_ShortDetected: u32 = 11971; pub const DAQmx_PhysicalChan_AO_ManualControlAmplitude: u32 = 10783; pub const DAQmx_PhysicalChan_AO_ManualControlFreq: u32 = 10784; pub const DAQmx_AO_PowerAmp_ChannelEnable: u32 = 12386; pub const DAQmx_AO_PowerAmp_ScalingCoeff: u32 = 12387; pub const DAQmx_AO_PowerAmp_Overcurrent: u32 = 12388; pub const DAQmx_AO_PowerAmp_Gain: u32 = 12389; pub const DAQmx_AO_PowerAmp_Offset: u32 = 12390; pub const DAQmx_PhysicalChan_DI_PortWidth: u32 = 10660; pub const DAQmx_PhysicalChan_DI_SampClkSupported: u32 = 10661; pub const DAQmx_PhysicalChan_DI_SampModes: u32 = 12256; pub const DAQmx_PhysicalChan_DI_ChangeDetectSupported: u32 = 10662; pub const DAQmx_PhysicalChan_DO_PortWidth: u32 = 10663; pub const DAQmx_PhysicalChan_DO_SampClkSupported: u32 = 10664; pub const DAQmx_PhysicalChan_DO_SampModes: u32 = 12257; pub const DAQmx_PhysicalChan_CI_SupportedMeasTypes: u32 = 12250; pub const DAQmx_PhysicalChan_CO_SupportedOutputTypes: u32 = 12251; pub const DAQmx_PhysicalChan_TEDS_MfgID: u32 = 8666; pub const DAQmx_PhysicalChan_TEDS_ModelNum: u32 = 8667; pub const DAQmx_PhysicalChan_TEDS_SerialNum: u32 = 8668; pub const DAQmx_PhysicalChan_TEDS_VersionNum: u32 = 8669; pub const DAQmx_PhysicalChan_TEDS_VersionLetter: u32 = 8670; pub const DAQmx_PhysicalChan_TEDS_BitStream: u32 = 8671; pub const DAQmx_PhysicalChan_TEDS_TemplateIDs: u32 = 8847; pub const DAQmx_Read_RelativeTo: u32 = 6410; pub const DAQmx_Read_Offset: u32 = 6411; pub const DAQmx_Read_ChannelsToRead: u32 = 6179; pub const DAQmx_Read_ReadAllAvailSamp: u32 = 4629; pub const DAQmx_Read_AutoStart: u32 = 6182; pub const DAQmx_Read_OverWrite: u32 = 4625; pub const DAQmx_Logging_FilePath: u32 = 11972; pub const DAQmx_Logging_Mode: u32 = 11973; pub const DAQmx_Logging_TDMS_GroupName: u32 = 11974; pub const DAQmx_Logging_TDMS_Operation: u32 = 11975; pub const DAQmx_Logging_Pause: u32 = 12259; pub const DAQmx_Logging_SampsPerFile: u32 = 12260; pub const DAQmx_Logging_FileWriteSize: u32 = 12227; pub const DAQmx_Logging_FilePreallocationSize: u32 = 12230; pub const DAQmx_Read_CurrReadPos: u32 = 4641; pub const DAQmx_Read_AvailSampPerChan: u32 = 4643; pub const DAQmx_Read_TotalSampPerChanAcquired: u32 = 6442; pub const DAQmx_Read_CommonModeRangeErrorChansExist: u32 = 10904; pub const DAQmx_Read_CommonModeRangeErrorChans: u32 = 10905; pub const DAQmx_Read_ExcitFaultChansExist: u32 = 12424; pub const DAQmx_Read_ExcitFaultChans: u32 = 12425; pub const DAQmx_Read_OvercurrentChansExist: u32 = 10726; pub const DAQmx_Read_OvercurrentChans: u32 = 10727; pub const DAQmx_Read_OvertemperatureChansExist: u32 = 12417; pub const DAQmx_Read_OvertemperatureChans: u32 = 12418; pub const DAQmx_Read_OpenChansExist: u32 = 12544; pub const DAQmx_Read_OpenChans: u32 = 12545; pub const DAQmx_Read_OpenChansDetails: u32 = 12546; pub const DAQmx_Read_OpenCurrentLoopChansExist: u32 = 10761; pub const DAQmx_Read_OpenCurrentLoopChans: u32 = 10762; pub const DAQmx_Read_OpenThrmcplChansExist: u32 = 10902; pub const DAQmx_Read_OpenThrmcplChans: u32 = 10903; pub const DAQmx_Read_OverloadedChansExist: u32 = 8564; pub const DAQmx_Read_OverloadedChans: u32 = 8565; pub const DAQmx_Read_PLL_UnlockedChansExist: u32 = 12568; pub const DAQmx_Read_PLL_UnlockedChans: u32 = 12569; pub const DAQmx_Read_Sync_UnlockedChansExist: u32 = 12605; pub const DAQmx_Read_Sync_UnlockedChans: u32 = 12606; pub const DAQmx_Read_AccessoryInsertionOrRemovalDetected: u32 = 12144; pub const DAQmx_Read_DevsWithInsertedOrRemovedAccessories: u32 = 12145; pub const DAQmx_Read_ChangeDetect_HasOverflowed: u32 = 8596; pub const DAQmx_Read_RawDataWidth: u32 = 8570; pub const DAQmx_Read_NumChans: u32 = 8571; pub const DAQmx_Read_DigitalLines_BytesPerChan: u32 = 8572; pub const DAQmx_Read_WaitMode: u32 = 8754; pub const DAQmx_Read_SleepTime: u32 = 8880; pub const DAQmx_RealTime_ConvLateErrorsToWarnings: u32 = 8942; pub const DAQmx_RealTime_NumOfWarmupIters: u32 = 8941; pub const DAQmx_RealTime_WaitForNextSampClkWaitMode: u32 = 8943; pub const DAQmx_RealTime_ReportMissedSamp: u32 = 8985; pub const DAQmx_RealTime_WriteRecoveryMode: u32 = 8986; pub const DAQmx_Scale_Descr: u32 = 4646; pub const DAQmx_Scale_ScaledUnits: u32 = 6427; pub const DAQmx_Scale_PreScaledUnits: u32 = 6391; pub const DAQmx_Scale_Type: u32 = 6441; pub const DAQmx_Scale_Lin_Slope: u32 = 4647; pub const DAQmx_Scale_Lin_YIntercept: u32 = 4648; pub const DAQmx_Scale_Map_ScaledMax: u32 = 4649; pub const DAQmx_Scale_Map_PreScaledMax: u32 = 4657; pub const DAQmx_Scale_Map_ScaledMin: u32 = 4656; pub const DAQmx_Scale_Map_PreScaledMin: u32 = 4658; pub const DAQmx_Scale_Poly_ForwardCoeff: u32 = 4660; pub const DAQmx_Scale_Poly_ReverseCoeff: u32 = 4661; pub const DAQmx_Scale_Table_ScaledVals: u32 = 4662; pub const DAQmx_Scale_Table_PreScaledVals: u32 = 4663; pub const DAQmx_SwitchChan_Usage: u32 = 6372; pub const DAQmx_SwitchChan_AnlgBusSharingEnable: u32 = 12190; pub const DAQmx_SwitchChan_MaxACCarryCurrent: u32 = 1608; pub const DAQmx_SwitchChan_MaxACSwitchCurrent: u32 = 1606; pub const DAQmx_SwitchChan_MaxACCarryPwr: u32 = 1602; pub const DAQmx_SwitchChan_MaxACSwitchPwr: u32 = 1604; pub const DAQmx_SwitchChan_MaxDCCarryCurrent: u32 = 1607; pub const DAQmx_SwitchChan_MaxDCSwitchCurrent: u32 = 1605; pub const DAQmx_SwitchChan_MaxDCCarryPwr: u32 = 1603; pub const DAQmx_SwitchChan_MaxDCSwitchPwr: u32 = 1609; pub const DAQmx_SwitchChan_MaxACVoltage: u32 = 1617; pub const DAQmx_SwitchChan_MaxDCVoltage: u32 = 1616; pub const DAQmx_SwitchChan_WireMode: u32 = 6373; pub const DAQmx_SwitchChan_Bandwidth: u32 = 1600; pub const DAQmx_SwitchChan_Impedance: u32 = 1601; pub const DAQmx_SwitchDev_SettlingTime: u32 = 4676; pub const DAQmx_SwitchDev_AutoConnAnlgBus: u32 = 6106; pub const DAQmx_SwitchDev_PwrDownLatchRelaysAfterSettling: u32 = 8923; pub const DAQmx_SwitchDev_Settled: u32 = 4675; pub const DAQmx_SwitchDev_RelayList: u32 = 6108; pub const DAQmx_SwitchDev_NumRelays: u32 = 6374; pub const DAQmx_SwitchDev_SwitchChanList: u32 = 6375; pub const DAQmx_SwitchDev_NumSwitchChans: u32 = 6376; pub const DAQmx_SwitchDev_NumRows: u32 = 6377; pub const DAQmx_SwitchDev_NumColumns: u32 = 6378; pub const DAQmx_SwitchDev_Topology: u32 = 6461; pub const DAQmx_SwitchDev_Temperature: u32 = 12314; pub const DAQmx_SwitchScan_BreakMode: u32 = 4679; pub const DAQmx_SwitchScan_RepeatMode: u32 = 4680; pub const DAQmx_SwitchScan_WaitingForAdv: u32 = 6105; pub const DAQmx_Sys_GlobalChans: u32 = 4709; pub const DAQmx_Sys_Scales: u32 = 4710; pub const DAQmx_Sys_Tasks: u32 = 4711; pub const DAQmx_Sys_DevNames: u32 = 6459; pub const DAQmx_Sys_NIDAQMajorVersion: u32 = 4722; pub const DAQmx_Sys_NIDAQMinorVersion: u32 = 6435; pub const DAQmx_Sys_NIDAQUpdateVersion: u32 = 12066; pub const DAQmx_Task_Name: u32 = 4726; pub const DAQmx_Task_Channels: u32 = 4723; pub const DAQmx_Task_NumChans: u32 = 8577; pub const DAQmx_Task_Devices: u32 = 8974; pub const DAQmx_Task_NumDevices: u32 = 10682; pub const DAQmx_Task_Complete: u32 = 4724; pub const DAQmx_SampQuant_SampMode: u32 = 4864; pub const DAQmx_SampQuant_SampPerChan: u32 = 4880; pub const DAQmx_SampTimingType: u32 = 4935; pub const DAQmx_SampClk_Rate: u32 = 4932; pub const DAQmx_SampClk_MaxRate: u32 = 8904; pub const DAQmx_SampClk_Src: u32 = 6226; pub const DAQmx_SampClk_ActiveEdge: u32 = 4865; pub const DAQmx_SampClk_OverrunBehavior: u32 = 12028; pub const DAQmx_SampClk_UnderflowBehavior: u32 = 10593; pub const DAQmx_SampClk_TimebaseDiv: u32 = 6379; pub const DAQmx_SampClk_Term: u32 = 12059; pub const DAQmx_SampClk_Timebase_Rate: u32 = 4867; pub const DAQmx_SampClk_Timebase_Src: u32 = 4872; pub const DAQmx_SampClk_Timebase_ActiveEdge: u32 = 6380; pub const DAQmx_SampClk_Timebase_MasterTimebaseDiv: u32 = 4869; pub const DAQmx_SampClkTimebase_Term: u32 = 12060; pub const DAQmx_SampClk_DigFltr_Enable: u32 = 8734; pub const DAQmx_SampClk_DigFltr_MinPulseWidth: u32 = 8735; pub const DAQmx_SampClk_DigFltr_TimebaseSrc: u32 = 8736; pub const DAQmx_SampClk_DigFltr_TimebaseRate: u32 = 8737; pub const DAQmx_SampClk_DigSync_Enable: u32 = 8738; pub const DAQmx_SampClk_WriteWfm_UseInitialWfmDT: u32 = 12540; pub const DAQmx_Hshk_DelayAfterXfer: u32 = 8898; pub const DAQmx_Hshk_StartCond: u32 = 8899; pub const DAQmx_Hshk_SampleInputDataWhen: u32 = 8900; pub const DAQmx_ChangeDetect_DI_RisingEdgePhysicalChans: u32 = 8597; pub const DAQmx_ChangeDetect_DI_FallingEdgePhysicalChans: u32 = 8598; pub const DAQmx_ChangeDetect_DI_Tristate: u32 = 12026; pub const DAQmx_OnDemand_SimultaneousAOEnable: u32 = 8608; pub const DAQmx_Implicit_UnderflowBehavior: u32 = 12029; pub const DAQmx_AIConv_Rate: u32 = 6216; pub const DAQmx_AIConv_MaxRate: u32 = 8905; pub const DAQmx_AIConv_Src: u32 = 5378; pub const DAQmx_AIConv_ActiveEdge: u32 = 6227; pub const DAQmx_AIConv_TimebaseDiv: u32 = 4917; pub const DAQmx_AIConv_Timebase_Src: u32 = 4921; pub const DAQmx_DelayFromSampClk_DelayUnits: u32 = 4868; pub const DAQmx_DelayFromSampClk_Delay: u32 = 4887; pub const DAQmx_AIConv_DigFltr_Enable: u32 = 11996; pub const DAQmx_AIConv_DigFltr_MinPulseWidth: u32 = 11997; pub const DAQmx_AIConv_DigFltr_TimebaseSrc: u32 = 11998; pub const DAQmx_AIConv_DigFltr_TimebaseRate: u32 = 11999; pub const DAQmx_AIConv_DigSync_Enable: u32 = 12000; pub const DAQmx_MasterTimebase_Rate: u32 = 5269; pub const DAQmx_MasterTimebase_Src: u32 = 4931; pub const DAQmx_RefClk_Rate: u32 = 4885; pub const DAQmx_RefClk_Src: u32 = 4886; pub const DAQmx_SyncPulse_Type: u32 = 12598; pub const DAQmx_SyncPulse_Src: u32 = 8765; pub const DAQmx_SyncPulse_Time_When: u32 = 12599; pub const DAQmx_SyncPulse_Time_Timescale: u32 = 12600; pub const DAQmx_SyncPulse_SyncTime: u32 = 8766; pub const DAQmx_SyncPulse_MinDelayToStart: u32 = 8767; pub const DAQmx_SyncPulse_ResetTime: u32 = 12156; pub const DAQmx_SyncPulse_ResetDelay: u32 = 12157; pub const DAQmx_SyncPulse_Term: u32 = 12165; pub const DAQmx_SyncClk_Interval: u32 = 12158; pub const DAQmx_SampTimingEngine: u32 = 10790; pub const DAQmx_FirstSampTimestamp_Enable: u32 = 12601; pub const DAQmx_FirstSampTimestamp_Timescale: u32 = 12603; pub const DAQmx_FirstSampTimestamp_Val: u32 = 12602; pub const DAQmx_FirstSampClk_When: u32 = 12674; pub const DAQmx_FirstSampClk_Timescale: u32 = 12675; pub const DAQmx_StartTrig_Type: u32 = 5011; pub const DAQmx_StartTrig_Term: u32 = 12062; pub const DAQmx_DigEdge_StartTrig_Src: u32 = 5127; pub const DAQmx_DigEdge_StartTrig_Edge: u32 = 5124; pub const DAQmx_DigEdge_StartTrig_DigFltr_Enable: u32 = 8739; pub const DAQmx_DigEdge_StartTrig_DigFltr_MinPulseWidth: u32 = 8740; pub const DAQmx_DigEdge_StartTrig_DigFltr_TimebaseSrc: u32 = 8741; pub const DAQmx_DigEdge_StartTrig_DigFltr_TimebaseRate: u32 = 8742; pub const DAQmx_DigEdge_StartTrig_DigSync_Enable: u32 = 8743; pub const DAQmx_DigPattern_StartTrig_Src: u32 = 5136; pub const DAQmx_DigPattern_StartTrig_Pattern: u32 = 8582; pub const DAQmx_DigPattern_StartTrig_When: u32 = 5137; pub const DAQmx_AnlgEdge_StartTrig_Src: u32 = 5016; pub const DAQmx_AnlgEdge_StartTrig_Slope: u32 = 5015; pub const DAQmx_AnlgEdge_StartTrig_Lvl: u32 = 5014; pub const DAQmx_AnlgEdge_StartTrig_Hyst: u32 = 5013; pub const DAQmx_AnlgEdge_StartTrig_Coupling: u32 = 8755; pub const DAQmx_AnlgEdge_StartTrig_DigFltr_Enable: u32 = 12001; pub const DAQmx_AnlgEdge_StartTrig_DigFltr_MinPulseWidth: u32 = 12002; pub const DAQmx_AnlgEdge_StartTrig_DigFltr_TimebaseSrc: u32 = 12003; pub const DAQmx_AnlgEdge_StartTrig_DigFltr_TimebaseRate: u32 = 12004; pub const DAQmx_AnlgEdge_StartTrig_DigSync_Enable: u32 = 12005; pub const DAQmx_AnlgMultiEdge_StartTrig_Srcs: u32 = 12577; pub const DAQmx_AnlgMultiEdge_StartTrig_Slopes: u32 = 12578; pub const DAQmx_AnlgMultiEdge_StartTrig_Lvls: u32 = 12579; pub const DAQmx_AnlgMultiEdge_StartTrig_Hysts: u32 = 12580; pub const DAQmx_AnlgMultiEdge_StartTrig_Couplings: u32 = 12581; pub const DAQmx_AnlgWin_StartTrig_Src: u32 = 5120; pub const DAQmx_AnlgWin_StartTrig_When: u32 = 5121; pub const DAQmx_AnlgWin_StartTrig_Top: u32 = 5123; pub const DAQmx_AnlgWin_StartTrig_Btm: u32 = 5122; pub const DAQmx_AnlgWin_StartTrig_Coupling: u32 = 8756; pub const DAQmx_AnlgWin_StartTrig_DigFltr_Enable: u32 = 12031; pub const DAQmx_AnlgWin_StartTrig_DigFltr_MinPulseWidth: u32 = 12032; pub const DAQmx_AnlgWin_StartTrig_DigFltr_TimebaseSrc: u32 = 12033; pub const DAQmx_AnlgWin_StartTrig_DigFltr_TimebaseRate: u32 = 12034; pub const DAQmx_AnlgWin_StartTrig_DigSync_Enable: u32 = 12035; pub const DAQmx_StartTrig_TrigWhen: u32 = 12365; pub const DAQmx_StartTrig_Timescale: u32 = 12342; pub const DAQmx_StartTrig_TimestampEnable: u32 = 12618; pub const DAQmx_StartTrig_TimestampTimescale: u32 = 12589; pub const DAQmx_StartTrig_TimestampVal: u32 = 12619; pub const DAQmx_StartTrig_Delay: u32 = 6230; pub const DAQmx_StartTrig_DelayUnits: u32 = 6344; pub const DAQmx_StartTrig_Retriggerable: u32 = 6415; pub const DAQmx_StartTrig_TrigWin: u32 = 12570; pub const DAQmx_StartTrig_RetriggerWin: u32 = 12571; pub const DAQmx_StartTrig_MaxNumTrigsToDetect: u32 = 12572; pub const DAQmx_RefTrig_Type: u32 = 5145; pub const DAQmx_RefTrig_PretrigSamples: u32 = 5189; pub const DAQmx_RefTrig_Term: u32 = 12063; pub const DAQmx_DigEdge_RefTrig_Src: u32 = 5172; pub const DAQmx_DigEdge_RefTrig_Edge: u32 = 5168; pub const DAQmx_DigEdge_RefTrig_DigFltr_Enable: u32 = 11991; pub const DAQmx_DigEdge_RefTrig_DigFltr_MinPulseWidth: u32 = 11992; pub const DAQmx_DigEdge_RefTrig_DigFltr_TimebaseSrc: u32 = 11993; pub const DAQmx_DigEdge_RefTrig_DigFltr_TimebaseRate: u32 = 11994; pub const DAQmx_DigEdge_RefTrig_DigSync_Enable: u32 = 11995; pub const DAQmx_DigPattern_RefTrig_Src: u32 = 5175; pub const DAQmx_DigPattern_RefTrig_Pattern: u32 = 8583; pub const DAQmx_DigPattern_RefTrig_When: u32 = 5176; pub const DAQmx_AnlgEdge_RefTrig_Src: u32 = 5156; pub const DAQmx_AnlgEdge_RefTrig_Slope: u32 = 5155; pub const DAQmx_AnlgEdge_RefTrig_Lvl: u32 = 5154; pub const DAQmx_AnlgEdge_RefTrig_Hyst: u32 = 5153; pub const DAQmx_AnlgEdge_RefTrig_Coupling: u32 = 8757; pub const DAQmx_AnlgEdge_RefTrig_DigFltr_Enable: u32 = 12006; pub const DAQmx_AnlgEdge_RefTrig_DigFltr_MinPulseWidth: u32 = 12007; pub const DAQmx_AnlgEdge_RefTrig_DigFltr_TimebaseSrc: u32 = 12008; pub const DAQmx_AnlgEdge_RefTrig_DigFltr_TimebaseRate: u32 = 12009; pub const DAQmx_AnlgEdge_RefTrig_DigSync_Enable: u32 = 12010; pub const DAQmx_AnlgMultiEdge_RefTrig_Srcs: u32 = 12582; pub const DAQmx_AnlgMultiEdge_RefTrig_Slopes: u32 = 12583; pub const DAQmx_AnlgMultiEdge_RefTrig_Lvls: u32 = 12584; pub const DAQmx_AnlgMultiEdge_RefTrig_Hysts: u32 = 12585; pub const DAQmx_AnlgMultiEdge_RefTrig_Couplings: u32 = 12586; pub const DAQmx_AnlgWin_RefTrig_Src: u32 = 5158; pub const DAQmx_AnlgWin_RefTrig_When: u32 = 5159; pub const DAQmx_AnlgWin_RefTrig_Top: u32 = 5161; pub const DAQmx_AnlgWin_RefTrig_Btm: u32 = 5160; pub const DAQmx_AnlgWin_RefTrig_Coupling: u32 = 6231; pub const DAQmx_AnlgWin_RefTrig_DigFltr_Enable: u32 = 12011; pub const DAQmx_AnlgWin_RefTrig_DigFltr_MinPulseWidth: u32 = 12012; pub const DAQmx_AnlgWin_RefTrig_DigFltr_TimebaseSrc: u32 = 12013; pub const DAQmx_AnlgWin_RefTrig_DigFltr_TimebaseRate: u32 = 12014; pub const DAQmx_AnlgWin_RefTrig_DigSync_Enable: u32 = 12015; pub const DAQmx_RefTrig_AutoTrigEnable: u32 = 11969; pub const DAQmx_RefTrig_AutoTriggered: u32 = 11970; pub const DAQmx_RefTrig_TimestampEnable: u32 = 12590; pub const DAQmx_RefTrig_TimestampTimescale: u32 = 12592; pub const DAQmx_RefTrig_TimestampVal: u32 = 12591; pub const DAQmx_RefTrig_Delay: u32 = 5251; pub const DAQmx_RefTrig_Retriggerable: u32 = 12573; pub const DAQmx_RefTrig_TrigWin: u32 = 12574; pub const DAQmx_RefTrig_RetriggerWin: u32 = 12575; pub const DAQmx_RefTrig_MaxNumTrigsToDetect: u32 = 12576; pub const DAQmx_AdvTrig_Type: u32 = 4965; pub const DAQmx_DigEdge_AdvTrig_Src: u32 = 4962; pub const DAQmx_DigEdge_AdvTrig_Edge: u32 = 4960; pub const DAQmx_DigEdge_AdvTrig_DigFltr_Enable: u32 = 8760; pub const DAQmx_HshkTrig_Type: u32 = 8887; pub const DAQmx_Interlocked_HshkTrig_Src: u32 = 8888; pub const DAQmx_Interlocked_HshkTrig_AssertedLvl: u32 = 8889; pub const DAQmx_PauseTrig_Type: u32 = 4966; pub const DAQmx_PauseTrig_Term: u32 = 12064; pub const DAQmx_AnlgLvl_PauseTrig_Src: u32 = 4976; pub const DAQmx_AnlgLvl_PauseTrig_When: u32 = 4977; pub const DAQmx_AnlgLvl_PauseTrig_Lvl: u32 = 4969; pub const DAQmx_AnlgLvl_PauseTrig_Hyst: u32 = 4968; pub const DAQmx_AnlgLvl_PauseTrig_Coupling: u32 = 8758; pub const DAQmx_AnlgLvl_PauseTrig_DigFltr_Enable: u32 = 12016; pub const DAQmx_AnlgLvl_PauseTrig_DigFltr_MinPulseWidth: u32 = 12017; pub const DAQmx_AnlgLvl_PauseTrig_DigFltr_TimebaseSrc: u32 = 12018; pub const DAQmx_AnlgLvl_PauseTrig_DigFltr_TimebaseRate: u32 = 12019; pub const DAQmx_AnlgLvl_PauseTrig_DigSync_Enable: u32 = 12020; pub const DAQmx_AnlgWin_PauseTrig_Src: u32 = 4979; pub const DAQmx_AnlgWin_PauseTrig_When: u32 = 4980; pub const DAQmx_AnlgWin_PauseTrig_Top: u32 = 4982; pub const DAQmx_AnlgWin_PauseTrig_Btm: u32 = 4981; pub const DAQmx_AnlgWin_PauseTrig_Coupling: u32 = 8759; pub const DAQmx_AnlgWin_PauseTrig_DigFltr_Enable: u32 = 12021; pub const DAQmx_AnlgWin_PauseTrig_DigFltr_MinPulseWidth: u32 = 12022; pub const DAQmx_AnlgWin_PauseTrig_DigFltr_TimebaseSrc: u32 = 12023; pub const DAQmx_AnlgWin_PauseTrig_DigFltr_TimebaseRate: u32 = 12024; pub const DAQmx_AnlgWin_PauseTrig_DigSync_Enable: u32 = 12025; pub const DAQmx_DigLvl_PauseTrig_Src: u32 = 4985; pub const DAQmx_DigLvl_PauseTrig_When: u32 = 4992; pub const DAQmx_DigLvl_PauseTrig_DigFltr_Enable: u32 = 8744; pub const DAQmx_DigLvl_PauseTrig_DigFltr_MinPulseWidth: u32 = 8745; pub const DAQmx_DigLvl_PauseTrig_DigFltr_TimebaseSrc: u32 = 8746; pub const DAQmx_DigLvl_PauseTrig_DigFltr_TimebaseRate: u32 = 8747; pub const DAQmx_DigLvl_PauseTrig_DigSync_Enable: u32 = 8748; pub const DAQmx_DigPattern_PauseTrig_Src: u32 = 8559; pub const DAQmx_DigPattern_PauseTrig_Pattern: u32 = 8584; pub const DAQmx_DigPattern_PauseTrig_When: u32 = 8560; pub const DAQmx_ArmStartTrig_Type: u32 = 5140; pub const DAQmx_ArmStart_Term: u32 = 12159; pub const DAQmx_DigEdge_ArmStartTrig_Src: u32 = 5143; pub const DAQmx_DigEdge_ArmStartTrig_Edge: u32 = 5141; pub const DAQmx_DigEdge_ArmStartTrig_DigFltr_Enable: u32 = 8749; pub const DAQmx_DigEdge_ArmStartTrig_DigFltr_MinPulseWidth: u32 = 8750; pub const DAQmx_DigEdge_ArmStartTrig_DigFltr_TimebaseSrc: u32 = 8751; pub const DAQmx_DigEdge_ArmStartTrig_DigFltr_TimebaseRate: u32 = 8752; pub const DAQmx_DigEdge_ArmStartTrig_DigSync_Enable: u32 = 8753; pub const DAQmx_ArmStartTrig_TrigWhen: u32 = 12593; pub const DAQmx_ArmStartTrig_Timescale: u32 = 12594; pub const DAQmx_ArmStartTrig_TimestampEnable: u32 = 12595; pub const DAQmx_ArmStartTrig_TimestampTimescale: u32 = 12597; pub const DAQmx_ArmStartTrig_TimestampVal: u32 = 12596; pub const DAQmx_Trigger_SyncType: u32 = 12160; pub const DAQmx_Watchdog_Timeout: u32 = 8617; pub const DAQmx_WatchdogExpirTrig_Type: u32 = 8611; pub const DAQmx_WatchdogExpirTrig_TrigOnNetworkConnLoss: u32 = 12381; pub const DAQmx_DigEdge_WatchdogExpirTrig_Src: u32 = 8612; pub const DAQmx_DigEdge_WatchdogExpirTrig_Edge: u32 = 8613; pub const DAQmx_Watchdog_DO_ExpirState: u32 = 8615; pub const DAQmx_Watchdog_AO_OutputType: u32 = 12382; pub const DAQmx_Watchdog_AO_ExpirState: u32 = 12383; pub const DAQmx_Watchdog_CO_ExpirState: u32 = 12384; pub const DAQmx_Watchdog_HasExpired: u32 = 8616; pub const DAQmx_Write_RelativeTo: u32 = 6412; pub const DAQmx_Write_Offset: u32 = 6413; pub const DAQmx_Write_RegenMode: u32 = 5203; pub const DAQmx_Write_CurrWritePos: u32 = 5208; pub const DAQmx_Write_OvercurrentChansExist: u32 = 10728; pub const DAQmx_Write_OvercurrentChans: u32 = 10729; pub const DAQmx_Write_OvertemperatureChansExist: u32 = 10884; pub const DAQmx_Write_OvertemperatureChans: u32 = 12419; pub const DAQmx_Write_ExternalOvervoltageChansExist: u32 = 12475; pub const DAQmx_Write_ExternalOvervoltageChans: u32 = 12476; pub const DAQmx_Write_OverloadedChansExist: u32 = 12420; pub const DAQmx_Write_OverloadedChans: u32 = 12421; pub const DAQmx_Write_OpenCurrentLoopChansExist: u32 = 10730; pub const DAQmx_Write_OpenCurrentLoopChans: u32 = 10731; pub const DAQmx_Write_PowerSupplyFaultChansExist: u32 = 10732; pub const DAQmx_Write_PowerSupplyFaultChans: u32 = 10733; pub const DAQmx_Write_Sync_UnlockedChansExist: u32 = 12607; pub const DAQmx_Write_Sync_UnlockedChans: u32 = 12608; pub const DAQmx_Write_SpaceAvail: u32 = 5216; pub const DAQmx_Write_TotalSampPerChanGenerated: u32 = 6443; pub const DAQmx_Write_AccessoryInsertionOrRemovalDetected: u32 = 12371; pub const DAQmx_Write_DevsWithInsertedOrRemovedAccessories: u32 = 12372; pub const DAQmx_Write_RawDataWidth: u32 = 8573; pub const DAQmx_Write_NumChans: u32 = 8574; pub const DAQmx_Write_WaitMode: u32 = 8881; pub const DAQmx_Write_SleepTime: u32 = 8882; pub const DAQmx_Write_DigitalLines_BytesPerChan: u32 = 8575; pub const DAQmx_ReadWaitMode: u32 = 8754; pub const DAQmx_Val_Task_Start: u32 = 0; pub const DAQmx_Val_Task_Stop: u32 = 1; pub const DAQmx_Val_Task_Verify: u32 = 2; pub const DAQmx_Val_Task_Commit: u32 = 3; pub const DAQmx_Val_Task_Reserve: u32 = 4; pub const DAQmx_Val_Task_Unreserve: u32 = 5; pub const DAQmx_Val_Task_Abort: u32 = 6; pub const DAQmx_Val_SynchronousEventCallbacks: u32 = 1; pub const DAQmx_Val_Acquired_Into_Buffer: u32 = 1; pub const DAQmx_Val_Transferred_From_Buffer: u32 = 2; pub const DAQmx_Val_ResetTimer: u32 = 0; pub const DAQmx_Val_ClearExpiration: u32 = 1; pub const DAQmx_Val_ChanPerLine: u32 = 0; pub const DAQmx_Val_ChanForAllLines: u32 = 1; pub const DAQmx_Val_GroupByChannel: u32 = 0; pub const DAQmx_Val_GroupByScanNumber: u32 = 1; pub const DAQmx_Val_DoNotInvertPolarity: u32 = 0; pub const DAQmx_Val_InvertPolarity: u32 = 1; pub const DAQmx_Val_Action_Commit: u32 = 0; pub const DAQmx_Val_Action_Cancel: u32 = 1; pub const DAQmx_Val_AdvanceTrigger: u32 = 12488; pub const DAQmx_Val_Rising: u32 = 10280; pub const DAQmx_Val_Falling: u32 = 10171; pub const DAQmx_Val_PathStatus_Available: u32 = 10431; pub const DAQmx_Val_PathStatus_AlreadyExists: u32 = 10432; pub const DAQmx_Val_PathStatus_Unsupported: u32 = 10433; pub const DAQmx_Val_PathStatus_ChannelInUse: u32 = 10434; pub const DAQmx_Val_PathStatus_SourceChannelConflict: u32 = 10435; pub const DAQmx_Val_PathStatus_ChannelReservedForRouting: u32 = 10436; pub const DAQmx_Val_DegC: u32 = 10143; pub const DAQmx_Val_DegF: u32 = 10144; pub const DAQmx_Val_Kelvins: u32 = 10325; pub const DAQmx_Val_DegR: u32 = 10145; pub const DAQmx_Val_High: u32 = 10192; pub const DAQmx_Val_Low: u32 = 10214; pub const DAQmx_Val_Tristate: u32 = 10310; pub const DAQmx_Val_PullUp: u32 = 15950; pub const DAQmx_Val_PullDown: u32 = 15951; pub const DAQmx_Val_ChannelVoltage: u32 = 0; pub const DAQmx_Val_ChannelCurrent: u32 = 1; pub const DAQmx_Val_ChannelHighImpedance: u32 = 2; pub const DAQmx_Val_Open: u32 = 10437; pub const DAQmx_Val_Closed: u32 = 10438; pub const DAQmx_Val_Loopback0: u32 = 0; pub const DAQmx_Val_Loopback180: u32 = 1; pub const DAQmx_Val_Ground: u32 = 2; pub const DAQmx_Val_Voltage: u32 = 10322; pub const DAQmx_Val_Bridge: u32 = 15908; pub const DAQmx_Val_Current: u32 = 10134; pub const DAQmx_Val_Diff: u32 = 10106; pub const DAQmx_Val_PseudoDiff: u32 = 12529; pub const DAQmx_Val_Charge: u32 = 16105; pub const DAQmx_Val_A: u32 = 12513; pub const DAQmx_Val_B: u32 = 12514; pub const DAQmx_Val_Newtons: u32 = 15875; pub const DAQmx_Val_Pounds: u32 = 15876; pub const DAQmx_Val_FromCustomScale: u32 = 10065; pub const DAQmx_Val_StartTrigger: u32 = 12491; pub const DAQmx_Val_ReferenceTrigger: u32 = 12490; pub const DAQmx_Val_ArmStartTrigger: u32 = 14641; pub const DAQmx_Val_FirstSampleTimestamp: u32 = 16130; pub const DAQmx_Val_Cfg_Default: i32 = -1; pub const DAQmx_Val_Default: i32 = -1; pub const DAQmx_Val_WaitInfinitely: f64 = -1.0; pub const DAQmx_Val_Auto: i32 = -1; pub const DAQmx_Val_Save_Overwrite: u32 = 1; pub const DAQmx_Val_Save_AllowInteractiveEditing: u32 = 2; pub const DAQmx_Val_Save_AllowInteractiveDeletion: u32 = 4; pub const DAQmx_Val_Bit_TriggerUsageTypes_Advance: u32 = 1; pub const DAQmx_Val_Bit_TriggerUsageTypes_Pause: u32 = 2; pub const DAQmx_Val_Bit_TriggerUsageTypes_Reference: u32 = 4; pub const DAQmx_Val_Bit_TriggerUsageTypes_Start: u32 = 8; pub const DAQmx_Val_Bit_TriggerUsageTypes_Handshake: u32 = 16; pub const DAQmx_Val_Bit_TriggerUsageTypes_ArmStart: u32 = 32; pub const DAQmx_Val_Bit_CouplingTypes_AC: u32 = 1; pub const DAQmx_Val_Bit_CouplingTypes_DC: u32 = 2; pub const DAQmx_Val_Bit_CouplingTypes_Ground: u32 = 4; pub const DAQmx_Val_Bit_CouplingTypes_HFReject: u32 = 8; pub const DAQmx_Val_Bit_CouplingTypes_LFReject: u32 = 16; pub const DAQmx_Val_Bit_CouplingTypes_NoiseReject: u32 = 32; pub const DAQmx_Val_Bit_TermCfg_RSE: u32 = 1; pub const DAQmx_Val_Bit_TermCfg_NRSE: u32 = 2; pub const DAQmx_Val_Bit_TermCfg_Diff: u32 = 4; pub const DAQmx_Val_Bit_TermCfg_PseudoDIFF: u32 = 8; pub const DAQmx_Val_4Wire: u32 = 4; pub const DAQmx_Val_5Wire: u32 = 5; pub const DAQmx_Val_6Wire: u32 = 6; pub const DAQmx_Val_Automatic: u32 = 16097; pub const DAQmx_Val_HighResolution: u32 = 10195; pub const DAQmx_Val_HighSpeed: u32 = 14712; pub const DAQmx_Val_Best50HzRejection: u32 = 14713; pub const DAQmx_Val_Best60HzRejection: u32 = 14714; pub const DAQmx_Val_Custom: u32 = 10137; pub const DAQmx_Val_VoltageRMS: u32 = 10350; pub const DAQmx_Val_CurrentRMS: u32 = 10351; pub const DAQmx_Val_Voltage_CustomWithExcitation: u32 = 10323; pub const DAQmx_Val_Freq_Voltage: u32 = 10181; pub const DAQmx_Val_Resistance: u32 = 10278; pub const DAQmx_Val_Temp_TC: u32 = 10303; pub const DAQmx_Val_Temp_Thrmstr: u32 = 10302; pub const DAQmx_Val_Temp_RTD: u32 = 10301; pub const DAQmx_Val_Temp_BuiltInSensor: u32 = 10311; pub const DAQmx_Val_Strain_Gage: u32 = 10300; pub const DAQmx_Val_Rosette_Strain_Gage: u32 = 15980; pub const DAQmx_Val_Position_LVDT: u32 = 10352; pub const DAQmx_Val_Position_RVDT: u32 = 10353; pub const DAQmx_Val_Position_EddyCurrentProximityProbe: u32 = 14835; pub const DAQmx_Val_Accelerometer: u32 = 10356; pub const DAQmx_Val_Acceleration_Charge: u32 = 16104; pub const DAQmx_Val_Acceleration_4WireDCVoltage: u32 = 16106; pub const DAQmx_Val_Velocity_IEPESensor: u32 = 15966; pub const DAQmx_Val_Force_Bridge: u32 = 15899; pub const DAQmx_Val_Force_IEPESensor: u32 = 15895; pub const DAQmx_Val_Pressure_Bridge: u32 = 15902; pub const DAQmx_Val_SoundPressure_Microphone: u32 = 10354; pub const DAQmx_Val_Torque_Bridge: u32 = 15905; pub const DAQmx_Val_TEDS_Sensor: u32 = 12531; pub const DAQmx_Val_ZeroVolts: u32 = 12526; pub const DAQmx_Val_HighImpedance: u32 = 12527; pub const DAQmx_Val_MaintainExistingValue: u32 = 12528; pub const DAQmx_Val_FuncGen: u32 = 14750; pub const DAQmx_Val_PicoCoulombsPerG: u32 = 16099; pub const DAQmx_Val_PicoCoulombsPerMetersPerSecondSquared: u32 = 16100; pub const DAQmx_Val_PicoCoulombsPerInchesPerSecondSquared: u32 = 16101; pub const DAQmx_Val_mVoltsPerG: u32 = 12509; pub const DAQmx_Val_VoltsPerG: u32 = 12510; pub const DAQmx_Val_AccelUnit_g: u32 = 10186; pub const DAQmx_Val_MetersPerSecondSquared: u32 = 12470; pub const DAQmx_Val_InchesPerSecondSquared: u32 = 12471; pub const DAQmx_Val_FiniteSamps: u32 = 10178; pub const DAQmx_Val_ContSamps: u32 = 10123; pub const DAQmx_Val_HWTimedSinglePoint: u32 = 12522; pub const DAQmx_Val_AboveLvl: u32 = 10093; pub const DAQmx_Val_BelowLvl: u32 = 10107; pub const DAQmx_Val_Degrees: u32 = 10146; pub const DAQmx_Val_Radians: u32 = 10273; pub const DAQmx_Val_Ticks: u32 = 10304; pub const DAQmx_Val_RPM: u32 = 16080; pub const DAQmx_Val_RadiansPerSecond: u32 = 16081; pub const DAQmx_Val_DegreesPerSecond: u32 = 16082; pub const DAQmx_Val_None: u32 = 10230; pub const DAQmx_Val_Once: u32 = 10244; pub const DAQmx_Val_EverySample: u32 = 10164; pub const DAQmx_Val_NoAction: u32 = 10227; pub const DAQmx_Val_BreakBeforeMake: u32 = 10110; pub const DAQmx_Val_FullBridge: u32 = 10182; pub const DAQmx_Val_HalfBridge: u32 = 10187; pub const DAQmx_Val_QuarterBridge: u32 = 10270; pub const DAQmx_Val_NoBridge: u32 = 10228; pub const DAQmx_Val_VoltsPerVolt: u32 = 15896; pub const DAQmx_Val_mVoltsPerVolt: u32 = 15897; pub const DAQmx_Val_KilogramForce: u32 = 15877; pub const DAQmx_Val_Pascals: u32 = 10081; pub const DAQmx_Val_PoundsPerSquareInch: u32 = 15879; pub const DAQmx_Val_Bar: u32 = 15880; pub const DAQmx_Val_NewtonMeters: u32 = 15881; pub const DAQmx_Val_InchOunces: u32 = 15882; pub const DAQmx_Val_InchPounds: u32 = 15883; pub const DAQmx_Val_FootPounds: u32 = 15884; pub const DAQmx_Val_FromTEDS: u32 = 12516; pub const DAQmx_Val_PCI: u32 = 12582; pub const DAQmx_Val_PCIe: u32 = 13612; pub const DAQmx_Val_PXI: u32 = 12583; pub const DAQmx_Val_PXIe: u32 = 14706; pub const DAQmx_Val_SCXI: u32 = 12584; pub const DAQmx_Val_SCC: u32 = 14707; pub const DAQmx_Val_PCCard: u32 = 12585; pub const DAQmx_Val_USB: u32 = 12586; pub const DAQmx_Val_CompactDAQ: u32 = 14637; pub const DAQmx_Val_CompactRIO: u32 = 16143; pub const DAQmx_Val_TCPIP: u32 = 14828; pub const DAQmx_Val_Unknown: u32 = 12588; pub const DAQmx_Val_SwitchBlock: u32 = 15870; pub const DAQmx_Val_CountEdges: u32 = 10125; pub const DAQmx_Val_Freq: u32 = 10179; pub const DAQmx_Val_Period: u32 = 10256; pub const DAQmx_Val_PulseWidth: u32 = 10359; pub const DAQmx_Val_SemiPeriod: u32 = 10289; pub const DAQmx_Val_PulseFrequency: u32 = 15864; pub const DAQmx_Val_PulseTime: u32 = 15865; pub const DAQmx_Val_PulseTicks: u32 = 15866; pub const DAQmx_Val_DutyCycle: u32 = 16070; pub const DAQmx_Val_Position_AngEncoder: u32 = 10360; pub const DAQmx_Val_Position_LinEncoder: u32 = 10361; pub const DAQmx_Val_Velocity_AngEncoder: u32 = 16078; pub const DAQmx_Val_Velocity_LinEncoder: u32 = 16079; pub const DAQmx_Val_TwoEdgeSep: u32 = 10267; pub const DAQmx_Val_GPS_Timestamp: u32 = 10362; pub const DAQmx_Val_BuiltIn: u32 = 10200; pub const DAQmx_Val_ConstVal: u32 = 10116; pub const DAQmx_Val_Chan: u32 = 10113; pub const DAQmx_Val_Pulse_Time: u32 = 10269; pub const DAQmx_Val_Pulse_Freq: u32 = 10119; pub const DAQmx_Val_Pulse_Ticks: u32 = 10268; pub const DAQmx_Val_AI: u32 = 10100; pub const DAQmx_Val_AO: u32 = 10102; pub const DAQmx_Val_DI: u32 = 10151; pub const DAQmx_Val_DO: u32 = 10153; pub const DAQmx_Val_CI: u32 = 10131; pub const DAQmx_Val_CO: u32 = 10132; pub const DAQmx_Val_Unconstrained: u32 = 14708; pub const DAQmx_Val_FixedHighFreq: u32 = 14709; pub const DAQmx_Val_FixedLowFreq: u32 = 14710; pub const DAQmx_Val_Fixed50PercentDutyCycle: u32 = 14711; pub const DAQmx_Val_CountUp: u32 = 10128; pub const DAQmx_Val_CountDown: u32 = 10124; pub const DAQmx_Val_ExtControlled: u32 = 10326; pub const DAQmx_Val_LowFreq1Ctr: u32 = 10105; pub const DAQmx_Val_HighFreq2Ctr: u32 = 10157; pub const DAQmx_Val_LargeRng2Ctr: u32 = 10205; pub const DAQmx_Val_DynAvg: u32 = 16065; pub const DAQmx_Val_AC: u32 = 10045; pub const DAQmx_Val_DC: u32 = 10050; pub const DAQmx_Val_GND: u32 = 10066; pub const DAQmx_Val_Internal: u32 = 10200; pub const DAQmx_Val_External: u32 = 10167; pub const DAQmx_Val_UserProvided: u32 = 10167; pub const DAQmx_Val_Coulombs: u32 = 16102; pub const DAQmx_Val_PicoCoulombs: u32 = 16103; pub const DAQmx_Val_Amps: u32 = 10342; pub const DAQmx_Val_RightJustified: u32 = 10279; pub const DAQmx_Val_LeftJustified: u32 = 10209; pub const DAQmx_Val_DMA: u32 = 10054; pub const DAQmx_Val_Interrupts: u32 = 10204; pub const DAQmx_Val_ProgrammedIO: u32 = 10264; pub const DAQmx_Val_USBbulk: u32 = 12590; pub const DAQmx_Val_OnbrdMemMoreThanHalfFull: u32 = 10237; pub const DAQmx_Val_OnbrdMemFull: u32 = 10236; pub const DAQmx_Val_OnbrdMemCustomThreshold: u32 = 12577; pub const DAQmx_Val_ActiveDrive: u32 = 12573; pub const DAQmx_Val_OpenCollector: u32 = 12574; pub const DAQmx_Val_NoChange: u32 = 10160; pub const DAQmx_Val_PatternMatches: u32 = 10254; pub const DAQmx_Val_PatternDoesNotMatch: u32 = 10253; pub const DAQmx_Val_SampClkPeriods: u32 = 10286; pub const DAQmx_Val_Seconds: u32 = 10364; pub const DAQmx_Val_SampleClkPeriods: u32 = 10286; pub const DAQmx_Val_mVoltsPerMil: u32 = 14836; pub const DAQmx_Val_VoltsPerMil: u32 = 14837; pub const DAQmx_Val_mVoltsPerMillimeter: u32 = 14838; pub const DAQmx_Val_VoltsPerMillimeter: u32 = 14839; pub const DAQmx_Val_mVoltsPerMicron: u32 = 14840; pub const DAQmx_Val_X1: u32 = 10090; pub const DAQmx_Val_X2: u32 = 10091; pub const DAQmx_Val_X4: u32 = 10092; pub const DAQmx_Val_TwoPulseCounting: u32 = 10313; pub const DAQmx_Val_AHighBHigh: u32 = 10040; pub const DAQmx_Val_AHighBLow: u32 = 10041; pub const DAQmx_Val_ALowBHigh: u32 = 10042; pub const DAQmx_Val_ALowBLow: u32 = 10043; pub const DAQmx_Val_Pulse: u32 = 10265; pub const DAQmx_Val_Toggle: u32 = 10307; pub const DAQmx_Val_Lvl: u32 = 10210; pub const DAQmx_Val_Interlocked: u32 = 12549; pub const DAQmx_Val_Lowpass: u32 = 16071; pub const DAQmx_Val_Highpass: u32 = 16072; pub const DAQmx_Val_Bandpass: u32 = 16073; pub const DAQmx_Val_Notch: u32 = 16074; pub const DAQmx_Val_ConstantGroupDelay: u32 = 16075; pub const DAQmx_Val_Butterworth: u32 = 16076; pub const DAQmx_Val_Elliptical: u32 = 16077; pub const DAQmx_Val_HardwareDefined: u32 = 10191; pub const DAQmx_Val_Comb: u32 = 16152; pub const DAQmx_Val_Bessel: u32 = 16153; pub const DAQmx_Val_Brickwall: u32 = 16155; pub const DAQmx_Val_mVoltsPerNewton: u32 = 15891; pub const DAQmx_Val_mVoltsPerPound: u32 = 15892; pub const DAQmx_Val_Hz: u32 = 10373; pub const DAQmx_Val_Sine: u32 = 14751; pub const DAQmx_Val_Triangle: u32 = 14752; pub const DAQmx_Val_Square: u32 = 14753; pub const DAQmx_Val_Sawtooth: u32 = 14754; pub const DAQmx_Val_IRIGB: u32 = 10070; pub const DAQmx_Val_PPS: u32 = 10080; pub const DAQmx_Val_Immediate: u32 = 10198; pub const DAQmx_Val_WaitForHandshakeTriggerAssert: u32 = 12550; pub const DAQmx_Val_WaitForHandshakeTriggerDeassert: u32 = 12551; pub const DAQmx_Val_OnBrdMemMoreThanHalfFull: u32 = 10237; pub const DAQmx_Val_OnBrdMemNotEmpty: u32 = 10241; pub const DAQmx_Val_WhenAcqComplete: u32 = 12546; pub const DAQmx_Val_RSE: u32 = 10083; pub const DAQmx_Val_NRSE: u32 = 10078; pub const DAQmx_Val_mVoltsPerVoltPerMillimeter: u32 = 12506; pub const DAQmx_Val_mVoltsPerVoltPerMilliInch: u32 = 12505; pub const DAQmx_Val_Meters: u32 = 10219; pub const DAQmx_Val_Inches: u32 = 10379; pub const DAQmx_Val_Off: u32 = 10231; pub const DAQmx_Val_Log: u32 = 15844; pub const DAQmx_Val_LogAndRead: u32 = 15842; pub const DAQmx_Val_OpenOrCreate: u32 = 15846; pub const DAQmx_Val_CreateOrReplace: u32 = 15847; pub const DAQmx_Val_Create: u32 = 15848; pub const DAQmx_Val_2point5V: u32 = 14620; pub const DAQmx_Val_3point3V: u32 = 14621; pub const DAQmx_Val_5V: u32 = 14619; pub const DAQmx_Val_SameAsSampTimebase: u32 = 10284; pub const DAQmx_Val_SameAsMasterTimebase: u32 = 10282; pub const DAQmx_Val_100MHzTimebase: u32 = 15857; pub const DAQmx_Val_80MHzTimebase: u32 = 14636; pub const DAQmx_Val_20MHzTimebase: u32 = 12537; pub const DAQmx_Val_8MHzTimebase: u32 = 16023; pub const DAQmx_Val_AM: u32 = 14756; pub const DAQmx_Val_FM: u32 = 14757; pub const DAQmx_Val_OnBrdMemEmpty: u32 = 10235; pub const DAQmx_Val_OnBrdMemHalfFullOrLess: u32 = 10239; pub const DAQmx_Val_OnBrdMemNotFull: u32 = 10242; pub const DAQmx_Val_StopTaskAndError: u32 = 15862; pub const DAQmx_Val_IgnoreOverruns: u32 = 15863; pub const DAQmx_Val_OverwriteUnreadSamps: u32 = 10252; pub const DAQmx_Val_DoNotOverwriteUnreadSamps: u32 = 10159; pub const DAQmx_Val_ActiveHigh: u32 = 10095; pub const DAQmx_Val_ActiveLow: u32 = 10096; pub const DAQmx_Val_MSeriesDAQ: u32 = 14643; pub const DAQmx_Val_XSeriesDAQ: u32 = 15858; pub const DAQmx_Val_ESeriesDAQ: u32 = 14642; pub const DAQmx_Val_SSeriesDAQ: u32 = 14644; pub const DAQmx_Val_BSeriesDAQ: u32 = 14662; pub const DAQmx_Val_SCSeriesDAQ: u32 = 14645; pub const DAQmx_Val_USBDAQ: u32 = 14646; pub const DAQmx_Val_AOSeries: u32 = 14647; pub const DAQmx_Val_DigitalIO: u32 = 14648; pub const DAQmx_Val_TIOSeries: u32 = 14661; pub const DAQmx_Val_DynamicSignalAcquisition: u32 = 14649; pub const DAQmx_Val_Switches: u32 = 14650; pub const DAQmx_Val_CompactDAQChassis: u32 = 14658; pub const DAQmx_Val_CompactRIOChassis: u32 = 16144; pub const DAQmx_Val_CSeriesModule: u32 = 14659; pub const DAQmx_Val_SCXIModule: u32 = 14660; pub const DAQmx_Val_SCCConnectorBlock: u32 = 14704; pub const DAQmx_Val_SCCModule: u32 = 14705; pub const DAQmx_Val_NIELVIS: u32 = 14755; pub const DAQmx_Val_NetworkDAQ: u32 = 14829; pub const DAQmx_Val_SCExpress: u32 = 15886; pub const DAQmx_Val_FieldDAQ: u32 = 16151; pub const DAQmx_Val_Pt3750: u32 = 12481; pub const DAQmx_Val_Pt3851: u32 = 10071; pub const DAQmx_Val_Pt3911: u32 = 12482; pub const DAQmx_Val_Pt3916: u32 = 10069; pub const DAQmx_Val_Pt3920: u32 = 10053; pub const DAQmx_Val_Pt3928: u32 = 12483; pub const DAQmx_Val_mVoltsPerVoltPerDegree: u32 = 12507; pub const DAQmx_Val_mVoltsPerVoltPerRadian: u32 = 12508; pub const DAQmx_Val_LosslessPacking: u32 = 12555; pub const DAQmx_Val_LossyLSBRemoval: u32 = 12556; pub const DAQmx_Val_FirstSample: u32 = 10424; pub const DAQmx_Val_CurrReadPos: u32 = 10425; pub const DAQmx_Val_RefTrig: u32 = 10426; pub const DAQmx_Val_FirstPretrigSamp: u32 = 10427; pub const DAQmx_Val_MostRecentSamp: u32 = 10428; pub const DAQmx_Val_AllowRegen: u32 = 10097; pub const DAQmx_Val_DoNotAllowRegen: u32 = 10158; pub const DAQmx_Val_2Wire: u32 = 2; pub const DAQmx_Val_3Wire: u32 = 3; pub const DAQmx_Val_Ohms: u32 = 10384; pub const DAQmx_Val_Bits: u32 = 10109; pub const DAQmx_Val_SCXI1124Range0to1V: u32 = 14629; pub const DAQmx_Val_SCXI1124Range0to5V: u32 = 14630; pub const DAQmx_Val_SCXI1124Range0to10V: u32 = 14631; pub const DAQmx_Val_SCXI1124RangeNeg1to1V: u32 = 14632; pub const DAQmx_Val_SCXI1124RangeNeg5to5V: u32 = 14633; pub const DAQmx_Val_SCXI1124RangeNeg10to10V: u32 = 14634; pub const DAQmx_Val_SCXI1124Range0to20mA: u32 = 14635; pub const DAQmx_Val_SampClkActiveEdge: u32 = 14617; pub const DAQmx_Val_SampClkInactiveEdge: u32 = 14618; pub const DAQmx_Val_HandshakeTriggerAsserts: u32 = 12552; pub const DAQmx_Val_HandshakeTriggerDeasserts: u32 = 12553; pub const DAQmx_Val_SampClk: u32 = 10388; pub const DAQmx_Val_BurstHandshake: u32 = 12548; pub const DAQmx_Val_Handshake: u32 = 10389; pub const DAQmx_Val_Implicit: u32 = 10451; pub const DAQmx_Val_OnDemand: u32 = 10390; pub const DAQmx_Val_ChangeDetection: u32 = 12504; pub const DAQmx_Val_PipelinedSampClk: u32 = 14668; pub const DAQmx_Val_Linear: u32 = 10447; pub const DAQmx_Val_MapRanges: u32 = 10448; pub const DAQmx_Val_Polynomial: u32 = 10449; pub const DAQmx_Val_Table: u32 = 10450; pub const DAQmx_Val_TwoPointLinear: u32 = 15898; pub const DAQmx_Val_Enabled: u32 = 16145; pub const DAQmx_Val_Disabled: u32 = 16146; pub const DAQmx_Val_BipolarDC: u32 = 16147; pub const DAQmx_Val_AandB: u32 = 12515; pub const DAQmx_Val_R1: u32 = 12465; pub const DAQmx_Val_R2: u32 = 12466; pub const DAQmx_Val_R3: u32 = 12467; pub const DAQmx_Val_R4: u32 = 14813; pub const DAQmx_Val_AIConvertClock: u32 = 12484; pub const DAQmx_Val_10MHzRefClock: u32 = 12536; pub const DAQmx_Val_20MHzTimebaseClock: u32 = 12486; pub const DAQmx_Val_SampleClock: u32 = 12487; pub const DAQmx_Val_AdvCmpltEvent: u32 = 12492; pub const DAQmx_Val_AIHoldCmpltEvent: u32 = 12493; pub const DAQmx_Val_CounterOutputEvent: u32 = 12494; pub const DAQmx_Val_ChangeDetectionEvent: u32 = 12511; pub const DAQmx_Val_WDTExpiredEvent: u32 = 12512; pub const DAQmx_Val_SampleCompleteEvent: u32 = 12530; pub const DAQmx_Val_RisingSlope: u32 = 10280; pub const DAQmx_Val_FallingSlope: u32 = 10171; pub const DAQmx_Val_FullBridgeI: u32 = 10183; pub const DAQmx_Val_FullBridgeII: u32 = 10184; pub const DAQmx_Val_FullBridgeIII: u32 = 10185; pub const DAQmx_Val_HalfBridgeI: u32 = 10188; pub const DAQmx_Val_HalfBridgeII: u32 = 10189; pub const DAQmx_Val_QuarterBridgeI: u32 = 10271; pub const DAQmx_Val_QuarterBridgeII: u32 = 10272; pub const DAQmx_Val_RectangularRosette: u32 = 15968; pub const DAQmx_Val_DeltaRosette: u32 = 15969; pub const DAQmx_Val_TeeRosette: u32 = 15970; pub const DAQmx_Val_PrincipalStrain1: u32 = 15971; pub const DAQmx_Val_PrincipalStrain2: u32 = 15972; pub const DAQmx_Val_PrincipalStrainAngle: u32 = 15973; pub const DAQmx_Val_CartesianStrainX: u32 = 15974; pub const DAQmx_Val_CartesianStrainY: u32 = 15975; pub const DAQmx_Val_CartesianShearStrainXY: u32 = 15976; pub const DAQmx_Val_MaxShearStrain: u32 = 15977; pub const DAQmx_Val_MaxShearStrainAngle: u32 = 15978; pub const DAQmx_Val_Strain: u32 = 10299; pub const DAQmx_Val_Finite: u32 = 10172; pub const DAQmx_Val_Cont: u32 = 10117; pub const DAQmx_Val_Source: u32 = 10439; pub const DAQmx_Val_Load: u32 = 10440; pub const DAQmx_Val_ReservedForRouting: u32 = 10441; pub const DAQmx_Val_Onboard: u32 = 16128; pub const DAQmx_Val_DigEdge: u32 = 10150; pub const DAQmx_Val_Time: u32 = 15996; pub const DAQmx_Val_Master: u32 = 15888; pub const DAQmx_Val_Slave: u32 = 15889; pub const DAQmx_Val_IgnoreLostSyncLock: u32 = 16129; pub const DAQmx_Val_J_Type_TC: u32 = 10072; pub const DAQmx_Val_K_Type_TC: u32 = 10073; pub const DAQmx_Val_N_Type_TC: u32 = 10077; pub const DAQmx_Val_R_Type_TC: u32 = 10082; pub const DAQmx_Val_S_Type_TC: u32 = 10085; pub const DAQmx_Val_T_Type_TC: u32 = 10086; pub const DAQmx_Val_B_Type_TC: u32 = 10047; pub const DAQmx_Val_E_Type_TC: u32 = 10055; pub const DAQmx_Val_HostTime: u32 = 16126; pub const DAQmx_Val_IODeviceTime: u32 = 16127; pub const DAQmx_Val_SingleCycle: u32 = 14613; pub const DAQmx_Val_Multicycle: u32 = 14614; pub const DAQmx_Val_Software: u32 = 10292; pub const DAQmx_Val_AnlgLvl: u32 = 10101; pub const DAQmx_Val_AnlgWin: u32 = 10103; pub const DAQmx_Val_DigLvl: u32 = 10152; pub const DAQmx_Val_DigPattern: u32 = 10398; pub const DAQmx_Val_AnlgEdge: u32 = 10099; pub const DAQmx_Val_AnlgMultiEdge: u32 = 16108; pub const DAQmx_Val_HaltOutputAndError: u32 = 14615; pub const DAQmx_Val_PauseUntilDataAvailable: u32 = 14616; pub const DAQmx_Val_Volts: u32 = 10348; pub const DAQmx_Val_g: u32 = 10186; pub const DAQmx_Val_MetersPerSecond: u32 = 15959; pub const DAQmx_Val_InchesPerSecond: u32 = 15960; pub const DAQmx_Val_MillivoltsPerMillimeterPerSecond: u32 = 15963; pub const DAQmx_Val_MilliVoltsPerInchPerSecond: u32 = 15964; pub const DAQmx_Val_WaitForInterrupt: u32 = 12523; pub const DAQmx_Val_Poll: u32 = 12524; pub const DAQmx_Val_Yield: u32 = 12525; pub const DAQmx_Val_Sleep: u32 = 12547; pub const DAQmx_Val_EnteringWin: u32 = 10163; pub const DAQmx_Val_LeavingWin: u32 = 10208; pub const DAQmx_Val_InsideWin: u32 = 10199; pub const DAQmx_Val_OutsideWin: u32 = 10251; pub const DAQmx_Val_WriteToEEPROM: u32 = 12538; pub const DAQmx_Val_WriteToPROM: u32 = 12539; pub const DAQmx_Val_DoNotWrite: u32 = 12540; pub const DAQmx_Val_CurrWritePos: u32 = 10430; pub const DAQmx_Val_ZeroVoltsOrAmps: u32 = 12526; pub const DAQmx_Val_RepeatedData: u32 = 16062; pub const DAQmx_Val_SentinelValue: u32 = 16063; pub const DAQmx_Val_LogicLevelPullUp: u32 = 16064; pub const DAQmx_Val_Local: u32 = 16095; pub const DAQmx_Val_Remote: u32 = 16096; pub const DAQmx_Val_Switch_Topology_Configured_Topology: &'static [u8; 20usize] = b"Configured Topology\0"; pub const DAQmx_Val_Switch_Topology_1127_1_Wire_64x1_Mux: &'static [u8; 21usize] = b"1127/1-Wire 64x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1127_2_Wire_32x1_Mux: &'static [u8; 21usize] = b"1127/2-Wire 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1127_2_Wire_4x8_Matrix: &'static [u8; 23usize] = b"1127/2-Wire 4x8 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1127_4_Wire_16x1_Mux: &'static [u8; 21usize] = b"1127/4-Wire 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1127_Independent: &'static [u8; 17usize] = b"1127/Independent\0"; pub const DAQmx_Val_Switch_Topology_1128_1_Wire_64x1_Mux: &'static [u8; 21usize] = b"1128/1-Wire 64x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1128_2_Wire_32x1_Mux: &'static [u8; 21usize] = b"1128/2-Wire 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1128_2_Wire_4x8_Matrix: &'static [u8; 23usize] = b"1128/2-Wire 4x8 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1128_4_Wire_16x1_Mux: &'static [u8; 21usize] = b"1128/4-Wire 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1128_Independent: &'static [u8; 17usize] = b"1128/Independent\0"; pub const DAQmx_Val_Switch_Topology_1129_2_Wire_16x16_Matrix: &'static [u8; 25usize] = b"1129/2-Wire 16x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1129_2_Wire_8x32_Matrix: &'static [u8; 24usize] = b"1129/2-Wire 8x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1129_2_Wire_4x64_Matrix: &'static [u8; 24usize] = b"1129/2-Wire 4x64 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1129_2_Wire_Dual_8x16_Matrix: &'static [u8; 29usize] = b"1129/2-Wire Dual 8x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1129_2_Wire_Dual_4x32_Matrix: &'static [u8; 29usize] = b"1129/2-Wire Dual 4x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1129_2_Wire_Quad_4x16_Matrix: &'static [u8; 29usize] = b"1129/2-Wire Quad 4x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1130_1_Wire_256x1_Mux: &'static [u8; 22usize] = b"1130/1-Wire 256x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_1_Wire_Dual_128x1_Mux: &'static [u8; 27usize] = b"1130/1-Wire Dual 128x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_2_Wire_128x1_Mux: &'static [u8; 22usize] = b"1130/2-Wire 128x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_4_Wire_64x1_Mux: &'static [u8; 21usize] = b"1130/4-Wire 64x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_1_Wire_4x64_Matrix: &'static [u8; 24usize] = b"1130/1-Wire 4x64 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1130_1_Wire_8x32_Matrix: &'static [u8; 24usize] = b"1130/1-Wire 8x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1130_1_Wire_Octal_32x1_Mux: &'static [u8; 27usize] = b"1130/1-Wire Octal 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_1_Wire_Quad_64x1_Mux: &'static [u8; 26usize] = b"1130/1-Wire Quad 64x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_1_Wire_Sixteen_16x1_Mux: &'static [u8; 29usize] = b"1130/1-Wire Sixteen 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_2_Wire_4x32_Matrix: &'static [u8; 24usize] = b"1130/2-Wire 4x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_1130_2_Wire_Octal_16x1_Mux: &'static [u8; 27usize] = b"1130/2-Wire Octal 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_2_Wire_Quad_32x1_Mux: &'static [u8; 26usize] = b"1130/2-Wire Quad 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_4_Wire_Quad_16x1_Mux: &'static [u8; 26usize] = b"1130/4-Wire Quad 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1130_Independent: &'static [u8; 17usize] = b"1130/Independent\0"; pub const DAQmx_Val_Switch_Topology_1160_16_SPDT: &'static [u8; 13usize] = b"1160/16-SPDT\0"; pub const DAQmx_Val_Switch_Topology_1161_8_SPDT: &'static [u8; 12usize] = b"1161/8-SPDT\0"; pub const DAQmx_Val_Switch_Topology_1163R_Octal_4x1_Mux: &'static [u8; 20usize] = b"1163R/Octal 4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1166_32_SPDT: &'static [u8; 13usize] = b"1166/32-SPDT\0"; pub const DAQmx_Val_Switch_Topology_1166_16_DPDT: &'static [u8; 13usize] = b"1166/16-DPDT\0"; pub const DAQmx_Val_Switch_Topology_1167_Independent: &'static [u8; 17usize] = b"1167/Independent\0"; pub const DAQmx_Val_Switch_Topology_1169_100_SPST: &'static [u8; 14usize] = b"1169/100-SPST\0"; pub const DAQmx_Val_Switch_Topology_1169_50_DPST: &'static [u8; 13usize] = b"1169/50-DPST\0"; pub const DAQmx_Val_Switch_Topology_1175_1_Wire_196x1_Mux: &'static [u8; 22usize] = b"1175/1-Wire 196x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1175_2_Wire_98x1_Mux: &'static [u8; 21usize] = b"1175/2-Wire 98x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1175_2_Wire_95x1_Mux: &'static [u8; 21usize] = b"1175/2-Wire 95x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1190_Quad_4x1_Mux: &'static [u8; 18usize] = b"1190/Quad 4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1191_Quad_4x1_Mux: &'static [u8; 18usize] = b"1191/Quad 4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1192_8_SPDT: &'static [u8; 12usize] = b"1192/8-SPDT\0"; pub const DAQmx_Val_Switch_Topology_1193_32x1_Mux: &'static [u8; 14usize] = b"1193/32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1193_Dual_16x1_Mux: &'static [u8; 19usize] = b"1193/Dual 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1193_Quad_8x1_Mux: &'static [u8; 18usize] = b"1193/Quad 8x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1193_16x1_Terminated_Mux: &'static [u8; 25usize] = b"1193/16x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_1193_Dual_8x1_Terminated_Mux: &'static [u8; 29usize] = b"1193/Dual 8x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_1193_Quad_4x1_Terminated_Mux: &'static [u8; 29usize] = b"1193/Quad 4x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_1193_Independent: &'static [u8; 17usize] = b"1193/Independent\0"; pub const DAQmx_Val_Switch_Topology_1194_Quad_4x1_Mux: &'static [u8; 18usize] = b"1194/Quad 4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_1195_Quad_4x1_Mux: &'static [u8; 18usize] = b"1195/Quad 4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2501_1_Wire_48x1_Mux: &'static [u8; 21usize] = b"2501/1-Wire 48x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2501_1_Wire_48x1_Amplified_Mux: &'static [u8; 31usize] = b"2501/1-Wire 48x1 Amplified Mux\0"; pub const DAQmx_Val_Switch_Topology_2501_2_Wire_24x1_Mux: &'static [u8; 21usize] = b"2501/2-Wire 24x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2501_2_Wire_24x1_Amplified_Mux: &'static [u8; 31usize] = b"2501/2-Wire 24x1 Amplified Mux\0"; pub const DAQmx_Val_Switch_Topology_2501_2_Wire_Dual_12x1_Mux: &'static [u8; 26usize] = b"2501/2-Wire Dual 12x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2501_2_Wire_Quad_6x1_Mux: &'static [u8; 25usize] = b"2501/2-Wire Quad 6x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2501_2_Wire_4x6_Matrix: &'static [u8; 23usize] = b"2501/2-Wire 4x6 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2501_4_Wire_12x1_Mux: &'static [u8; 21usize] = b"2501/4-Wire 12x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2503_1_Wire_48x1_Mux: &'static [u8; 21usize] = b"2503/1-Wire 48x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2503_2_Wire_24x1_Mux: &'static [u8; 21usize] = b"2503/2-Wire 24x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2503_2_Wire_Dual_12x1_Mux: &'static [u8; 26usize] = b"2503/2-Wire Dual 12x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2503_2_Wire_Quad_6x1_Mux: &'static [u8; 25usize] = b"2503/2-Wire Quad 6x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2503_2_Wire_4x6_Matrix: &'static [u8; 23usize] = b"2503/2-Wire 4x6 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2503_4_Wire_12x1_Mux: &'static [u8; 21usize] = b"2503/4-Wire 12x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2510_Independent: &'static [u8; 17usize] = b"2510/Independent\0"; pub const DAQmx_Val_Switch_Topology_2512_Independent: &'static [u8; 17usize] = b"2512/Independent\0"; pub const DAQmx_Val_Switch_Topology_2514_Independent: &'static [u8; 17usize] = b"2514/Independent\0"; pub const DAQmx_Val_Switch_Topology_2515_Independent: &'static [u8; 17usize] = b"2515/Independent\0"; pub const DAQmx_Val_Switch_Topology_2520_80_SPST: &'static [u8; 13usize] = b"2520/80-SPST\0"; pub const DAQmx_Val_Switch_Topology_2521_40_DPST: &'static [u8; 13usize] = b"2521/40-DPST\0"; pub const DAQmx_Val_Switch_Topology_2522_53_SPDT: &'static [u8; 13usize] = b"2522/53-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2523_26_DPDT: &'static [u8; 13usize] = b"2523/26-DPDT\0"; pub const DAQmx_Val_Switch_Topology_2527_1_Wire_64x1_Mux: &'static [u8; 21usize] = b"2527/1-Wire 64x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2527_1_Wire_Dual_32x1_Mux: &'static [u8; 26usize] = b"2527/1-Wire Dual 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2527_2_Wire_32x1_Mux: &'static [u8; 21usize] = b"2527/2-Wire 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2527_2_Wire_Dual_16x1_Mux: &'static [u8; 26usize] = b"2527/2-Wire Dual 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2527_4_Wire_16x1_Mux: &'static [u8; 21usize] = b"2527/4-Wire 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2527_Independent: &'static [u8; 17usize] = b"2527/Independent\0"; pub const DAQmx_Val_Switch_Topology_2529_2_Wire_8x16_Matrix: &'static [u8; 24usize] = b"2529/2-Wire 8x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2529_2_Wire_4x32_Matrix: &'static [u8; 24usize] = b"2529/2-Wire 4x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2529_2_Wire_Dual_4x16_Matrix: &'static [u8; 29usize] = b"2529/2-Wire Dual 4x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2530_1_Wire_128x1_Mux: &'static [u8; 22usize] = b"2530/1-Wire 128x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_1_Wire_Dual_64x1_Mux: &'static [u8; 26usize] = b"2530/1-Wire Dual 64x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_2_Wire_64x1_Mux: &'static [u8; 21usize] = b"2530/2-Wire 64x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_4_Wire_32x1_Mux: &'static [u8; 21usize] = b"2530/4-Wire 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_1_Wire_4x32_Matrix: &'static [u8; 24usize] = b"2530/1-Wire 4x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2530_1_Wire_8x16_Matrix: &'static [u8; 24usize] = b"2530/1-Wire 8x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2530_1_Wire_Octal_16x1_Mux: &'static [u8; 27usize] = b"2530/1-Wire Octal 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_1_Wire_Quad_32x1_Mux: &'static [u8; 26usize] = b"2530/1-Wire Quad 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_2_Wire_4x16_Matrix: &'static [u8; 24usize] = b"2530/2-Wire 4x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2530_2_Wire_Dual_32x1_Mux: &'static [u8; 26usize] = b"2530/2-Wire Dual 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_2_Wire_Quad_16x1_Mux: &'static [u8; 26usize] = b"2530/2-Wire Quad 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_4_Wire_Dual_16x1_Mux: &'static [u8; 26usize] = b"2530/4-Wire Dual 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2530_Independent: &'static [u8; 17usize] = b"2530/Independent\0"; pub const DAQmx_Val_Switch_Topology_2531_1_Wire_4x128_Matrix: &'static [u8; 25usize] = b"2531/1-Wire 4x128 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2531_1_Wire_8x64_Matrix: &'static [u8; 24usize] = b"2531/1-Wire 8x64 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2531_1_Wire_Dual_4x64_Matrix: &'static [u8; 29usize] = b"2531/1-Wire Dual 4x64 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2531_1_Wire_Dual_8x32_Matrix: &'static [u8; 29usize] = b"2531/1-Wire Dual 8x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_1_Wire_16x32_Matrix: &'static [u8; 25usize] = b"2532/1-Wire 16x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_1_Wire_4x128_Matrix: &'static [u8; 25usize] = b"2532/1-Wire 4x128 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_1_Wire_8x64_Matrix: &'static [u8; 24usize] = b"2532/1-Wire 8x64 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_1_Wire_Dual_16x16_Matrix: &'static [u8; 30usize] = b"2532/1-Wire Dual 16x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_1_Wire_Dual_4x64_Matrix: &'static [u8; 29usize] = b"2532/1-Wire Dual 4x64 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_1_Wire_Dual_8x32_Matrix: &'static [u8; 29usize] = b"2532/1-Wire Dual 8x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_1_Wire_Quad_4x32_Matrix: &'static [u8; 29usize] = b"2532/1-Wire Quad 4x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_1_Wire_Sixteen_2x16_Matrix: &'static [u8; 32usize] = b"2532/1-Wire Sixteen 2x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_2_Wire_16x16_Matrix: &'static [u8; 25usize] = b"2532/2-Wire 16x16 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_2_Wire_4x64_Matrix: &'static [u8; 24usize] = b"2532/2-Wire 4x64 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_2_Wire_8x32_Matrix: &'static [u8; 24usize] = b"2532/2-Wire 8x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2532_2_Wire_Dual_4x32_Matrix: &'static [u8; 29usize] = b"2532/2-Wire Dual 4x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2533_1_Wire_4x64_Matrix: &'static [u8; 24usize] = b"2533/1-Wire 4x64 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2534_1_Wire_8x32_Matrix: &'static [u8; 24usize] = b"2534/1-Wire 8x32 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2535_1_Wire_4x136_Matrix: &'static [u8; 25usize] = b"2535/1-Wire 4x136 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2536_1_Wire_8x68_Matrix: &'static [u8; 24usize] = b"2536/1-Wire 8x68 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2540_1_Wire_8x9_Matrix: &'static [u8; 23usize] = b"2540/1-Wire 8x9 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2541_1_Wire_8x12_Matrix: &'static [u8; 24usize] = b"2541/1-Wire 8x12 Matrix\0"; pub const DAQmx_Val_Switch_Topology_2542_Quad_2x1_Terminated_Mux: &'static [u8; 29usize] = b"2542/Quad 2x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2543_Dual_4x1_Terminated_Mux: &'static [u8; 29usize] = b"2543/Dual 4x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2544_8x1_Terminated_Mux: &'static [u8; 24usize] = b"2544/8x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2545_4x1_Terminated_Mux: &'static [u8; 24usize] = b"2545/4x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2546_Dual_4x1_Mux: &'static [u8; 18usize] = b"2546/Dual 4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2547_8x1_Mux: &'static [u8; 13usize] = b"2547/8x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2548_4_SPDT: &'static [u8; 12usize] = b"2548/4-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2549_Terminated_2_SPDT: &'static [u8; 23usize] = b"2549/Terminated 2-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2554_4x1_Mux: &'static [u8; 13usize] = b"2554/4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2555_4x1_Terminated_Mux: &'static [u8; 24usize] = b"2555/4x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2556_Dual_4x1_Mux: &'static [u8; 18usize] = b"2556/Dual 4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2557_8x1_Mux: &'static [u8; 13usize] = b"2557/8x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2558_4_SPDT: &'static [u8; 12usize] = b"2558/4-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2559_Terminated_2_SPDT: &'static [u8; 23usize] = b"2559/Terminated 2-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2564_16_SPST: &'static [u8; 13usize] = b"2564/16-SPST\0"; pub const DAQmx_Val_Switch_Topology_2564_8_DPST: &'static [u8; 12usize] = b"2564/8-DPST\0"; pub const DAQmx_Val_Switch_Topology_2565_16_SPST: &'static [u8; 13usize] = b"2565/16-SPST\0"; pub const DAQmx_Val_Switch_Topology_2566_16_SPDT: &'static [u8; 13usize] = b"2566/16-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2566_8_DPDT: &'static [u8; 12usize] = b"2566/8-DPDT\0"; pub const DAQmx_Val_Switch_Topology_2567_Independent: &'static [u8; 17usize] = b"2567/Independent\0"; pub const DAQmx_Val_Switch_Topology_2568_31_SPST: &'static [u8; 13usize] = b"2568/31-SPST\0"; pub const DAQmx_Val_Switch_Topology_2568_15_DPST: &'static [u8; 13usize] = b"2568/15-DPST\0"; pub const DAQmx_Val_Switch_Topology_2569_100_SPST: &'static [u8; 14usize] = b"2569/100-SPST\0"; pub const DAQmx_Val_Switch_Topology_2569_50_DPST: &'static [u8; 13usize] = b"2569/50-DPST\0"; pub const DAQmx_Val_Switch_Topology_2570_40_SPDT: &'static [u8; 13usize] = b"2570/40-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2570_20_DPDT: &'static [u8; 13usize] = b"2570/20-DPDT\0"; pub const DAQmx_Val_Switch_Topology_2571_66_SPDT: &'static [u8; 13usize] = b"2571/66-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2575_1_Wire_196x1_Mux: &'static [u8; 22usize] = b"2575/1-Wire 196x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2575_2_Wire_98x1_Mux: &'static [u8; 21usize] = b"2575/2-Wire 98x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2575_2_Wire_95x1_Mux: &'static [u8; 21usize] = b"2575/2-Wire 95x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2576_2_Wire_64x1_Mux: &'static [u8; 21usize] = b"2576/2-Wire 64x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2576_2_Wire_Dual_32x1_Mux: &'static [u8; 26usize] = b"2576/2-Wire Dual 32x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2576_2_Wire_Octal_8x1_Mux: &'static [u8; 26usize] = b"2576/2-Wire Octal 8x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2576_2_Wire_Quad_16x1_Mux: &'static [u8; 26usize] = b"2576/2-Wire Quad 16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2576_2_Wire_Sixteen_4x1_Mux: &'static [u8; 28usize] = b"2576/2-Wire Sixteen 4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2576_Independent: &'static [u8; 17usize] = b"2576/Independent\0"; pub const DAQmx_Val_Switch_Topology_2584_1_Wire_12x1_Mux: &'static [u8; 21usize] = b"2584/1-Wire 12x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2584_1_Wire_Dual_6x1_Mux: &'static [u8; 25usize] = b"2584/1-Wire Dual 6x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2584_2_Wire_6x1_Mux: &'static [u8; 20usize] = b"2584/2-Wire 6x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2584_Independent: &'static [u8; 17usize] = b"2584/Independent\0"; pub const DAQmx_Val_Switch_Topology_2585_1_Wire_10x1_Mux: &'static [u8; 21usize] = b"2585/1-Wire 10x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2586_10_SPST: &'static [u8; 13usize] = b"2586/10-SPST\0"; pub const DAQmx_Val_Switch_Topology_2586_5_DPST: &'static [u8; 12usize] = b"2586/5-DPST\0"; pub const DAQmx_Val_Switch_Topology_2590_4x1_Mux: &'static [u8; 13usize] = b"2590/4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2591_4x1_Mux: &'static [u8; 13usize] = b"2591/4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2593_16x1_Mux: &'static [u8; 14usize] = b"2593/16x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2593_Dual_8x1_Mux: &'static [u8; 18usize] = b"2593/Dual 8x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2593_8x1_Terminated_Mux: &'static [u8; 24usize] = b"2593/8x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2593_Dual_4x1_Terminated_Mux: &'static [u8; 29usize] = b"2593/Dual 4x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2593_Independent: &'static [u8; 17usize] = b"2593/Independent\0"; pub const DAQmx_Val_Switch_Topology_2594_4x1_Mux: &'static [u8; 13usize] = b"2594/4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2595_4x1_Mux: &'static [u8; 13usize] = b"2595/4x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2596_Dual_6x1_Mux: &'static [u8; 18usize] = b"2596/Dual 6x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2597_6x1_Terminated_Mux: &'static [u8; 24usize] = b"2597/6x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2598_Dual_Transfer: &'static [u8; 19usize] = b"2598/Dual Transfer\0"; pub const DAQmx_Val_Switch_Topology_2599_2_SPDT: &'static [u8; 12usize] = b"2599/2-SPDT\0"; pub const DAQmx_Val_Switch_Topology_2720_Independent: &'static [u8; 17usize] = b"2720/Independent\0"; pub const DAQmx_Val_Switch_Topology_2722_Independent: &'static [u8; 17usize] = b"2722/Independent\0"; pub const DAQmx_Val_Switch_Topology_2725_Independent: &'static [u8; 17usize] = b"2725/Independent\0"; pub const DAQmx_Val_Switch_Topology_2727_Independent: &'static [u8; 17usize] = b"2727/Independent\0"; pub const DAQmx_Val_Switch_Topology_2790_Independent: &'static [u8; 17usize] = b"2790/Independent\0"; pub const DAQmx_Val_Switch_Topology_2796_Dual_6x1_Mux: &'static [u8; 18usize] = b"2796/Dual 6x1 Mux\0"; pub const DAQmx_Val_Switch_Topology_2797_6x1_Terminated_Mux: &'static [u8; 24usize] = b"2797/6x1 Terminated Mux\0"; pub const DAQmx_Val_Switch_Topology_2798_Dual_Transfer: &'static [u8; 19usize] = b"2798/Dual Transfer\0"; pub const DAQmx_Val_Switch_Topology_2799_2_SPDT: &'static [u8; 12usize] = b"2799/2-SPDT\0"; pub const DAQmxSuccess: u32 = 0; pub const DAQmxErrorTaskAlreadyRegisteredATimingSource: i32 = -209870; pub const DAQmxErrorFilterNotSupportedOnHWRev: i32 = -209869; pub const DAQmxErrorSensorPowerSupplyVoltageLevel: i32 = -209868; pub const DAQmxErrorSensorPowerSupply: i32 = -209867; pub const DAQmxErrorInvalidScanlist: i32 = -209866; pub const DAQmxErrorTimeResourceCannotBeRouted: i32 = -209865; pub const DAQmxErrorInvalidResetDelayRequested: i32 = -209864; pub const DAQmxErrorExceededTotalTimetriggersAvailable: i32 = -209863; pub const DAQmxErrorExceededTotalTimestampsAvailable: i32 = -209862; pub const DAQmxErrorNoSynchronizationProtocolRunning: i32 = -209861; pub const DAQmxErrorConflictingCoherencyRequirements: i32 = -209860; pub const DAQmxErrorNoSharedTimescale: i32 = -209859; pub const DAQmxErrorInvalidFieldDAQBankName: i32 = -209858; pub const DAQmxErrorDeviceDoesNotSupportHWTSP: i32 = -209857; pub const DAQmxErrorBankTypeDoesNotMatchBankTypeInDestination: i32 = -209856; pub const DAQmxErrorInvalidFieldDAQBankNumberSpecd: i32 = -209855; pub const DAQmxErrorUnsupportedSimulatedBankForSimulatedFieldDAQ: i32 = -209854; pub const DAQmxErrorFieldDAQBankSimMustMatchFieldDAQSim: i32 = -209853; pub const DAQmxErrorDevNoLongerSupportedWithinDAQmxAPI: i32 = -209852; pub const DAQmxErrorTimingEngineDoesNotSupportOnBoardMemory: i32 = -209851; pub const DAQmxErrorDuplicateTaskCrossProject: i32 = -209850; pub const DAQmxErrorTimeStartTriggerBeforeArmStartTrigger: i32 = -209849; pub const DAQmxErrorTimeTriggerCannotBeSet: i32 = -209848; pub const DAQmxErrorInvalidTriggerWindowValue: i32 = -209847; pub const DAQmxErrorCannotQueryPropertyBeforeOrDuringAcquisition: i32 = -209846; pub const DAQmxErrorSampleClockTimebaseNotSupported: i32 = -209845; pub const DAQmxErrorTimestampNotYetReceived: i32 = -209844; pub const DAQmxErrorTimeTriggerNotSupported: i32 = -209843; pub const DAQmxErrorTimestampNotEnabled: i32 = -209842; pub const DAQmxErrorTimeTriggersInconsistent: i32 = -209841; pub const DAQmxErrorTriggerConfiguredIsInThePast: i32 = -209840; pub const DAQmxErrorTriggerConfiguredIsTooFarFromCurrentTime: i32 = -209839; pub const DAQmxErrorSynchronizationLockLost: i32 = -209838; pub const DAQmxErrorInconsistentTimescales: i32 = -209837; pub const DAQmxErrorCannotSynchronizeDevices: i32 = -209836; pub const DAQmxErrorAssociatedChansHaveAttributeConflictWithMultipleMaxMinRanges: i32 = -209835; pub const DAQmxErrorSampleRateNumChansOrAttributeValues: i32 = -209834; pub const DAQmxErrorWaitForValidTimestampNotSupported: i32 = -209833; pub const DAQmxErrorTrigWinTimeoutExpired: i32 = -209832; pub const DAQmxErrorInvalidTriggerCfgForDevice: i32 = -209831; pub const DAQmxErrorInvalidDataTransferMechanismForDevice: i32 = -209830; pub const DAQmxErrorInputFIFOOverflow3: i32 = -209829; pub const DAQmxErrorTooManyDevicesForAnalogMultiEdgeTrigCDAQ: i32 = -209828; pub const DAQmxErrorTooManyTriggersTypesSpecifiedInTask: i32 = -209827; pub const DAQmxErrorMismatchedMultiTriggerConfigValues: i32 = -209826; pub const DAQmxErrorInconsistentAODACRangeAcrossTasks: i32 = -209825; pub const DAQmxErrorInconsistentDTToWrite: i32 = -209824; pub const DAQmxErrorFunctionObsolete: i32 = -209823; pub const DAQmxErrorNegativeDurationNotSupported: i32 = -209822; pub const DAQmxErrorDurationTooSmall: i32 = -209821; pub const DAQmxErrorDurationTooLong: i32 = -209820; pub const DAQmxErrorDurationBasedNotSupportedForSpecifiedTimingMode: i32 = -209819; pub const DAQmxErrorInvalidLEDState: i32 = -209818; pub const DAQmxErrorWatchdogStatesNotUniform: i32 = -209817; pub const DAQmxErrorSelfTestFailedPowerSupplyOutOfTolerance: i32 = -209816; pub const DAQmxErrorHWTSPMultiSampleWrite: i32 = -209815; pub const DAQmxErrorOnboardRegenExceedsChannelLimit: i32 = -209814; pub const DAQmxErrorWatchdogChannelExpirationStateNotSpecified: i32 = -209813; pub const DAQmxErrorInvalidShuntSourceForCalibration: i32 = -209812; pub const DAQmxErrorInvalidShuntSelectForCalibration: i32 = -209811; pub const DAQmxErrorInvalidShuntCalibrationConfiguration: i32 = -209810; pub const DAQmxErrorBufferedOperationsNotSupportedOnChannelStandalone: i32 = -209809; pub const DAQmxErrorFeatureNotAvailableOnAccessory: i32 = -209808; pub const DAQmxErrorInconsistentThreshVoltageAcrossTerminals: i32 = -209807; pub const DAQmxErrorDAQmxIsNotInstalledOnTarget: i32 = -209806; pub const DAQmxErrorCOCannotKeepUpInHWTimedSinglePoint: i32 = -209805; pub const DAQmxErrorWaitForNextSampClkDetected3OrMoreSampClks: i32 = -209803; pub const DAQmxErrorWaitForNextSampClkDetectedMissedSampClk: i32 = -209802; pub const DAQmxErrorWriteNotCompleteBeforeSampClk: i32 = -209801; pub const DAQmxErrorReadNotCompleteBeforeSampClk: i32 = -209800; pub const DAQmxErrorInconsistentDigitalFilteringAcrossTerminals: i32 = -201510; pub const DAQmxErrorInconsistentPullUpCfgAcrossTerminals: i32 = -201509; pub const DAQmxErrorInconsistentTermCfgAcrossTerminals: i32 = -201508; pub const DAQmxErrorVCXODCMBecameUnlocked: i32 = -201507; pub const DAQmxErrorPLLDACUpdateFailed: i32 = -201506; pub const DAQmxErrorNoCabledDevice: i32 = -201505; pub const DAQmxErrorLostRefClk: i32 = -201504; pub const DAQmxErrorCantUseAITimingEngineWithCounters: i32 = -201503; pub const DAQmxErrorDACOffsetValNotSet: i32 = -201502; pub const DAQmxErrorCalAdjustRefValOutOfRange: i32 = -201501; pub const DAQmxErrorChansForCalAdjustMustPerformSetContext: i32 = -201500; pub const DAQmxErrorGetCalDataInvalidForCalMode: i32 = -201499; pub const DAQmxErrorNoIEPEWithACNotAllowed: i32 = -201498; pub const DAQmxErrorSetupCalNeededBeforeGetCalDataPoints: i32 = -201497; pub const DAQmxErrorVoltageNotCalibrated: i32 = -201496; pub const DAQmxErrorMissingRangeForCalibration: i32 = -201495; pub const DAQmxErrorMultipleChansNotSupportedDuringCalAdjust: i32 = -201494; pub const DAQmxErrorShuntCalFailedOutOfRange: i32 = -201493; pub const DAQmxErrorOperationNotSupportedOnSimulatedDevice: i32 = -201492; pub const DAQmxErrorFirmwareVersionSameAsInstalledVersion: i32 = -201491; pub const DAQmxErrorFirmwareVersionOlderThanInstalledVersion: i32 = -201490; pub const DAQmxErrorFirmwareUpdateInvalidState: i32 = -201489; pub const DAQmxErrorFirmwareUpdateInvalidID: i32 = -201488; pub const DAQmxErrorFirmwareUpdateAutomaticManagementEnabled: i32 = -201487; pub const DAQmxErrorSetupCalibrationNotCalled: i32 = -201486; pub const DAQmxErrorCalMeasuredDataSizeVsActualDataSizeMismatch: i32 = -201485; pub const DAQmxErrorCDAQMissingDSAMasterForChanExpansion: i32 = -201484; pub const DAQmxErrorCDAQMasterNotFoundForChanExpansion: i32 = -201483; pub const DAQmxErrorAllChansShouldBeProvidedForCalibration: i32 = -201482; pub const DAQmxErrorMustSpecifyExpirationStateForAllLinesInRange: i32 = -201481; pub const DAQmxErrorOpenSessionExists: i32 = -201480; pub const DAQmxErrorCannotQueryTerminalForSWArmStart: i32 = -201479; pub const DAQmxErrorChassisWatchdogTimerExpired: i32 = -201478; pub const DAQmxErrorCantReserveWatchdogTaskWhileOtherTasksReserved: i32 = -201477; pub const DAQmxErrorCantReserveTaskWhileWatchdogTaskReserving: i32 = -201476; pub const DAQmxErrorAuxPowerSourceRequired: i32 = -201475; pub const DAQmxErrorDeviceNotSupportedOnLocalSystem: i32 = -201474; pub const DAQmxErrorOneTimestampChannelRequiredForCombinedNavigationRead: i32 = -201472; pub const DAQmxErrorMultDevsMultPhysChans: i32 = -201471; pub const DAQmxErrorInvalidCalAdjustmentPointValues: i32 = -201470; pub const DAQmxErrorDifferentDigitizerFromCommunicator: i32 = -201469; pub const DAQmxErrorCDAQSyncMasterClockNotPresent: i32 = -201468; pub const DAQmxErrorAssociatedChansHaveConflictingProps: i32 = -201467; pub const DAQmxErrorAutoConfigBetweenMultipleDeviceStatesInvalid: i32 = -201466; pub const DAQmxErrorAutoConfigOfOfflineDevicesInvalid: i32 = -201465; pub const DAQmxErrorExternalFIFOFault: i32 = -201464; pub const DAQmxErrorConnectionsNotReciprocal: i32 = -201463; pub const DAQmxErrorInvalidOutputToInputCDAQSyncConnection: i32 = -201462; pub const DAQmxErrorReferenceClockNotPresent: i32 = -201461; pub const DAQmxErrorBlankStringExpansionFoundNoSupportedCDAQSyncConnectionDevices: i32 = -201460; pub const DAQmxErrorNoDevicesSupportCDAQSyncConnections: i32 = -201459; pub const DAQmxErrorInvalidCDAQSyncTimeoutValue: i32 = -201458; pub const DAQmxErrorCDAQSyncConnectionToSamePort: i32 = -201457; pub const DAQmxErrorDevsWithoutCommonSyncConnectionStrategy: i32 = -201456; pub const DAQmxErrorNoCDAQSyncBetweenPhysAndSimulatedDevs: i32 = -201455; pub const DAQmxErrorUnableToContainCards: i32 = -201454; pub const DAQmxErrorFindDisconnectedBetweenPhysAndSimDeviceStatesInvalid: i32 = -201453; pub const DAQmxErrorOperationAborted: i32 = -201452; pub const DAQmxErrorTwoPortsRequired: i32 = -201451; pub const DAQmxErrorDeviceDoesNotSupportCDAQSyncConnections: i32 = -201450; pub const DAQmxErrorInvalidcDAQSyncPortConnectionFormat: i32 = -201449; pub const DAQmxErrorRosetteMeasurementsNotSpecified: i32 = -201448; pub const DAQmxErrorInvalidNumOfPhysChansForDeltaRosette: i32 = -201447; pub const DAQmxErrorInvalidNumOfPhysChansForTeeRosette: i32 = -201446; pub const DAQmxErrorRosetteStrainChanNamesNeeded: i32 = -201445; pub const DAQmxErrorMultideviceWithOnDemandTiming: i32 = -201444; pub const DAQmxErrorFREQOUTCannotProduceDesiredFrequency3: i32 = -201443; pub const DAQmxErrorTwoEdgeSeparationSameTerminalSameEdge: i32 = -201442; pub const DAQmxErrorDontMixSyncPulseAndSampClkTimebaseOn449x: i32 = -201441; pub const DAQmxErrorNeitherRefClkNorSampClkTimebaseConfiguredForDSASync: i32 = -201440; pub const DAQmxErrorRetriggeringFiniteCONotAllowed: i32 = -201439; pub const DAQmxErrorDeviceRebootedFromWDTTimeout: i32 = -201438; pub const DAQmxErrorTimeoutValueExceedsMaximum: i32 = -201437; pub const DAQmxErrorSharingDifferentWireModes: i32 = -201436; pub const DAQmxErrorCantPrimeWithEmptyBuffer: i32 = -201435; pub const DAQmxErrorConfigFailedBecauseWatchdogExpired: i32 = -201434; pub const DAQmxErrorWriteFailedBecauseWatchdogChangedLineDirection: i32 = -201433; pub const DAQmxErrorMultipleSubsytemCalibration: i32 = -201432; pub const DAQmxErrorIncorrectChannelForOffsetAdjustment: i32 = -201431; pub const DAQmxErrorInvalidNumRefVoltagesToWrite: i32 = -201430; pub const DAQmxErrorStartTrigDelayWithDSAModule: i32 = -201429; pub const DAQmxErrorMoreThanOneSyncPulseDetected: i32 = -201428; pub const DAQmxErrorDevNotSupportedWithinDAQmxAPI: i32 = -201427; pub const DAQmxErrorDevsWithoutSyncStrategies: i32 = -201426; pub const DAQmxErrorDevsWithoutCommonSyncStrategy: i32 = -201425; pub const DAQmxErrorSyncStrategiesCannotSync: i32 = -201424; pub const DAQmxErrorChassisCommunicationInterrupted: i32 = -201423; pub const DAQmxErrorUnknownCardPowerProfileInCarrier: i32 = -201422; pub const DAQmxErrorAttrNotSupportedOnAccessory: i32 = -201421; pub const DAQmxErrorNetworkDeviceReservedByAnotherHost: i32 = -201420; pub const DAQmxErrorIncorrectFirmwareFileUploaded: i32 = -201419; pub const DAQmxErrorInvalidFirmwareFileUploaded: i32 = -201418; pub const DAQmxErrorInTimerTimeoutOnArm: i32 = -201417; pub const DAQmxErrorCantExceedSlotRelayDriveLimit: i32 = -201416; pub const DAQmxErrorModuleUnsupportedFor9163: i32 = -201415; pub const DAQmxErrorConnectionsNotSupported: i32 = -201414; pub const DAQmxErrorAccessoryNotPresent: i32 = -201413; pub const DAQmxErrorSpecifiedAccessoryChannelsNotPresentOnDevice: i32 = -201412; pub const DAQmxErrorConnectionsNotSupportedOnAccessory: i32 = -201411; pub const DAQmxErrorRateTooFastForHWTSP: i32 = -201410; pub const DAQmxErrorDelayFromSampleClockOutOfRangeForHWTSP: i32 = -201409; pub const DAQmxErrorAveragingWhenNotInternalHWTSP: i32 = -201408; pub const DAQmxErrorAttributeNotSupportedUnlessHWTSP: i32 = -201407; pub const DAQmxErrorFiveVoltDetectFailed: i32 = -201406; pub const DAQmxErrorAnalogBusStateInconsistent: i32 = -201405; pub const DAQmxErrorCardDetectedDoesNotMatchExpectedCard: i32 = -201404; pub const DAQmxErrorLoggingStartNewFileNotCalled: i32 = -201403; pub const DAQmxErrorLoggingSampsPerFileNotDivisible: i32 = -201402; pub const DAQmxErrorRetrievingNetworkDeviceProperties: i32 = -201401; pub const DAQmxErrorFilePreallocationFailed: i32 = -201400; pub const DAQmxErrorModuleMismatchInSameTimedTask: i32 = -201399; pub const DAQmxErrorInvalidAttributeValuePossiblyDueToOtherAttributeValues: i32 = -201398; pub const DAQmxErrorChangeDetectionStoppedToPreventDeviceHang: i32 = -201397; pub const DAQmxErrorFilterDelayRemovalNotPosssibleWithAnalogTrigger: i32 = -201396; pub const DAQmxErrorNonbufferedOrNoChannels: i32 = -201395; pub const DAQmxErrorTristateLogicLevelNotSpecdForEntirePort: i32 = -201394; pub const DAQmxErrorTristateLogicLevelNotSupportedOnDigOutChan: i32 = -201393; pub const DAQmxErrorTristateLogicLevelNotSupported: i32 = -201392; pub const DAQmxErrorIncompleteGainAndCouplingCalAdjustment: i32 = -201391; pub const DAQmxErrorNetworkStatusConnectionLost: i32 = -201390; pub const DAQmxErrorModuleChangeDuringConnectionLoss: i32 = -201389; pub const DAQmxErrorNetworkDeviceNotReservedByHost: i32 = -201388; pub const DAQmxErrorDuplicateCalibrationAdjustmentInput: i32 = -201387; pub const DAQmxErrorSelfCalFailedContactTechSupport: i32 = -201386; pub const DAQmxErrorSelfCalFailedToConverge: i32 = -201385; pub const DAQmxErrorUnsupportedSimulatedModuleForSimulatedChassis: i32 = -201384; pub const DAQmxErrorLoggingWriteSizeTooBig: i32 = -201383; pub const DAQmxErrorLoggingWriteSizeNotDivisible: i32 = -201382; pub const DAQmxErrorMyDAQPowerRailFault: i32 = -201381; pub const DAQmxErrorDeviceDoesNotSupportThisOperation: i32 = -201380; pub const DAQmxErrorNetworkDevicesNotSupportedOnThisPlatform: i32 = -201379; pub const DAQmxErrorUnknownFirmwareVersion: i32 = -201378; pub const DAQmxErrorFirmwareIsUpdating: i32 = -201377; pub const DAQmxErrorAccessoryEEPROMIsCorrupt: i32 = -201376; pub const DAQmxErrorThrmcplLeadOffsetNullingCalNotSupported: i32 = -201375; pub const DAQmxErrorSelfCalFailedTryExtCal: i32 = -201374; pub const DAQmxErrorOutputP2PNotSupportedWithMultithreadedScripts: i32 = -201373; pub const DAQmxErrorThrmcplCalibrationChannelsOpen: i32 = -201372; pub const DAQmxErrorMDNSServiceInstanceAlreadyInUse: i32 = -201371; pub const DAQmxErrorIPAddressAlreadyInUse: i32 = -201370; pub const DAQmxErrorHostnameAlreadyInUse: i32 = -201369; pub const DAQmxErrorInvalidNumberOfCalAdjustmentPoints: i32 = -201368; pub const DAQmxErrorFilterOrDigitalSyncInternalSignal: i32 = -201367; pub const DAQmxErrorBadDDSSource: i32 = -201366; pub const DAQmxErrorOnboardRegenWithMoreThan16Channels: i32 = -201365; pub const DAQmxErrorTriggerTooFast: i32 = -201364; pub const DAQmxErrorMinMaxOutsideTableRange: i32 = -201363; pub const DAQmxErrorChannelExpansionWithInvalidAnalogTriggerDevice: i32 = -201362; pub const DAQmxErrorSyncPulseSrcInvalidForTask: i32 = -201361; pub const DAQmxErrorInvalidCarrierSlotNumberSpecd: i32 = -201360; pub const DAQmxErrorCardsMustBeInSameCarrier: i32 = -201359; pub const DAQmxErrorCardDevCarrierSimMustMatch: i32 = -201358; pub const DAQmxErrorDevMustHaveAtLeastOneCard: i32 = -201357; pub const DAQmxErrorCardTopologyError: i32 = -201356; pub const DAQmxErrorExceededCarrierPowerLimit: i32 = -201355; pub const DAQmxErrorCardsIncompatible: i32 = -201354; pub const DAQmxErrorAnalogBusNotValid: i32 = -201353; pub const DAQmxErrorReservationConflict: i32 = -201352; pub const DAQmxErrorMemMappedOnDemandNotSupported: i32 = -201351; pub const DAQmxErrorSlaveWithNoStartTriggerConfigured: i32 = -201350; pub const DAQmxErrorChannelExpansionWithDifferentTriggerDevices: i32 = -201349; pub const DAQmxErrorCounterSyncAndRetriggered: i32 = -201348; pub const DAQmxErrorNoExternalSyncPulseDetected: i32 = -201347; pub const DAQmxErrorSlaveAndNoExternalSyncPulse: i32 = -201346; pub const DAQmxErrorCustomTimingRequiredForAttribute: i32 = -201345; pub const DAQmxErrorCustomTimingModeNotSet: i32 = -201344; pub const DAQmxErrorAccessoryPowerTripped: i32 = -201343; pub const DAQmxErrorUnsupportedAccessory: i32 = -201342; pub const DAQmxErrorInvalidAccessoryChange: i32 = -201341; pub const DAQmxErrorFirmwareRequiresUpgrade: i32 = -201340; pub const DAQmxErrorFastExternalTimebaseNotSupportedForDevice: i32 = -201339; pub const DAQmxErrorInvalidShuntLocationForCalibration: i32 = -201338; pub const DAQmxErrorDeviceNameTooLong: i32 = -201337; pub const DAQmxErrorBridgeScalesUnsupported: i32 = -201336; pub const DAQmxErrorMismatchedElecPhysValues: i32 = -201335; pub const DAQmxErrorLinearRequiresUniquePoints: i32 = -201334; pub const DAQmxErrorMissingRequiredScalingParameter: i32 = -201333; pub const DAQmxErrorLoggingNotSupportOnOutputTasks: i32 = -201332; pub const DAQmxErrorMemoryMappedHardwareTimedNonBufferedUnsupported: i32 = -201331; pub const DAQmxErrorCannotUpdatePulseTrainWithAutoIncrementEnabled: i32 = -201330; pub const DAQmxErrorHWTimedSinglePointAndDataXferNotDMA: i32 = -201329; pub const DAQmxErrorSCCSecondStageEmpty: i32 = -201328; pub const DAQmxErrorSCCInvalidDualStageCombo: i32 = -201327; pub const DAQmxErrorSCCInvalidSecondStage: i32 = -201326; pub const DAQmxErrorSCCInvalidFirstStage: i32 = -201325; pub const DAQmxErrorCounterMultipleSampleClockedChannels: i32 = -201324; pub const DAQmxError2CounterMeasurementModeAndSampleClocked: i32 = -201323; pub const DAQmxErrorCantHaveBothMemMappedAndNonMemMappedTasks: i32 = -201322; pub const DAQmxErrorMemMappedDataReadByAnotherProcess: i32 = -201321; pub const DAQmxErrorRetriggeringInvalidForGivenSettings: i32 = -201320; pub const DAQmxErrorAIOverrun: i32 = -201319; pub const DAQmxErrorCOOverrun: i32 = -201318; pub const DAQmxErrorCounterMultipleBufferedChannels: i32 = -201317; pub const DAQmxErrorInvalidTimebaseForCOHWTSP: i32 = -201316; pub const DAQmxErrorWriteBeforeEvent: i32 = -201315; pub const DAQmxErrorCIOverrun: i32 = -201314; pub const DAQmxErrorCounterNonResponsiveAndReset: i32 = -201313; pub const DAQmxErrorMeasTypeOrChannelNotSupportedForLogging: i32 = -201312; pub const DAQmxErrorFileAlreadyOpenedForWrite: i32 = -201311; pub const DAQmxErrorTdmsNotFound: i32 = -201310; pub const DAQmxErrorGenericFileIO: i32 = -201309; pub const DAQmxErrorFiniteSTCCounterNotSupportedForLogging: i32 = -201308; pub const DAQmxErrorMeasurementTypeNotSupportedForLogging: i32 = -201307; pub const DAQmxErrorFileAlreadyOpened: i32 = -201306; pub const DAQmxErrorDiskFull: i32 = -201305; pub const DAQmxErrorFilePathInvalid: i32 = -201304; pub const DAQmxErrorFileVersionMismatch: i32 = -201303; pub const DAQmxErrorFileWriteProtected: i32 = -201302; pub const DAQmxErrorReadNotSupportedForLoggingMode: i32 = -201301; pub const DAQmxErrorAttributeNotSupportedWhenLogging: i32 = -201300; pub const DAQmxErrorLoggingModeNotSupportedNonBuffered: i32 = -201299; pub const DAQmxErrorPropertyNotSupportedWithConflictingProperty: i32 = -201298; pub const DAQmxErrorParallelSSHOnConnector1: i32 = -201297; pub const DAQmxErrorCOOnlyImplicitSampleTimingTypeSupported: i32 = -201296; pub const DAQmxErrorCalibrationFailedAOOutOfRange: i32 = -201295; pub const DAQmxErrorCalibrationFailedAIOutOfRange: i32 = -201294; pub const DAQmxErrorCalPWMLinearityFailed: i32 = -201293; pub const DAQmxErrorOverrunUnderflowConfigurationCombo: i32 = -201292; pub const DAQmxErrorCannotWriteToFiniteCOTask: i32 = -201291; pub const DAQmxErrorNetworkDAQInvalidWEPKeyLength: i32 = -201290; pub const DAQmxErrorCalInputsShortedNotSupported: i32 = -201289; pub const DAQmxErrorCannotSetPropertyWhenTaskIsReserved: i32 = -201288; pub const DAQmxErrorMinus12VFuseBlown: i32 = -201287; pub const DAQmxErrorPlus12VFuseBlown: i32 = -201286; pub const DAQmxErrorPlus5VFuseBlown: i32 = -201285; pub const DAQmxErrorPlus3VFuseBlown: i32 = -201284; pub const DAQmxErrorDeviceSerialPortError: i32 = -201283; pub const DAQmxErrorPowerUpStateMachineNotDone: i32 = -201282; pub const DAQmxErrorTooManyTriggersSpecifiedInTask: i32 = -201281; pub const DAQmxErrorVerticalOffsetNotSupportedOnDevice: i32 = -201280; pub const DAQmxErrorInvalidCouplingForMeasurementType: i32 = -201279; pub const DAQmxErrorDigitalLineUpdateTooFastForDevice: i32 = -201278; pub const DAQmxErrorCertificateIsTooBigToTransfer: i32 = -201277; pub const DAQmxErrorOnlyPEMOrDERCertiticatesAccepted: i32 = -201276; pub const DAQmxErrorCalCouplingNotSupported: i32 = -201275; pub const DAQmxErrorDeviceNotSupportedIn64Bit: i32 = -201274; pub const DAQmxErrorNetworkDeviceInUse: i32 = -201273; pub const DAQmxErrorInvalidIPv4AddressFormat: i32 = -201272; pub const DAQmxErrorNetworkProductTypeMismatch: i32 = -201271; pub const DAQmxErrorOnlyPEMCertificatesAccepted: i32 = -201270; pub const DAQmxErrorCalibrationRequiresPrototypingBoardEnabled: i32 = -201269; pub const DAQmxErrorAllCurrentLimitingResourcesAlreadyTaken: i32 = -201268; pub const DAQmxErrorUserDefInfoStringBadLength: i32 = -201267; pub const DAQmxErrorPropertyNotFound: i32 = -201266; pub const DAQmxErrorOverVoltageProtectionActivated: i32 = -201265; pub const DAQmxErrorScaledIQWaveformTooLarge: i32 = -201264; pub const DAQmxErrorFirmwareFailedToDownload: i32 = -201263; pub const DAQmxErrorPropertyNotSupportedForBusType: i32 = -201262; pub const DAQmxErrorChangeRateWhileRunningCouldNotBeCompleted: i32 = -201261; pub const DAQmxErrorCannotQueryManualControlAttribute: i32 = -201260; pub const DAQmxErrorInvalidNetworkConfiguration: i32 = -201259; pub const DAQmxErrorInvalidWirelessConfiguration: i32 = -201258; pub const DAQmxErrorInvalidWirelessCountryCode: i32 = -201257; pub const DAQmxErrorInvalidWirelessChannel: i32 = -201256; pub const DAQmxErrorNetworkEEPROMHasChanged: i32 = -201255; pub const DAQmxErrorNetworkSerialNumberMismatch: i32 = -201254; pub const DAQmxErrorNetworkStatusDown: i32 = -201253; pub const DAQmxErrorNetworkTargetUnreachable: i32 = -201252; pub const DAQmxErrorNetworkTargetNotFound: i32 = -201251; pub const DAQmxErrorNetworkStatusTimedOut: i32 = -201250; pub const DAQmxErrorInvalidWirelessSecuritySelection: i32 = -201249; pub const DAQmxErrorNetworkDeviceConfigurationLocked: i32 = -201248; pub const DAQmxErrorNetworkDAQDeviceNotSupported: i32 = -201247; pub const DAQmxErrorNetworkDAQCannotCreateEmptySleeve: i32 = -201246; pub const DAQmxErrorUserDefInfoStringTooLong: i32 = -201245; pub const DAQmxErrorModuleTypeDoesNotMatchModuleTypeInDestination: i32 = -201244; pub const DAQmxErrorInvalidTEDSInterfaceAddress: i32 = -201243; pub const DAQmxErrorDevDoesNotSupportSCXIComm: i32 = -201242; pub const DAQmxErrorSCXICommDevConnector0MustBeCabledToModule: i32 = -201241; pub const DAQmxErrorSCXIModuleDoesNotSupportDigitizationMode: i32 = -201240; pub const DAQmxErrorDevDoesNotSupportMultiplexedSCXIDigitizationMode: i32 = -201239; pub const DAQmxErrorDevOrDevPhysChanDoesNotSupportSCXIDigitization: i32 = -201238; pub const DAQmxErrorInvalidPhysChanName: i32 = -201237; pub const DAQmxErrorSCXIChassisCommModeInvalid: i32 = -201236; pub const DAQmxErrorRequiredDependencyNotFound: i32 = -201235; pub const DAQmxErrorInvalidStorage: i32 = -201234; pub const DAQmxErrorInvalidObject: i32 = -201233; pub const DAQmxErrorStorageAlteredPriorToSave: i32 = -201232; pub const DAQmxErrorTaskDoesNotReferenceLocalChannel: i32 = -201231; pub const DAQmxErrorReferencedDevSimMustMatchTarget: i32 = -201230; pub const DAQmxErrorProgrammedIOFailsBecauseOfWatchdogTimer: i32 = -201229; pub const DAQmxErrorWatchdogTimerFailsBecauseOfProgrammedIO: i32 = -201228; pub const DAQmxErrorCantUseThisTimingEngineWithAPort: i32 = -201227; pub const DAQmxErrorProgrammedIOConflict: i32 = -201226; pub const DAQmxErrorChangeDetectionIncompatibleWithProgrammedIO: i32 = -201225; pub const DAQmxErrorTristateNotEnoughLines: i32 = -201224; pub const DAQmxErrorTristateConflict: i32 = -201223; pub const DAQmxErrorGenerateOrFiniteWaitExpectedBeforeBreakBlock: i32 = -201222; pub const DAQmxErrorBreakBlockNotAllowedInLoop: i32 = -201221; pub const DAQmxErrorClearTriggerNotAllowedInBreakBlock: i32 = -201220; pub const DAQmxErrorNestingNotAllowedInBreakBlock: i32 = -201219; pub const DAQmxErrorIfElseBlockNotAllowedInBreakBlock: i32 = -201218; pub const DAQmxErrorRepeatUntilTriggerLoopNotAllowedInBreakBlock: i32 = -201217; pub const DAQmxErrorWaitUntilTriggerNotAllowedInBreakBlock: i32 = -201216; pub const DAQmxErrorMarkerPosInvalidInBreakBlock: i32 = -201215; pub const DAQmxErrorInvalidWaitDurationInBreakBlock: i32 = -201214; pub const DAQmxErrorInvalidSubsetLengthInBreakBlock: i32 = -201213; pub const DAQmxErrorInvalidWaveformLengthInBreakBlock: i32 = -201212; pub const DAQmxErrorInvalidWaitDurationBeforeBreakBlock: i32 = -201211; pub const DAQmxErrorInvalidSubsetLengthBeforeBreakBlock: i32 = -201210; pub const DAQmxErrorInvalidWaveformLengthBeforeBreakBlock: i32 = -201209; pub const DAQmxErrorSampleRateTooHighForADCTimingMode: i32 = -201208; pub const DAQmxErrorActiveDevNotSupportedWithMultiDevTask: i32 = -201207; pub const DAQmxErrorRealDevAndSimDevNotSupportedInSameTask: i32 = -201206; pub const DAQmxErrorRTSISimMustMatchDevSim: i32 = -201205; pub const DAQmxErrorBridgeShuntCaNotSupported: i32 = -201204; pub const DAQmxErrorStrainShuntCaNotSupported: i32 = -201203; pub const DAQmxErrorGainTooLargeForGainCalConst: i32 = -201202; pub const DAQmxErrorOffsetTooLargeForOffsetCalConst: i32 = -201201; pub const DAQmxErrorElvisPrototypingBoardRemoved: i32 = -201200; pub const DAQmxErrorElvis2PowerRailFault: i32 = -201199; pub const DAQmxErrorElvis2PhysicalChansFault: i32 = -201198; pub const DAQmxErrorElvis2PhysicalChansThermalEvent: i32 = -201197; pub const DAQmxErrorRXBitErrorRateLimitExceeded: i32 = -201196; pub const DAQmxErrorPHYBitErrorRateLimitExceeded: i32 = -201195; pub const DAQmxErrorTwoPartAttributeCalledOutOfOrder: i32 = -201194; pub const DAQmxErrorInvalidSCXIChassisAddress: i32 = -201193; pub const DAQmxErrorCouldNotConnectToRemoteMXS: i32 = -201192; pub const DAQmxErrorExcitationStateRequiredForAttributes: i32 = -201191; pub const DAQmxErrorDeviceNotUsableUntilUSBReplug: i32 = -201190; pub const DAQmxErrorInputFIFOOverflowDuringCalibrationOnFullSpeedUSB: i32 = -201189; pub const DAQmxErrorInputFIFOOverflowDuringCalibration: i32 = -201188; pub const DAQmxErrorCJCChanConflictsWithNonThermocoupleChan: i32 = -201187; pub const DAQmxErrorCommDeviceForPXIBackplaneNotInRightmostSlot: i32 = -201186; pub const DAQmxErrorCommDeviceForPXIBackplaneNotInSameChassis: i32 = -201185; pub const DAQmxErrorCommDeviceForPXIBackplaneNotPXI: i32 = -201184; pub const DAQmxErrorInvalidCalExcitFrequency: i32 = -201183; pub const DAQmxErrorInvalidCalExcitVoltage: i32 = -201182; pub const DAQmxErrorInvalidAIInputSrc: i32 = -201181; pub const DAQmxErrorInvalidCalInputRef: i32 = -201180; pub const DAQmxErrordBReferenceValueNotGreaterThanZero: i32 = -201179; pub const DAQmxErrorSampleClockRateIsTooFastForSampleClockTiming: i32 = -201178; pub const DAQmxErrorDeviceNotUsableUntilColdStart: i32 = -201177; pub const DAQmxErrorSampleClockRateIsTooFastForBurstTiming: i32 = -201176; pub const DAQmxErrorDevImportFailedAssociatedResourceIDsNotSupported: i32 = -201175; pub const DAQmxErrorSCXI1600ImportNotSupported: i32 = -201174; pub const DAQmxErrorPowerSupplyConfigurationFailed: i32 = -201173; pub const DAQmxErrorIEPEWithDCNotAllowed: i32 = -201172; pub const DAQmxErrorMinTempForThermocoupleTypeOutsideAccuracyForPolyScaling: i32 = -201171; pub const DAQmxErrorDevImportFailedNoDeviceToOverwriteAndSimulationNotSupported: i32 = -201170; pub const DAQmxErrorDevImportFailedDeviceNotSupportedOnDestination: i32 = -201169; pub const DAQmxErrorFirmwareIsTooOld: i32 = -201168; pub const DAQmxErrorFirmwareCouldntUpdate: i32 = -201167; pub const DAQmxErrorFirmwareIsCorrupt: i32 = -201166; pub const DAQmxErrorFirmwareTooNew: i32 = -201165; pub const DAQmxErrorSampClockCannotBeExportedFromExternalSampClockSrc: i32 = -201164; pub const DAQmxErrorPhysChanReservedForInputWhenDesiredForOutput: i32 = -201163; pub const DAQmxErrorPhysChanReservedForOutputWhenDesiredForInput: i32 = -201162; pub const DAQmxErrorSpecifiedCDAQSlotNotEmpty: i32 = -201161; pub const DAQmxErrorDeviceDoesNotSupportSimulation: i32 = -201160; pub const DAQmxErrorInvalidCDAQSlotNumberSpecd: i32 = -201159; pub const DAQmxErrorCSeriesModSimMustMatchCDAQChassisSim: i32 = -201158; pub const DAQmxErrorSCCCabledDevMustNotBeSimWhenSCCCarrierIsNotSim: i32 = -201157; pub const DAQmxErrorSCCModSimMustMatchSCCCarrierSim: i32 = -201156; pub const DAQmxErrorSCXIModuleDoesNotSupportSimulation: i32 = -201155; pub const DAQmxErrorSCXICableDevMustNotBeSimWhenModIsNotSim: i32 = -201154; pub const DAQmxErrorSCXIDigitizerSimMustNotBeSimWhenModIsNotSim: i32 = -201153; pub const DAQmxErrorSCXIModSimMustMatchSCXIChassisSim: i32 = -201152; pub const DAQmxErrorSimPXIDevReqSlotAndChassisSpecd: i32 = -201151; pub const DAQmxErrorSimDevConflictWithRealDev: i32 = -201150; pub const DAQmxErrorInsufficientDataForCalibration: i32 = -201149; pub const DAQmxErrorTriggerChannelMustBeEnabled: i32 = -201148; pub const DAQmxErrorCalibrationDataConflictCouldNotBeResolved: i32 = -201147; pub const DAQmxErrorSoftwareTooNewForSelfCalibrationData: i32 = -201146; pub const DAQmxErrorSoftwareTooNewForExtCalibrationData: i32 = -201145; pub const DAQmxErrorSelfCalibrationDataTooNewForSoftware: i32 = -201144; pub const DAQmxErrorExtCalibrationDataTooNewForSoftware: i32 = -201143; pub const DAQmxErrorSoftwareTooNewForEEPROM: i32 = -201142; pub const DAQmxErrorEEPROMTooNewForSoftware: i32 = -201141; pub const DAQmxErrorSoftwareTooNewForHardware: i32 = -201140; pub const DAQmxErrorHardwareTooNewForSoftware: i32 = -201139; pub const DAQmxErrorTaskCannotRestartFirstSampNotAvailToGenerate: i32 = -201138; pub const DAQmxErrorOnlyUseStartTrigSrcPrptyWithDevDataLines: i32 = -201137; pub const DAQmxErrorOnlyUsePauseTrigSrcPrptyWithDevDataLines: i32 = -201136; pub const DAQmxErrorOnlyUseRefTrigSrcPrptyWithDevDataLines: i32 = -201135; pub const DAQmxErrorPauseTrigDigPatternSizeDoesNotMatchSrcSize: i32 = -201134; pub const DAQmxErrorLineConflictCDAQ: i32 = -201133; pub const DAQmxErrorCannotWriteBeyondFinalFiniteSample: i32 = -201132; pub const DAQmxErrorRefAndStartTriggerSrcCantBeSame: i32 = -201131; pub const DAQmxErrorMemMappingIncompatibleWithPhysChansInTask: i32 = -201130; pub const DAQmxErrorOutputDriveTypeMemMappingConflict: i32 = -201129; pub const DAQmxErrorCAPIDeviceIndexInvalid: i32 = -201128; pub const DAQmxErrorRatiometricDevicesMustUseExcitationForScaling: i32 = -201127; pub const DAQmxErrorPropertyRequiresPerDeviceCfg: i32 = -201126; pub const DAQmxErrorAICouplingAndAIInputSourceConflict: i32 = -201125; pub const DAQmxErrorOnlyOneTaskCanPerformDOMemoryMappingAtATime: i32 = -201124; pub const DAQmxErrorTooManyChansForAnalogRefTrigCDAQ: i32 = -201123; pub const DAQmxErrorSpecdPropertyValueIsIncompatibleWithSampleTimingType: i32 = -201122; pub const DAQmxErrorCPUNotSupportedRequireSSE: i32 = -201121; pub const DAQmxErrorSpecdPropertyValueIsIncompatibleWithSampleTimingResponseMode: i32 = -201120; pub const DAQmxErrorConflictingNextWriteIsLastAndRegenModeProperties: i32 = -201119; pub const DAQmxErrorMStudioOperationDoesNotSupportDeviceContext: i32 = -201118; pub const DAQmxErrorPropertyValueInChannelExpansionContextInvalid: i32 = -201117; pub const DAQmxErrorHWTimedNonBufferedAONotSupported: i32 = -201116; pub const DAQmxErrorWaveformLengthNotMultOfQuantum: i32 = -201115; pub const DAQmxErrorDSAExpansionMixedBoardsWrongOrderInPXIChassis: i32 = -201114; pub const DAQmxErrorPowerLevelTooLowForOOK: i32 = -201113; pub const DAQmxErrorDeviceComponentTestFailure: i32 = -201112; pub const DAQmxErrorUserDefinedWfmWithOOKUnsupported: i32 = -201111; pub const DAQmxErrorInvalidDigitalModulationUserDefinedWaveform: i32 = -201110; pub const DAQmxErrorBothRefInAndRefOutEnabled: i32 = -201109; pub const DAQmxErrorBothAnalogAndDigitalModulationEnabled: i32 = -201108; pub const DAQmxErrorBufferedOpsNotSupportedInSpecdSlotForCDAQ: i32 = -201107; pub const DAQmxErrorPhysChanNotSupportedInSpecdSlotForCDAQ: i32 = -201106; pub const DAQmxErrorResourceReservedWithConflictingSettings: i32 = -201105; pub const DAQmxErrorInconsistentAnalogTrigSettingsCDAQ: i32 = -201104; pub const DAQmxErrorTooManyChansForAnalogPauseTrigCDAQ: i32 = -201103; pub const DAQmxErrorAnalogTrigNotFirstInScanListCDAQ: i32 = -201102; pub const DAQmxErrorTooManyChansGivenTimingType: i32 = -201101; pub const DAQmxErrorSampClkTimebaseDivWithExtSampClk: i32 = -201100; pub const DAQmxErrorCantSaveTaskWithPerDeviceTimingProperties: i32 = -201099; pub const DAQmxErrorConflictingAutoZeroMode: i32 = -201098; pub const DAQmxErrorSampClkRateNotSupportedWithEAREnabled: i32 = -201097; pub const DAQmxErrorSampClkTimebaseRateNotSpecd: i32 = -201096; pub const DAQmxErrorSessionCorruptedByDLLReload: i32 = -201095; pub const DAQmxErrorActiveDevNotSupportedWithChanExpansion: i32 = -201094; pub const DAQmxErrorSampClkRateInvalid: i32 = -201093; pub const DAQmxErrorExtSyncPulseSrcCannotBeExported: i32 = -201092; pub const DAQmxErrorSyncPulseMinDelayToStartNeededForExtSyncPulseSrc: i32 = -201091; pub const DAQmxErrorSyncPulseSrcInvalid: i32 = -201090; pub const DAQmxErrorSampClkTimebaseRateInvalid: i32 = -201089; pub const DAQmxErrorSampClkTimebaseSrcInvalid: i32 = -201088; pub const DAQmxErrorSampClkRateMustBeSpecd: i32 = -201087; pub const DAQmxErrorInvalidAttributeName: i32 = -201086; pub const DAQmxErrorCJCChanNameMustBeSetWhenCJCSrcIsScannableChan: i32 = -201085; pub const DAQmxErrorHiddenChanMissingInChansPropertyInCfgFile: i32 = -201084; pub const DAQmxErrorChanNamesNotSpecdInCfgFile: i32 = -201083; pub const DAQmxErrorDuplicateHiddenChanNamesInCfgFile: i32 = -201082; pub const DAQmxErrorDuplicateChanNameInCfgFile: i32 = -201081; pub const DAQmxErrorInvalidSCCModuleForSlotSpecd: i32 = -201080; pub const DAQmxErrorInvalidSCCSlotNumberSpecd: i32 = -201079; pub const DAQmxErrorInvalidSectionIdentifier: i32 = -201078; pub const DAQmxErrorInvalidSectionName: i32 = -201077; pub const DAQmxErrorDAQmxVersionNotSupported: i32 = -201076; pub const DAQmxErrorSWObjectsFoundInFile: i32 = -201075; pub const DAQmxErrorHWObjectsFoundInFile: i32 = -201074; pub const DAQmxErrorLocalChannelSpecdWithNoParentTask: i32 = -201073; pub const DAQmxErrorTaskReferencesMissingLocalChannel: i32 = -201072; pub const DAQmxErrorTaskReferencesLocalChannelFromOtherTask: i32 = -201071; pub const DAQmxErrorTaskMissingChannelProperty: i32 = -201070; pub const DAQmxErrorInvalidLocalChanName: i32 = -201069; pub const DAQmxErrorInvalidEscapeCharacterInString: i32 = -201068; pub const DAQmxErrorInvalidTableIdentifier: i32 = -201067; pub const DAQmxErrorValueFoundInInvalidColumn: i32 = -201066; pub const DAQmxErrorMissingStartOfTable: i32 = -201065; pub const DAQmxErrorFileMissingRequiredDAQmxHeader: i32 = -201064; pub const DAQmxErrorDeviceIDDoesNotMatch: i32 = -201063; pub const DAQmxErrorBufferedOperationsNotSupportedOnSelectedLines: i32 = -201062; pub const DAQmxErrorPropertyConflictsWithScale: i32 = -201061; pub const DAQmxErrorInvalidINIFileSyntax: i32 = -201060; pub const DAQmxErrorDeviceInfoFailedPXIChassisNotIdentified: i32 = -201059; pub const DAQmxErrorInvalidHWProductNumber: i32 = -201058; pub const DAQmxErrorInvalidHWProductType: i32 = -201057; pub const DAQmxErrorInvalidNumericFormatSpecd: i32 = -201056; pub const DAQmxErrorDuplicatePropertyInObject: i32 = -201055; pub const DAQmxErrorInvalidEnumValueSpecd: i32 = -201054; pub const DAQmxErrorTEDSSensorPhysicalChannelConflict: i32 = -201053; pub const DAQmxErrorTooManyPhysicalChansForTEDSInterfaceSpecd: i32 = -201052; pub const DAQmxErrorIncapableTEDSInterfaceControllingDeviceSpecd: i32 = -201051; pub const DAQmxErrorSCCCarrierSpecdIsMissing: i32 = -201050; pub const DAQmxErrorIncapableSCCDigitizingDeviceSpecd: i32 = -201049; pub const DAQmxErrorAccessorySettingNotApplicable: i32 = -201048; pub const DAQmxErrorDeviceAndConnectorSpecdAlreadyOccupied: i32 = -201047; pub const DAQmxErrorIllegalAccessoryTypeForDeviceSpecd: i32 = -201046; pub const DAQmxErrorInvalidDeviceConnectorNumberSpecd: i32 = -201045; pub const DAQmxErrorInvalidAccessoryName: i32 = -201044; pub const DAQmxErrorMoreThanOneMatchForSpecdDevice: i32 = -201043; pub const DAQmxErrorNoMatchForSpecdDevice: i32 = -201042; pub const DAQmxErrorProductTypeAndProductNumberConflict: i32 = -201041; pub const DAQmxErrorExtraPropertyDetectedInSpecdObject: i32 = -201040; pub const DAQmxErrorRequiredPropertyMissing: i32 = -201039; pub const DAQmxErrorCantSetAuthorForLocalChan: i32 = -201038; pub const DAQmxErrorInvalidTimeValue: i32 = -201037; pub const DAQmxErrorInvalidTimeFormat: i32 = -201036; pub const DAQmxErrorDigDevChansSpecdInModeOtherThanParallel: i32 = -201035; pub const DAQmxErrorCascadeDigitizationModeNotSupported: i32 = -201034; pub const DAQmxErrorSpecdSlotAlreadyOccupied: i32 = -201033; pub const DAQmxErrorInvalidSCXISlotNumberSpecd: i32 = -201032; pub const DAQmxErrorAddressAlreadyInUse: i32 = -201031; pub const DAQmxErrorSpecdDeviceDoesNotSupportRTSI: i32 = -201030; pub const DAQmxErrorSpecdDeviceIsAlreadyOnRTSIBus: i32 = -201029; pub const DAQmxErrorIdentifierInUse: i32 = -201028; pub const DAQmxErrorWaitForNextSampleClockOrReadDetected3OrMoreMissedSampClks: i32 = -201027; pub const DAQmxErrorHWTimedAndDataXferPIO: i32 = -201026; pub const DAQmxErrorNonBufferedAndHWTimed: i32 = -201025; pub const DAQmxErrorCTROutSampClkPeriodShorterThanGenPulseTrainPeriodPolled: i32 = -201024; pub const DAQmxErrorCTROutSampClkPeriodShorterThanGenPulseTrainPeriod2: i32 = -201023; pub const DAQmxErrorCOCannotKeepUpInHWTimedSinglePointPolled: i32 = -201022; pub const DAQmxErrorWriteRecoveryCannotKeepUpInHWTimedSinglePoint: i32 = -201021; pub const DAQmxErrorNoChangeDetectionOnSelectedLineForDevice: i32 = -201020; pub const DAQmxErrorSMIOPauseTriggersNotSupportedWithChannelExpansion: i32 = -201019; pub const DAQmxErrorClockMasterForExternalClockNotLongestPipeline: i32 = -201018; pub const DAQmxErrorUnsupportedUnicodeByteOrderMarker: i32 = -201017; pub const DAQmxErrorTooManyInstructionsInLoopInScript: i32 = -201016; pub const DAQmxErrorPLLNotLocked: i32 = -201015; pub const DAQmxErrorIfElseBlockNotAllowedInFiniteRepeatLoopInScript: i32 = -201014; pub const DAQmxErrorIfElseBlockNotAllowedInConditionalRepeatLoopInScript: i32 = -201013; pub const DAQmxErrorClearIsLastInstructionInIfElseBlockInScript: i32 = -201012; pub const DAQmxErrorInvalidWaitDurationBeforeIfElseBlockInScript: i32 = -201011; pub const DAQmxErrorMarkerPosInvalidBeforeIfElseBlockInScript: i32 = -201010; pub const DAQmxErrorInvalidSubsetLengthBeforeIfElseBlockInScript: i32 = -201009; pub const DAQmxErrorInvalidWaveformLengthBeforeIfElseBlockInScript: i32 = -201008; pub const DAQmxErrorGenerateOrFiniteWaitInstructionExpectedBeforeIfElseBlockInScript: i32 = -201007; pub const DAQmxErrorCalPasswordNotSupported: i32 = -201006; pub const DAQmxErrorSetupCalNeededBeforeAdjustCal: i32 = -201005; pub const DAQmxErrorMultipleChansNotSupportedDuringCalSetup: i32 = -201004; pub const DAQmxErrorDevCannotBeAccessed: i32 = -201003; pub const DAQmxErrorSampClkRateDoesntMatchSampClkSrc: i32 = -201002; pub const DAQmxErrorSampClkRateNotSupportedWithEARDisabled: i32 = -201001; pub const DAQmxErrorLabVIEWVersionDoesntSupportDAQmxEvents: i32 = -201000; pub const DAQmxErrorCOReadyForNewValNotSupportedWithOnDemand: i32 = -200999; pub const DAQmxErrorCIHWTimedSinglePointNotSupportedForMeasType: i32 = -200998; pub const DAQmxErrorOnDemandNotSupportedWithHWTimedSinglePoint: i32 = -200997; pub const DAQmxErrorHWTimedSinglePointAndDataXferNotProgIO: i32 = -200996; pub const DAQmxErrorMemMapAndHWTimedSinglePoint: i32 = -200995; pub const DAQmxErrorCannotSetPropertyWhenHWTimedSinglePointTaskIsRunning: i32 = -200994; pub const DAQmxErrorCTROutSampClkPeriodShorterThanGenPulseTrainPeriod: i32 = -200993; pub const DAQmxErrorTooManyEventsGenerated: i32 = -200992; pub const DAQmxErrorMStudioCppRemoveEventsBeforeStop: i32 = -200991; pub const DAQmxErrorCAPICannotRegisterSyncEventsFromMultipleThreads: i32 = -200990; pub const DAQmxErrorReadWaitNextSampClkWaitMismatchTwo: i32 = -200989; pub const DAQmxErrorReadWaitNextSampClkWaitMismatchOne: i32 = -200988; pub const DAQmxErrorDAQmxSignalEventTypeNotSupportedByChanTypesOrDevicesInTask: i32 = -200987; pub const DAQmxErrorCannotUnregisterDAQmxSoftwareEventWhileTaskIsRunning: i32 = -200986; pub const DAQmxErrorAutoStartWriteNotAllowedEventRegistered: i32 = -200985; pub const DAQmxErrorAutoStartReadNotAllowedEventRegistered: i32 = -200984; pub const DAQmxErrorCannotGetPropertyWhenTaskNotReservedCommittedOrRunning: i32 = -200983; pub const DAQmxErrorSignalEventsNotSupportedByDevice: i32 = -200982; pub const DAQmxErrorEveryNSamplesAcqIntoBufferEventNotSupportedByDevice: i32 = -200981; pub const DAQmxErrorEveryNSampsTransferredFromBufferEventNotSupportedByDevice: i32 = -200980; pub const DAQmxErrorCAPISyncEventsTaskStateChangeNotAllowedFromDifferentThread: i32 = -200979; pub const DAQmxErrorDAQmxSWEventsWithDifferentCallMechanisms: i32 = -200978; pub const DAQmxErrorCantSaveChanWithPolyCalScaleAndAllowInteractiveEdit: i32 = -200977; pub const DAQmxErrorChanDoesNotSupportCJC: i32 = -200976; pub const DAQmxErrorCOReadyForNewValNotSupportedWithHWTimedSinglePoint: i32 = -200975; pub const DAQmxErrorDACAllowConnToGndNotSupportedByDevWhenRefSrcExt: i32 = -200974; pub const DAQmxErrorCantGetPropertyTaskNotRunning: i32 = -200973; pub const DAQmxErrorCantSetPropertyTaskNotRunning: i32 = -200972; pub const DAQmxErrorCantSetPropertyTaskNotRunningCommitted: i32 = -200971; pub const DAQmxErrorAIEveryNSampsEventIntervalNotMultipleOf2: i32 = -200970; pub const DAQmxErrorInvalidTEDSPhysChanNotAI: i32 = -200969; pub const DAQmxErrorCAPICannotPerformTaskOperationInAsyncCallback: i32 = -200968; pub const DAQmxErrorEveryNSampsTransferredFromBufferEventAlreadyRegistered: i32 = -200967; pub const DAQmxErrorEveryNSampsAcqIntoBufferEventAlreadyRegistered: i32 = -200966; pub const DAQmxErrorEveryNSampsTransferredFromBufferNotForInput: i32 = -200965; pub const DAQmxErrorEveryNSampsAcqIntoBufferNotForOutput: i32 = -200964; pub const DAQmxErrorAOSampTimingTypeDifferentIn2Tasks: i32 = -200963; pub const DAQmxErrorCouldNotDownloadFirmwareHWDamaged: i32 = -200962; pub const DAQmxErrorCouldNotDownloadFirmwareFileMissingOrDamaged: i32 = -200961; pub const DAQmxErrorCannotRegisterDAQmxSoftwareEventWhileTaskIsRunning: i32 = -200960; pub const DAQmxErrorDifferentRawDataCompression: i32 = -200959; pub const DAQmxErrorConfiguredTEDSInterfaceDevNotDetected: i32 = -200958; pub const DAQmxErrorCompressedSampSizeExceedsResolution: i32 = -200957; pub const DAQmxErrorChanDoesNotSupportCompression: i32 = -200956; pub const DAQmxErrorDifferentRawDataFormats: i32 = -200955; pub const DAQmxErrorSampClkOutputTermIncludesStartTrigSrc: i32 = -200954; pub const DAQmxErrorStartTrigSrcEqualToSampClkSrc: i32 = -200953; pub const DAQmxErrorEventOutputTermIncludesTrigSrc: i32 = -200952; pub const DAQmxErrorCOMultipleWritesBetweenSampClks: i32 = -200951; pub const DAQmxErrorDoneEventAlreadyRegistered: i32 = -200950; pub const DAQmxErrorSignalEventAlreadyRegistered: i32 = -200949; pub const DAQmxErrorCannotHaveTimedLoopAndDAQmxSignalEventsInSameTask: i32 = -200948; pub const DAQmxErrorNeedLabVIEW711PatchToUseDAQmxEvents: i32 = -200947; pub const DAQmxErrorStartFailedDueToWriteFailure: i32 = -200946; pub const DAQmxErrorDataXferCustomThresholdNotDMAXferMethodSpecifiedForDev: i32 = -200945; pub const DAQmxErrorDataXferRequestConditionNotSpecifiedForCustomThreshold: i32 = -200944; pub const DAQmxErrorDataXferCustomThresholdNotSpecified: i32 = -200943; pub const DAQmxErrorCAPISyncCallbackNotSupportedOnThisPlatform: i32 = -200942; pub const DAQmxErrorCalChanReversePolyCoefNotSpecd: i32 = -200941; pub const DAQmxErrorCalChanForwardPolyCoefNotSpecd: i32 = -200940; pub const DAQmxErrorChanCalRepeatedNumberInPreScaledVals: i32 = -200939; pub const DAQmxErrorChanCalTableNumScaledNotEqualNumPrescaledVals: i32 = -200938; pub const DAQmxErrorChanCalTableScaledValsNotSpecd: i32 = -200937; pub const DAQmxErrorChanCalTablePreScaledValsNotSpecd: i32 = -200936; pub const DAQmxErrorChanCalScaleTypeNotSet: i32 = -200935; pub const DAQmxErrorChanCalExpired: i32 = -200934; pub const DAQmxErrorChanCalExpirationDateNotSet: i32 = -200933; pub const DAQmxError3OutputPortCombinationGivenSampTimingType653x: i32 = -200932; pub const DAQmxError3InputPortCombinationGivenSampTimingType653x: i32 = -200931; pub const DAQmxError2OutputPortCombinationGivenSampTimingType653x: i32 = -200930; pub const DAQmxError2InputPortCombinationGivenSampTimingType653x: i32 = -200929; pub const DAQmxErrorPatternMatcherMayBeUsedByOneTrigOnly: i32 = -200928; pub const DAQmxErrorNoChansSpecdForPatternSource: i32 = -200927; pub const DAQmxErrorChangeDetectionChanNotInTask: i32 = -200926; pub const DAQmxErrorChangeDetectionChanNotTristated: i32 = -200925; pub const DAQmxErrorWaitModeValueNotSupportedNonBuffered: i32 = -200924; pub const DAQmxErrorWaitModePropertyNotSupportedNonBuffered: i32 = -200923; pub const DAQmxErrorCantSavePerLineConfigDigChanSoInteractiveEditsAllowed: i32 = -200922; pub const DAQmxErrorCantSaveNonPortMultiLineDigChanSoInteractiveEditsAllowed: i32 = -200921; pub const DAQmxErrorBufferSizeNotMultipleOfEveryNSampsEventIntervalNoIrqOnDev: i32 = -200920; pub const DAQmxErrorGlobalTaskNameAlreadyChanName: i32 = -200919; pub const DAQmxErrorGlobalChanNameAlreadyTaskName: i32 = -200918; pub const DAQmxErrorAOEveryNSampsEventIntervalNotMultipleOf2: i32 = -200917; pub const DAQmxErrorSampleTimebaseDivisorNotSupportedGivenTimingType: i32 = -200916; pub const DAQmxErrorHandshakeEventOutputTermNotSupportedGivenTimingType: i32 = -200915; pub const DAQmxErrorChangeDetectionOutputTermNotSupportedGivenTimingType: i32 = -200914; pub const DAQmxErrorReadyForTransferOutputTermNotSupportedGivenTimingType: i32 = -200913; pub const DAQmxErrorRefTrigOutputTermNotSupportedGivenTimingType: i32 = -200912; pub const DAQmxErrorStartTrigOutputTermNotSupportedGivenTimingType: i32 = -200911; pub const DAQmxErrorSampClockOutputTermNotSupportedGivenTimingType: i32 = -200910; pub const DAQmxError20MhzTimebaseNotSupportedGivenTimingType: i32 = -200909; pub const DAQmxErrorSampClockSourceNotSupportedGivenTimingType: i32 = -200908; pub const DAQmxErrorRefTrigTypeNotSupportedGivenTimingType: i32 = -200907; pub const DAQmxErrorPauseTrigTypeNotSupportedGivenTimingType: i32 = -200906; pub const DAQmxErrorHandshakeTrigTypeNotSupportedGivenTimingType: i32 = -200905; pub const DAQmxErrorStartTrigTypeNotSupportedGivenTimingType: i32 = -200904; pub const DAQmxErrorRefClkSrcNotSupported: i32 = -200903; pub const DAQmxErrorDataVoltageLowAndHighIncompatible: i32 = -200902; pub const DAQmxErrorInvalidCharInDigPatternString: i32 = -200901; pub const DAQmxErrorCantUsePort3AloneGivenSampTimingTypeOn653x: i32 = -200900; pub const DAQmxErrorCantUsePort1AloneGivenSampTimingTypeOn653x: i32 = -200899; pub const DAQmxErrorPartialUseOfPhysicalLinesWithinPortNotSupported653x: i32 = -200898; pub const DAQmxErrorPhysicalChanNotSupportedGivenSampTimingType653x: i32 = -200897; pub const DAQmxErrorCanExportOnlyDigEdgeTrigs: i32 = -200896; pub const DAQmxErrorRefTrigDigPatternSizeDoesNotMatchSourceSize: i32 = -200895; pub const DAQmxErrorStartTrigDigPatternSizeDoesNotMatchSourceSize: i32 = -200894; pub const DAQmxErrorChangeDetectionRisingAndFallingEdgeChanDontMatch: i32 = -200893; pub const DAQmxErrorPhysicalChansForChangeDetectionAndPatternMatch653x: i32 = -200892; pub const DAQmxErrorCanExportOnlyOnboardSampClk: i32 = -200891; pub const DAQmxErrorInternalSampClkNotRisingEdge: i32 = -200890; pub const DAQmxErrorRefTrigDigPatternChanNotInTask: i32 = -200889; pub const DAQmxErrorRefTrigDigPatternChanNotTristated: i32 = -200888; pub const DAQmxErrorStartTrigDigPatternChanNotInTask: i32 = -200887; pub const DAQmxErrorStartTrigDigPatternChanNotTristated: i32 = -200886; pub const DAQmxErrorPXIStarAndClock10Sync: i32 = -200885; pub const DAQmxErrorGlobalChanCannotBeSavedSoInteractiveEditsAllowed: i32 = -200884; pub const DAQmxErrorTaskCannotBeSavedSoInteractiveEditsAllowed: i32 = -200883; pub const DAQmxErrorInvalidGlobalChan: i32 = -200882; pub const DAQmxErrorEveryNSampsEventAlreadyRegistered: i32 = -200881; pub const DAQmxErrorEveryNSampsEventIntervalZeroNotSupported: i32 = -200880; pub const DAQmxErrorChanSizeTooBigForU16PortWrite: i32 = -200879; pub const DAQmxErrorChanSizeTooBigForU16PortRead: i32 = -200878; pub const DAQmxErrorBufferSizeNotMultipleOfEveryNSampsEventIntervalWhenDMA: i32 = -200877; pub const DAQmxErrorWriteWhenTaskNotRunningCOTicks: i32 = -200876; pub const DAQmxErrorWriteWhenTaskNotRunningCOFreq: i32 = -200875; pub const DAQmxErrorWriteWhenTaskNotRunningCOTime: i32 = -200874; pub const DAQmxErrorAOMinMaxNotSupportedDACRangeTooSmall: i32 = -200873; pub const DAQmxErrorAOMinMaxNotSupportedGivenDACRange: i32 = -200872; pub const DAQmxErrorAOMinMaxNotSupportedGivenDACRangeAndOffsetVal: i32 = -200871; pub const DAQmxErrorAOMinMaxNotSupportedDACOffsetValInappropriate: i32 = -200870; pub const DAQmxErrorAOMinMaxNotSupportedGivenDACOffsetVal: i32 = -200869; pub const DAQmxErrorAOMinMaxNotSupportedDACRefValTooSmall: i32 = -200868; pub const DAQmxErrorAOMinMaxNotSupportedGivenDACRefVal: i32 = -200867; pub const DAQmxErrorAOMinMaxNotSupportedGivenDACRefAndOffsetVal: i32 = -200866; pub const DAQmxErrorWhenAcqCompAndNumSampsPerChanExceedsOnBrdBufSize: i32 = -200865; pub const DAQmxErrorWhenAcqCompAndNoRefTrig: i32 = -200864; pub const DAQmxErrorWaitForNextSampClkNotSupported: i32 = -200863; pub const DAQmxErrorDevInUnidentifiedPXIChassis: i32 = -200862; pub const DAQmxErrorMaxSoundPressureMicSensitivitRelatedAIPropertiesNotSupportedByDev: i32 = -200861; pub const DAQmxErrorMaxSoundPressureAndMicSensitivityNotSupportedByDev: i32 = -200860; pub const DAQmxErrorAOBufferSizeZeroForSampClkTimingType: i32 = -200859; pub const DAQmxErrorAOCallWriteBeforeStartForSampClkTimingType: i32 = -200858; pub const DAQmxErrorInvalidCalLowPassCutoffFreq: i32 = -200857; pub const DAQmxErrorSimulationCannotBeDisabledForDevCreatedAsSimulatedDev: i32 = -200856; pub const DAQmxErrorCannotAddNewDevsAfterTaskConfiguration: i32 = -200855; pub const DAQmxErrorDifftSyncPulseSrcAndSampClkTimebaseSrcDevMultiDevTask: i32 = -200854; pub const DAQmxErrorTermWithoutDevInMultiDevTask: i32 = -200853; pub const DAQmxErrorSyncNoDevSampClkTimebaseOrSyncPulseInPXISlot2: i32 = -200852; pub const DAQmxErrorPhysicalChanNotOnThisConnector: i32 = -200851; pub const DAQmxErrorNumSampsToWaitNotGreaterThanZeroInScript: i32 = -200850; pub const DAQmxErrorNumSampsToWaitNotMultipleOfAlignmentQuantumInScript: i32 = -200849; pub const DAQmxErrorEveryNSamplesEventNotSupportedForNonBufferedTasks: i32 = -200848; pub const DAQmxErrorBufferedAndDataXferPIO: i32 = -200847; pub const DAQmxErrorCannotWriteWhenAutoStartFalseAndTaskNotRunning: i32 = -200846; pub const DAQmxErrorNonBufferedAndDataXferInterrupts: i32 = -200845; pub const DAQmxErrorWriteFailedMultipleCtrsWithFREQOUT: i32 = -200844; pub const DAQmxErrorReadNotCompleteBefore3SampClkEdges: i32 = -200843; pub const DAQmxErrorCtrHWTimedSinglePointAndDataXferNotProgIO: i32 = -200842; pub const DAQmxErrorPrescalerNot1ForInputTerminal: i32 = -200841; pub const DAQmxErrorPrescalerNot1ForTimebaseSrc: i32 = -200840; pub const DAQmxErrorSampClkTimingTypeWhenTristateIsFalse: i32 = -200839; pub const DAQmxErrorOutputBufferSizeNotMultOfXferSize: i32 = -200838; pub const DAQmxErrorSampPerChanNotMultOfXferSize: i32 = -200837; pub const DAQmxErrorWriteToTEDSFailed: i32 = -200836; pub const DAQmxErrorSCXIDevNotUsablePowerTurnedOff: i32 = -200835; pub const DAQmxErrorCannotReadWhenAutoStartFalseBufSizeZeroAndTaskNotRunning: i32 = -200834; pub const DAQmxErrorCannotReadWhenAutoStartFalseHWTimedSinglePtAndTaskNotRunning: i32 = -200833; pub const DAQmxErrorCannotReadWhenAutoStartFalseOnDemandAndTaskNotRunning: i32 = -200832; pub const DAQmxErrorSimultaneousAOWhenNotOnDemandTiming: i32 = -200831; pub const DAQmxErrorMemMapAndSimultaneousAO: i32 = -200830; pub const DAQmxErrorWriteFailedMultipleCOOutputTypes: i32 = -200829; pub const DAQmxErrorWriteToTEDSNotSupportedOnRT: i32 = -200828; pub const DAQmxErrorVirtualTEDSDataFileError: i32 = -200827; pub const DAQmxErrorTEDSSensorDataError: i32 = -200826; pub const DAQmxErrorDataSizeMoreThanSizeOfEEPROMOnTEDS: i32 = -200825; pub const DAQmxErrorPROMOnTEDSContainsBasicTEDSData: i32 = -200824; pub const DAQmxErrorPROMOnTEDSAlreadyWritten: i32 = -200823; pub const DAQmxErrorTEDSDoesNotContainPROM: i32 = -200822; pub const DAQmxErrorHWTimedSinglePointNotSupportedAI: i32 = -200821; pub const DAQmxErrorHWTimedSinglePointOddNumChansInAITask: i32 = -200820; pub const DAQmxErrorCantUseOnlyOnBoardMemWithProgrammedIO: i32 = -200819; pub const DAQmxErrorSwitchDevShutDownDueToHighTemp: i32 = -200818; pub const DAQmxErrorExcitationNotSupportedWhenTermCfgDiff: i32 = -200817; pub const DAQmxErrorTEDSMinElecValGEMaxElecVal: i32 = -200816; pub const DAQmxErrorTEDSMinPhysValGEMaxPhysVal: i32 = -200815; pub const DAQmxErrorCIOnboardClockNotSupportedAsInputTerm: i32 = -200814; pub const DAQmxErrorInvalidSampModeForPositionMeas: i32 = -200813; pub const DAQmxErrorTrigWhenAOHWTimedSinglePtSampMode: i32 = -200812; pub const DAQmxErrorDAQmxCantUseStringDueToUnknownChar: i32 = -200811; pub const DAQmxErrorDAQmxCantRetrieveStringDueToUnknownChar: i32 = -200810; pub const DAQmxErrorClearTEDSNotSupportedOnRT: i32 = -200809; pub const DAQmxErrorCfgTEDSNotSupportedOnRT: i32 = -200808; pub const DAQmxErrorProgFilterClkCfgdToDifferentMinPulseWidthBySameTask1PerDev: i32 = -200807; pub const DAQmxErrorProgFilterClkCfgdToDifferentMinPulseWidthByAnotherTask1PerDev: i32 = -200806; pub const DAQmxErrorNoLastExtCalDateTimeLastExtCalNotDAQmx: i32 = -200804; pub const DAQmxErrorCannotWriteNotStartedAutoStartFalseNotOnDemandHWTimedSglPt: i32 = -200803; pub const DAQmxErrorCannotWriteNotStartedAutoStartFalseNotOnDemandBufSizeZero: i32 = -200802; pub const DAQmxErrorCOInvalidTimingSrcDueToSignal: i32 = -200801; pub const DAQmxErrorCIInvalidTimingSrcForSampClkDueToSampTimingType: i32 = -200800; pub const DAQmxErrorCIInvalidTimingSrcForEventCntDueToSampMode: i32 = -200799; pub const DAQmxErrorNoChangeDetectOnNonInputDigLineForDev: i32 = -200798; pub const DAQmxErrorEmptyStringTermNameNotSupported: i32 = -200797; pub const DAQmxErrorMemMapEnabledForHWTimedNonBufferedAO: i32 = -200796; pub const DAQmxErrorDevOnboardMemOverflowDuringHWTimedNonBufferedGen: i32 = -200795; pub const DAQmxErrorCODAQmxWriteMultipleChans: i32 = -200794; pub const DAQmxErrorCantMaintainExistingValueAOSync: i32 = -200793; pub const DAQmxErrorMStudioMultiplePhysChansNotSupported: i32 = -200792; pub const DAQmxErrorCantConfigureTEDSForChan: i32 = -200791; pub const DAQmxErrorWriteDataTypeTooSmall: i32 = -200790; pub const DAQmxErrorReadDataTypeTooSmall: i32 = -200789; pub const DAQmxErrorMeasuredBridgeOffsetTooHigh: i32 = -200788; pub const DAQmxErrorStartTrigConflictWithCOHWTimedSinglePt: i32 = -200787; pub const DAQmxErrorSampClkRateExtSampClkTimebaseRateMismatch: i32 = -200786; pub const DAQmxErrorInvalidTimingSrcDueToSampTimingType: i32 = -200785; pub const DAQmxErrorVirtualTEDSFileNotFound: i32 = -200784; pub const DAQmxErrorMStudioNoForwardPolyScaleCoeffs: i32 = -200783; pub const DAQmxErrorMStudioNoReversePolyScaleCoeffs: i32 = -200782; pub const DAQmxErrorMStudioNoPolyScaleCoeffsUseCalc: i32 = -200781; pub const DAQmxErrorMStudioNoForwardPolyScaleCoeffsUseCalc: i32 = -200780; pub const DAQmxErrorMStudioNoReversePolyScaleCoeffsUseCalc: i32 = -200779; pub const DAQmxErrorCOSampModeSampTimingTypeSampClkConflict: i32 = -200778; pub const DAQmxErrorDevCannotProduceMinPulseWidth: i32 = -200777; pub const DAQmxErrorCannotProduceMinPulseWidthGivenPropertyValues: i32 = -200776; pub const DAQmxErrorTermCfgdToDifferentMinPulseWidthByAnotherTask: i32 = -200775; pub const DAQmxErrorTermCfgdToDifferentMinPulseWidthByAnotherProperty: i32 = -200774; pub const DAQmxErrorDigSyncNotAvailableOnTerm: i32 = -200773; pub const DAQmxErrorDigFilterNotAvailableOnTerm: i32 = -200772; pub const DAQmxErrorDigFilterEnabledMinPulseWidthNotCfg: i32 = -200771; pub const DAQmxErrorDigFilterAndSyncBothEnabled: i32 = -200770; pub const DAQmxErrorHWTimedSinglePointAOAndDataXferNotProgIO: i32 = -200769; pub const DAQmxErrorNonBufferedAOAndDataXferNotProgIO: i32 = -200768; pub const DAQmxErrorProgIODataXferForBufferedAO: i32 = -200767; pub const DAQmxErrorTEDSLegacyTemplateIDInvalidOrUnsupported: i32 = -200766; pub const DAQmxErrorTEDSMappingMethodInvalidOrUnsupported: i32 = -200765; pub const DAQmxErrorTEDSLinearMappingSlopeZero: i32 = -200764; pub const DAQmxErrorAIInputBufferSizeNotMultOfXferSize: i32 = -200763; pub const DAQmxErrorNoSyncPulseExtSampClkTimebase: i32 = -200762; pub const DAQmxErrorNoSyncPulseAnotherTaskRunning: i32 = -200761; pub const DAQmxErrorAOMinMaxNotInGainRange: i32 = -200760; pub const DAQmxErrorAOMinMaxNotInDACRange: i32 = -200759; pub const DAQmxErrorDevOnlySupportsSampClkTimingAO: i32 = -200758; pub const DAQmxErrorDevOnlySupportsSampClkTimingAI: i32 = -200757; pub const DAQmxErrorTEDSIncompatibleSensorAndMeasType: i32 = -200756; pub const DAQmxErrorTEDSMultipleCalTemplatesNotSupported: i32 = -200755; pub const DAQmxErrorTEDSTemplateParametersNotSupported: i32 = -200754; pub const DAQmxErrorParsingTEDSData: i32 = -200753; pub const DAQmxErrorMultipleActivePhysChansNotSupported: i32 = -200752; pub const DAQmxErrorNoChansSpecdForChangeDetect: i32 = -200751; pub const DAQmxErrorInvalidCalVoltageForGivenGain: i32 = -200750; pub const DAQmxErrorInvalidCalGain: i32 = -200749; pub const DAQmxErrorMultipleWritesBetweenSampClks: i32 = -200748; pub const DAQmxErrorInvalidAcqTypeForFREQOUT: i32 = -200747; pub const DAQmxErrorSuitableTimebaseNotFoundTimeCombo2: i32 = -200746; pub const DAQmxErrorSuitableTimebaseNotFoundFrequencyCombo2: i32 = -200745; pub const DAQmxErrorRefClkRateRefClkSrcMismatch: i32 = -200744; pub const DAQmxErrorNoTEDSTerminalBlock: i32 = -200743; pub const DAQmxErrorCorruptedTEDSMemory: i32 = -200742; pub const DAQmxErrorTEDSNotSupported: i32 = -200741; pub const DAQmxErrorTimingSrcTaskStartedBeforeTimedLoop: i32 = -200740; pub const DAQmxErrorPropertyNotSupportedForTimingSrc: i32 = -200739; pub const DAQmxErrorTimingSrcDoesNotExist: i32 = -200738; pub const DAQmxErrorInputBufferSizeNotEqualSampsPerChanForFiniteSampMode: i32 = -200737; pub const DAQmxErrorFREQOUTCannotProduceDesiredFrequency2: i32 = -200736; pub const DAQmxErrorExtRefClkRateNotSpecified: i32 = -200735; pub const DAQmxErrorDeviceDoesNotSupportDMADataXferForNonBufferedAcq: i32 = -200734; pub const DAQmxErrorDigFilterMinPulseWidthSetWhenTristateIsFalse: i32 = -200733; pub const DAQmxErrorDigFilterEnableSetWhenTristateIsFalse: i32 = -200732; pub const DAQmxErrorNoHWTimingWithOnDemand: i32 = -200731; pub const DAQmxErrorCannotDetectChangesWhenTristateIsFalse: i32 = -200730; pub const DAQmxErrorCannotHandshakeWhenTristateIsFalse: i32 = -200729; pub const DAQmxErrorLinesUsedForStaticInputNotForHandshakingControl: i32 = -200728; pub const DAQmxErrorLinesUsedForHandshakingControlNotForStaticInput: i32 = -200727; pub const DAQmxErrorLinesUsedForStaticInputNotForHandshakingInput: i32 = -200726; pub const DAQmxErrorLinesUsedForHandshakingInputNotForStaticInput: i32 = -200725; pub const DAQmxErrorDifferentDITristateValsForChansInTask: i32 = -200724; pub const DAQmxErrorTimebaseCalFreqVarianceTooLarge: i32 = -200723; pub const DAQmxErrorTimebaseCalFailedToConverge: i32 = -200722; pub const DAQmxErrorInadequateResolutionForTimebaseCal: i32 = -200721; pub const DAQmxErrorInvalidAOGainCalConst: i32 = -200720; pub const DAQmxErrorInvalidAOOffsetCalConst: i32 = -200719; pub const DAQmxErrorInvalidAIGainCalConst: i32 = -200718; pub const DAQmxErrorInvalidAIOffsetCalConst: i32 = -200717; pub const DAQmxErrorDigOutputOverrun: i32 = -200716; pub const DAQmxErrorDigInputOverrun: i32 = -200715; pub const DAQmxErrorAcqStoppedDriverCantXferDataFastEnough: i32 = -200714; pub const DAQmxErrorChansCantAppearInSameTask: i32 = -200713; pub const DAQmxErrorInputCfgFailedBecauseWatchdogExpired: i32 = -200712; pub const DAQmxErrorAnalogTrigChanNotExternal: i32 = -200711; pub const DAQmxErrorTooManyChansForInternalAIInputSrc: i32 = -200710; pub const DAQmxErrorTEDSSensorNotDetected: i32 = -200709; pub const DAQmxErrorPrptyGetSpecdActiveItemFailedDueToDifftValues: i32 = -200708; pub const DAQmxErrorRoutingDestTermPXIClk10InNotInSlot2: i32 = -200706; pub const DAQmxErrorRoutingDestTermPXIStarXNotInSlot2: i32 = -200705; pub const DAQmxErrorRoutingSrcTermPXIStarXNotInSlot2: i32 = -200704; pub const DAQmxErrorRoutingSrcTermPXIStarInSlot16AndAbove: i32 = -200703; pub const DAQmxErrorRoutingDestTermPXIStarInSlot16AndAbove: i32 = -200702; pub const DAQmxErrorRoutingDestTermPXIStarInSlot2: i32 = -200701; pub const DAQmxErrorRoutingSrcTermPXIStarInSlot2: i32 = -200700; pub const DAQmxErrorRoutingDestTermPXIChassisNotIdentified: i32 = -200699; pub const DAQmxErrorRoutingSrcTermPXIChassisNotIdentified: i32 = -200698; pub const DAQmxErrorFailedToAcquireCalData: i32 = -200697; pub const DAQmxErrorBridgeOffsetNullingCalNotSupported: i32 = -200696; pub const DAQmxErrorAIMaxNotSpecified: i32 = -200695; pub const DAQmxErrorAIMinNotSpecified: i32 = -200694; pub const DAQmxErrorOddTotalBufferSizeToWrite: i32 = -200693; pub const DAQmxErrorOddTotalNumSampsToWrite: i32 = -200692; pub const DAQmxErrorBufferWithWaitMode: i32 = -200691; pub const DAQmxErrorBufferWithHWTimedSinglePointSampMode: i32 = -200690; pub const DAQmxErrorCOWritePulseLowTicksNotSupported: i32 = -200689; pub const DAQmxErrorCOWritePulseHighTicksNotSupported: i32 = -200688; pub const DAQmxErrorCOWritePulseLowTimeOutOfRange: i32 = -200687; pub const DAQmxErrorCOWritePulseHighTimeOutOfRange: i32 = -200686; pub const DAQmxErrorCOWriteFreqOutOfRange: i32 = -200685; pub const DAQmxErrorCOWriteDutyCycleOutOfRange: i32 = -200684; pub const DAQmxErrorInvalidInstallation: i32 = -200683; pub const DAQmxErrorRefTrigMasterSessionUnavailable: i32 = -200682; pub const DAQmxErrorRouteFailedBecauseWatchdogExpired: i32 = -200681; pub const DAQmxErrorDeviceShutDownDueToHighTemp: i32 = -200680; pub const DAQmxErrorNoMemMapWhenHWTimedSinglePoint: i32 = -200679; pub const DAQmxErrorWriteFailedBecauseWatchdogExpired: i32 = -200678; pub const DAQmxErrorDifftInternalAIInputSrcs: i32 = -200677; pub const DAQmxErrorDifftAIInputSrcInOneChanGroup: i32 = -200676; pub const DAQmxErrorInternalAIInputSrcInMultChanGroups: i32 = -200675; pub const DAQmxErrorSwitchOpFailedDueToPrevError: i32 = -200674; pub const DAQmxErrorWroteMultiSampsUsingSingleSampWrite: i32 = -200673; pub const DAQmxErrorMismatchedInputArraySizes: i32 = -200672; pub const DAQmxErrorCantExceedRelayDriveLimit: i32 = -200671; pub const DAQmxErrorDACRngLowNotEqualToMinusRefVal: i32 = -200670; pub const DAQmxErrorCantAllowConnectDACToGnd: i32 = -200669; pub const DAQmxErrorWatchdogTimeoutOutOfRangeAndNotSpecialVal: i32 = -200668; pub const DAQmxErrorNoWatchdogOutputOnPortReservedForInput: i32 = -200667; pub const DAQmxErrorNoInputOnPortCfgdForWatchdogOutput: i32 = -200666; pub const DAQmxErrorWatchdogExpirationStateNotEqualForLinesInPort: i32 = -200665; pub const DAQmxErrorCannotPerformOpWhenTaskNotReserved: i32 = -200664; pub const DAQmxErrorPowerupStateNotSupported: i32 = -200663; pub const DAQmxErrorWatchdogTimerNotSupported: i32 = -200662; pub const DAQmxErrorOpNotSupportedWhenRefClkSrcNone: i32 = -200661; pub const DAQmxErrorSampClkRateUnavailable: i32 = -200660; pub const DAQmxErrorPrptyGetSpecdSingleActiveChanFailedDueToDifftVals: i32 = -200659; pub const DAQmxErrorPrptyGetImpliedActiveChanFailedDueToDifftVals: i32 = -200658; pub const DAQmxErrorPrptyGetSpecdActiveChanFailedDueToDifftVals: i32 = -200657; pub const DAQmxErrorNoRegenWhenUsingBrdMem: i32 = -200656; pub const DAQmxErrorNonbufferedReadMoreThanSampsPerChan: i32 = -200655; pub const DAQmxErrorWatchdogExpirationTristateNotSpecdForEntirePort: i32 = -200654; pub const DAQmxErrorPowerupTristateNotSpecdForEntirePort: i32 = -200653; pub const DAQmxErrorPowerupStateNotSpecdForEntirePort: i32 = -200652; pub const DAQmxErrorCantSetWatchdogExpirationOnDigInChan: i32 = -200651; pub const DAQmxErrorCantSetPowerupStateOnDigInChan: i32 = -200650; pub const DAQmxErrorPhysChanNotInTask: i32 = -200649; pub const DAQmxErrorPhysChanDevNotInTask: i32 = -200648; pub const DAQmxErrorDigInputNotSupported: i32 = -200647; pub const DAQmxErrorDigFilterIntervalNotEqualForLines: i32 = -200646; pub const DAQmxErrorDigFilterIntervalAlreadyCfgd: i32 = -200645; pub const DAQmxErrorCantResetExpiredWatchdog: i32 = -200644; pub const DAQmxErrorActiveChanTooManyLinesSpecdWhenGettingPrpty: i32 = -200643; pub const DAQmxErrorActiveChanNotSpecdWhenGetting1LinePrpty: i32 = -200642; pub const DAQmxErrorDigPrptyCannotBeSetPerLine: i32 = -200641; pub const DAQmxErrorSendAdvCmpltAfterWaitForTrigInScanlist: i32 = -200640; pub const DAQmxErrorDisconnectionRequiredInScanlist: i32 = -200639; pub const DAQmxErrorTwoWaitForTrigsAfterConnectionInScanlist: i32 = -200638; pub const DAQmxErrorActionSeparatorRequiredAfterBreakingConnectionInScanlist: i32 = -200637; pub const DAQmxErrorConnectionInScanlistMustWaitForTrig: i32 = -200636; pub const DAQmxErrorActionNotSupportedTaskNotWatchdog: i32 = -200635; pub const DAQmxErrorWfmNameSameAsScriptName: i32 = -200634; pub const DAQmxErrorScriptNameSameAsWfmName: i32 = -200633; pub const DAQmxErrorDSFStopClock: i32 = -200632; pub const DAQmxErrorDSFReadyForStartClock: i32 = -200631; pub const DAQmxErrorWriteOffsetNotMultOfIncr: i32 = -200630; pub const DAQmxErrorDifferentPrptyValsNotSupportedOnDev: i32 = -200629; pub const DAQmxErrorRefAndPauseTrigConfigured: i32 = -200628; pub const DAQmxErrorFailedToEnableHighSpeedInputClock: i32 = -200627; pub const DAQmxErrorEmptyPhysChanInPowerUpStatesArray: i32 = -200626; pub const DAQmxErrorActivePhysChanTooManyLinesSpecdWhenGettingPrpty: i32 = -200625; pub const DAQmxErrorActivePhysChanNotSpecdWhenGetting1LinePrpty: i32 = -200624; pub const DAQmxErrorPXIDevTempCausedShutDown: i32 = -200623; pub const DAQmxErrorInvalidNumSampsToWrite: i32 = -200622; pub const DAQmxErrorOutputFIFOUnderflow2: i32 = -200621; pub const DAQmxErrorRepeatedAIPhysicalChan: i32 = -200620; pub const DAQmxErrorMultScanOpsInOneChassis: i32 = -200619; pub const DAQmxErrorInvalidAIChanOrder: i32 = -200618; pub const DAQmxErrorReversePowerProtectionActivated: i32 = -200617; pub const DAQmxErrorInvalidAsynOpHandle: i32 = -200616; pub const DAQmxErrorFailedToEnableHighSpeedOutput: i32 = -200615; pub const DAQmxErrorCannotReadPastEndOfRecord: i32 = -200614; pub const DAQmxErrorAcqStoppedToPreventInputBufferOverwriteOneDataXferMech: i32 = -200613; pub const DAQmxErrorZeroBasedChanIndexInvalid: i32 = -200612; pub const DAQmxErrorNoChansOfGivenTypeInTask: i32 = -200611; pub const DAQmxErrorSampClkSrcInvalidForOutputValidForInput: i32 = -200610; pub const DAQmxErrorOutputBufSizeTooSmallToStartGen: i32 = -200609; pub const DAQmxErrorInputBufSizeTooSmallToStartAcq: i32 = -200608; pub const DAQmxErrorExportTwoSignalsOnSameTerminal: i32 = -200607; pub const DAQmxErrorChanIndexInvalid: i32 = -200606; pub const DAQmxErrorRangeSyntaxNumberTooBig: i32 = -200605; pub const DAQmxErrorNULLPtr: i32 = -200604; pub const DAQmxErrorScaledMinEqualMax: i32 = -200603; pub const DAQmxErrorPreScaledMinEqualMax: i32 = -200602; pub const DAQmxErrorPropertyNotSupportedForScaleType: i32 = -200601; pub const DAQmxErrorChannelNameGenerationNumberTooBig: i32 = -200600; pub const DAQmxErrorRepeatedNumberInScaledValues: i32 = -200599; pub const DAQmxErrorRepeatedNumberInPreScaledValues: i32 = -200598; pub const DAQmxErrorLinesAlreadyReservedForOutput: i32 = -200597; pub const DAQmxErrorSwitchOperationChansSpanMultipleDevsInList: i32 = -200596; pub const DAQmxErrorInvalidIDInListAtBeginningOfSwitchOperation: i32 = -200595; pub const DAQmxErrorMStudioInvalidPolyDirection: i32 = -200594; pub const DAQmxErrorMStudioPropertyGetWhileTaskNotVerified: i32 = -200593; pub const DAQmxErrorRangeWithTooManyObjects: i32 = -200592; pub const DAQmxErrorCppDotNetAPINegativeBufferSize: i32 = -200591; pub const DAQmxErrorCppCantRemoveInvalidEventHandler: i32 = -200590; pub const DAQmxErrorCppCantRemoveEventHandlerTwice: i32 = -200589; pub const DAQmxErrorCppCantRemoveOtherObjectsEventHandler: i32 = -200588; pub const DAQmxErrorDigLinesReservedOrUnavailable: i32 = -200587; pub const DAQmxErrorDSFFailedToResetStream: i32 = -200586; pub const DAQmxErrorDSFReadyForOutputNotAsserted: i32 = -200585; pub const DAQmxErrorSampToWritePerChanNotMultipleOfIncr: i32 = -200584; pub const DAQmxErrorAOPropertiesCauseVoltageBelowMin: i32 = -200583; pub const DAQmxErrorAOPropertiesCauseVoltageOverMax: i32 = -200582; pub const DAQmxErrorPropertyNotSupportedWhenRefClkSrcNone: i32 = -200581; pub const DAQmxErrorAIMaxTooSmall: i32 = -200580; pub const DAQmxErrorAIMaxTooLarge: i32 = -200579; pub const DAQmxErrorAIMinTooSmall: i32 = -200578; pub const DAQmxErrorAIMinTooLarge: i32 = -200577; pub const DAQmxErrorBuiltInCJCSrcNotSupported: i32 = -200576; pub const DAQmxErrorTooManyPostTrigSampsPerChan: i32 = -200575; pub const DAQmxErrorTrigLineNotFoundSingleDevRoute: i32 = -200574; pub const DAQmxErrorDifferentInternalAIInputSources: i32 = -200573; pub const DAQmxErrorDifferentAIInputSrcInOneChanGroup: i32 = -200572; pub const DAQmxErrorInternalAIInputSrcInMultipleChanGroups: i32 = -200571; pub const DAQmxErrorCAPIChanIndexInvalid: i32 = -200570; pub const DAQmxErrorCollectionDoesNotMatchChanType: i32 = -200569; pub const DAQmxErrorOutputCantStartChangedRegenerationMode: i32 = -200568; pub const DAQmxErrorOutputCantStartChangedBufferSize: i32 = -200567; pub const DAQmxErrorChanSizeTooBigForU32PortWrite: i32 = -200566; pub const DAQmxErrorChanSizeTooBigForU8PortWrite: i32 = -200565; pub const DAQmxErrorChanSizeTooBigForU32PortRead: i32 = -200564; pub const DAQmxErrorChanSizeTooBigForU8PortRead: i32 = -200563; pub const DAQmxErrorInvalidDigDataWrite: i32 = -200562; pub const DAQmxErrorInvalidAODataWrite: i32 = -200561; pub const DAQmxErrorWaitUntilDoneDoesNotIndicateDone: i32 = -200560; pub const DAQmxErrorMultiChanTypesInTask: i32 = -200559; pub const DAQmxErrorMultiDevsInTask: i32 = -200558; pub const DAQmxErrorCannotSetPropertyWhenTaskRunning: i32 = -200557; pub const DAQmxErrorCannotGetPropertyWhenTaskNotCommittedOrRunning: i32 = -200556; pub const DAQmxErrorLeadingUnderscoreInString: i32 = -200555; pub const DAQmxErrorTrailingSpaceInString: i32 = -200554; pub const DAQmxErrorLeadingSpaceInString: i32 = -200553; pub const DAQmxErrorInvalidCharInString: i32 = -200552; pub const DAQmxErrorDLLBecameUnlocked: i32 = -200551; pub const DAQmxErrorDLLLock: i32 = -200550; pub const DAQmxErrorSelfCalConstsInvalid: i32 = -200549; pub const DAQmxErrorInvalidTrigCouplingExceptForExtTrigChan: i32 = -200548; pub const DAQmxErrorWriteFailsBufferSizeAutoConfigured: i32 = -200547; pub const DAQmxErrorExtCalAdjustExtRefVoltageFailed: i32 = -200546; pub const DAQmxErrorSelfCalFailedExtNoiseOrRefVoltageOutOfCal: i32 = -200545; pub const DAQmxErrorExtCalTemperatureNotDAQmx: i32 = -200544; pub const DAQmxErrorExtCalDateTimeNotDAQmx: i32 = -200543; pub const DAQmxErrorSelfCalTemperatureNotDAQmx: i32 = -200542; pub const DAQmxErrorSelfCalDateTimeNotDAQmx: i32 = -200541; pub const DAQmxErrorDACRefValNotSet: i32 = -200540; pub const DAQmxErrorAnalogMultiSampWriteNotSupported: i32 = -200539; pub const DAQmxErrorInvalidActionInControlTask: i32 = -200538; pub const DAQmxErrorPolyCoeffsInconsistent: i32 = -200537; pub const DAQmxErrorSensorValTooLow: i32 = -200536; pub const DAQmxErrorSensorValTooHigh: i32 = -200535; pub const DAQmxErrorWaveformNameTooLong: i32 = -200534; pub const DAQmxErrorIdentifierTooLongInScript: i32 = -200533; pub const DAQmxErrorUnexpectedIDFollowingSwitchChanName: i32 = -200532; pub const DAQmxErrorRelayNameNotSpecifiedInList: i32 = -200531; pub const DAQmxErrorUnexpectedIDFollowingRelayNameInList: i32 = -200530; pub const DAQmxErrorUnexpectedIDFollowingSwitchOpInList: i32 = -200529; pub const DAQmxErrorInvalidLineGrouping: i32 = -200528; pub const DAQmxErrorCtrMinMax: i32 = -200527; pub const DAQmxErrorWriteChanTypeMismatch: i32 = -200526; pub const DAQmxErrorReadChanTypeMismatch: i32 = -200525; pub const DAQmxErrorWriteNumChansMismatch: i32 = -200524; pub const DAQmxErrorOneChanReadForMultiChanTask: i32 = -200523; pub const DAQmxErrorCannotSelfCalDuringExtCal: i32 = -200522; pub const DAQmxErrorMeasCalAdjustOscillatorPhaseDAC: i32 = -200521; pub const DAQmxErrorInvalidCalConstCalADCAdjustment: i32 = -200520; pub const DAQmxErrorInvalidCalConstOscillatorFreqDACValue: i32 = -200519; pub const DAQmxErrorInvalidCalConstOscillatorPhaseDACValue: i32 = -200518; pub const DAQmxErrorInvalidCalConstOffsetDACValue: i32 = -200517; pub const DAQmxErrorInvalidCalConstGainDACValue: i32 = -200516; pub const DAQmxErrorInvalidNumCalADCReadsToAverage: i32 = -200515; pub const DAQmxErrorInvalidCfgCalAdjustDirectPathOutputImpedance: i32 = -200514; pub const DAQmxErrorInvalidCfgCalAdjustMainPathOutputImpedance: i32 = -200513; pub const DAQmxErrorInvalidCfgCalAdjustMainPathPostAmpGainAndOffset: i32 = -200512; pub const DAQmxErrorInvalidCfgCalAdjustMainPathPreAmpGain: i32 = -200511; pub const DAQmxErrorInvalidCfgCalAdjustMainPreAmpOffset: i32 = -200510; pub const DAQmxErrorMeasCalAdjustCalADC: i32 = -200509; pub const DAQmxErrorMeasCalAdjustOscillatorFrequency: i32 = -200508; pub const DAQmxErrorMeasCalAdjustDirectPathOutputImpedance: i32 = -200507; pub const DAQmxErrorMeasCalAdjustMainPathOutputImpedance: i32 = -200506; pub const DAQmxErrorMeasCalAdjustDirectPathGain: i32 = -200505; pub const DAQmxErrorMeasCalAdjustMainPathPostAmpGainAndOffset: i32 = -200504; pub const DAQmxErrorMeasCalAdjustMainPathPreAmpGain: i32 = -200503; pub const DAQmxErrorMeasCalAdjustMainPathPreAmpOffset: i32 = -200502; pub const DAQmxErrorInvalidDateTimeInEEPROM: i32 = -200501; pub const DAQmxErrorUnableToLocateErrorResources: i32 = -200500; pub const DAQmxErrorDotNetAPINotUnsigned32BitNumber: i32 = -200499; pub const DAQmxErrorInvalidRangeOfObjectsSyntaxInString: i32 = -200498; pub const DAQmxErrorAttemptToEnableLineNotPreviouslyDisabled: i32 = -200497; pub const DAQmxErrorInvalidCharInPattern: i32 = -200496; pub const DAQmxErrorIntermediateBufferFull: i32 = -200495; pub const DAQmxErrorLoadTaskFailsBecauseNoTimingOnDev: i32 = -200494; pub const DAQmxErrorCAPIReservedParamNotNULLNorEmpty: i32 = -200493; pub const DAQmxErrorCAPIReservedParamNotNULL: i32 = -200492; pub const DAQmxErrorCAPIReservedParamNotZero: i32 = -200491; pub const DAQmxErrorSampleValueOutOfRange: i32 = -200490; pub const DAQmxErrorChanAlreadyInTask: i32 = -200489; pub const DAQmxErrorVirtualChanDoesNotExist: i32 = -200488; pub const DAQmxErrorChanNotInTask: i32 = -200486; pub const DAQmxErrorTaskNotInDataNeighborhood: i32 = -200485; pub const DAQmxErrorCantSaveTaskWithoutReplace: i32 = -200484; pub const DAQmxErrorCantSaveChanWithoutReplace: i32 = -200483; pub const DAQmxErrorDevNotInTask: i32 = -200482; pub const DAQmxErrorDevAlreadyInTask: i32 = -200481; pub const DAQmxErrorCanNotPerformOpWhileTaskRunning: i32 = -200479; pub const DAQmxErrorCanNotPerformOpWhenNoChansInTask: i32 = -200478; pub const DAQmxErrorCanNotPerformOpWhenNoDevInTask: i32 = -200477; pub const DAQmxErrorCannotPerformOpWhenTaskNotRunning: i32 = -200475; pub const DAQmxErrorOperationTimedOut: i32 = -200474; pub const DAQmxErrorCannotReadWhenAutoStartFalseAndTaskNotRunningOrCommitted: i32 = -200473; pub const DAQmxErrorCannotWriteWhenAutoStartFalseAndTaskNotRunningOrCommitted: i32 = -200472; pub const DAQmxErrorTaskVersionNew: i32 = -200470; pub const DAQmxErrorChanVersionNew: i32 = -200469; pub const DAQmxErrorEmptyString: i32 = -200467; pub const DAQmxErrorChannelSizeTooBigForPortReadType: i32 = -200466; pub const DAQmxErrorChannelSizeTooBigForPortWriteType: i32 = -200465; pub const DAQmxErrorExpectedNumberOfChannelsVerificationFailed: i32 = -200464; pub const DAQmxErrorNumLinesMismatchInReadOrWrite: i32 = -200463; pub const DAQmxErrorOutputBufferEmpty: i32 = -200462; pub const DAQmxErrorInvalidChanName: i32 = -200461; pub const DAQmxErrorReadNoInputChansInTask: i32 = -200460; pub const DAQmxErrorWriteNoOutputChansInTask: i32 = -200459; pub const DAQmxErrorPropertyNotSupportedNotInputTask: i32 = -200457; pub const DAQmxErrorPropertyNotSupportedNotOutputTask: i32 = -200456; pub const DAQmxErrorGetPropertyNotInputBufferedTask: i32 = -200455; pub const DAQmxErrorGetPropertyNotOutputBufferedTask: i32 = -200454; pub const DAQmxErrorInvalidTimeoutVal: i32 = -200453; pub const DAQmxErrorAttributeNotSupportedInTaskContext: i32 = -200452; pub const DAQmxErrorAttributeNotQueryableUnlessTaskIsCommitted: i32 = -200451; pub const DAQmxErrorAttributeNotSettableWhenTaskIsRunning: i32 = -200450; pub const DAQmxErrorDACRngLowNotMinusRefValNorZero: i32 = -200449; pub const DAQmxErrorDACRngHighNotEqualRefVal: i32 = -200448; pub const DAQmxErrorUnitsNotFromCustomScale: i32 = -200447; pub const DAQmxErrorInvalidVoltageReadingDuringExtCal: i32 = -200446; pub const DAQmxErrorCalFunctionNotSupported: i32 = -200445; pub const DAQmxErrorInvalidPhysicalChanForCal: i32 = -200444; pub const DAQmxErrorExtCalNotComplete: i32 = -200443; pub const DAQmxErrorCantSyncToExtStimulusFreqDuringCal: i32 = -200442; pub const DAQmxErrorUnableToDetectExtStimulusFreqDuringCal: i32 = -200441; pub const DAQmxErrorInvalidCloseAction: i32 = -200440; pub const DAQmxErrorExtCalFunctionOutsideExtCalSession: i32 = -200439; pub const DAQmxErrorInvalidCalArea: i32 = -200438; pub const DAQmxErrorExtCalConstsInvalid: i32 = -200437; pub const DAQmxErrorStartTrigDelayWithExtSampClk: i32 = -200436; pub const DAQmxErrorDelayFromSampClkWithExtConv: i32 = -200435; pub const DAQmxErrorFewerThan2PreScaledVals: i32 = -200434; pub const DAQmxErrorFewerThan2ScaledValues: i32 = -200433; pub const DAQmxErrorPhysChanOutputType: i32 = -200432; pub const DAQmxErrorPhysChanMeasType: i32 = -200431; pub const DAQmxErrorInvalidPhysChanType: i32 = -200430; pub const DAQmxErrorLabVIEWEmptyTaskOrChans: i32 = -200429; pub const DAQmxErrorLabVIEWInvalidTaskOrChans: i32 = -200428; pub const DAQmxErrorInvalidRefClkRate: i32 = -200427; pub const DAQmxErrorInvalidExtTrigImpedance: i32 = -200426; pub const DAQmxErrorHystTrigLevelAIMax: i32 = -200425; pub const DAQmxErrorLineNumIncompatibleWithVideoSignalFormat: i32 = -200424; pub const DAQmxErrorTrigWindowAIMinAIMaxCombo: i32 = -200423; pub const DAQmxErrorTrigAIMinAIMax: i32 = -200422; pub const DAQmxErrorHystTrigLevelAIMin: i32 = -200421; pub const DAQmxErrorInvalidSampRateConsiderRIS: i32 = -200420; pub const DAQmxErrorInvalidReadPosDuringRIS: i32 = -200419; pub const DAQmxErrorImmedTrigDuringRISMode: i32 = -200418; pub const DAQmxErrorTDCNotEnabledDuringRISMode: i32 = -200417; pub const DAQmxErrorMultiRecWithRIS: i32 = -200416; pub const DAQmxErrorInvalidRefClkSrc: i32 = -200415; pub const DAQmxErrorInvalidSampClkSrc: i32 = -200414; pub const DAQmxErrorInsufficientOnBoardMemForNumRecsAndSamps: i32 = -200413; pub const DAQmxErrorInvalidAIAttenuation: i32 = -200412; pub const DAQmxErrorACCouplingNotAllowedWith50OhmImpedance: i32 = -200411; pub const DAQmxErrorInvalidRecordNum: i32 = -200410; pub const DAQmxErrorZeroSlopeLinearScale: i32 = -200409; pub const DAQmxErrorZeroReversePolyScaleCoeffs: i32 = -200408; pub const DAQmxErrorZeroForwardPolyScaleCoeffs: i32 = -200407; pub const DAQmxErrorNoReversePolyScaleCoeffs: i32 = -200406; pub const DAQmxErrorNoForwardPolyScaleCoeffs: i32 = -200405; pub const DAQmxErrorNoPolyScaleCoeffs: i32 = -200404; pub const DAQmxErrorReversePolyOrderLessThanNumPtsToCompute: i32 = -200403; pub const DAQmxErrorReversePolyOrderNotPositive: i32 = -200402; pub const DAQmxErrorNumPtsToComputeNotPositive: i32 = -200401; pub const DAQmxErrorWaveformLengthNotMultipleOfIncr: i32 = -200400; pub const DAQmxErrorCAPINoExtendedErrorInfoAvailable: i32 = -200399; pub const DAQmxErrorCVIFunctionNotFoundInDAQmxDLL: i32 = -200398; pub const DAQmxErrorCVIFailedToLoadDAQmxDLL: i32 = -200397; pub const DAQmxErrorNoCommonTrigLineForImmedRoute: i32 = -200396; pub const DAQmxErrorNoCommonTrigLineForTaskRoute: i32 = -200395; pub const DAQmxErrorF64PrptyValNotUnsignedInt: i32 = -200394; pub const DAQmxErrorRegisterNotWritable: i32 = -200393; pub const DAQmxErrorInvalidOutputVoltageAtSampClkRate: i32 = -200392; pub const DAQmxErrorStrobePhaseShiftDCMBecameUnlocked: i32 = -200391; pub const DAQmxErrorDrivePhaseShiftDCMBecameUnlocked: i32 = -200390; pub const DAQmxErrorClkOutPhaseShiftDCMBecameUnlocked: i32 = -200389; pub const DAQmxErrorOutputBoardClkDCMBecameUnlocked: i32 = -200388; pub const DAQmxErrorInputBoardClkDCMBecameUnlocked: i32 = -200387; pub const DAQmxErrorInternalClkDCMBecameUnlocked: i32 = -200386; pub const DAQmxErrorDCMLock: i32 = -200385; pub const DAQmxErrorDataLineReservedForDynamicOutput: i32 = -200384; pub const DAQmxErrorInvalidRefClkSrcGivenSampClkSrc: i32 = -200383; pub const DAQmxErrorNoPatternMatcherAvailable: i32 = -200382; pub const DAQmxErrorInvalidDelaySampRateBelowPhaseShiftDCMThresh: i32 = -200381; pub const DAQmxErrorStrainGageCalibration: i32 = -200380; pub const DAQmxErrorInvalidExtClockFreqAndDivCombo: i32 = -200379; pub const DAQmxErrorCustomScaleDoesNotExist: i32 = -200378; pub const DAQmxErrorOnlyFrontEndChanOpsDuringScan: i32 = -200377; pub const DAQmxErrorInvalidOptionForDigitalPortChannel: i32 = -200376; pub const DAQmxErrorUnsupportedSignalTypeExportSignal: i32 = -200375; pub const DAQmxErrorInvalidSignalTypeExportSignal: i32 = -200374; pub const DAQmxErrorUnsupportedTrigTypeSendsSWTrig: i32 = -200373; pub const DAQmxErrorInvalidTrigTypeSendsSWTrig: i32 = -200372; pub const DAQmxErrorRepeatedPhysicalChan: i32 = -200371; pub const DAQmxErrorResourcesInUseForRouteInTask: i32 = -200370; pub const DAQmxErrorResourcesInUseForRoute: i32 = -200369; pub const DAQmxErrorRouteNotSupportedByHW: i32 = -200368; pub const DAQmxErrorResourcesInUseForExportSignalPolarity: i32 = -200367; pub const DAQmxErrorResourcesInUseForInversionInTask: i32 = -200366; pub const DAQmxErrorResourcesInUseForInversion: i32 = -200365; pub const DAQmxErrorExportSignalPolarityNotSupportedByHW: i32 = -200364; pub const DAQmxErrorInversionNotSupportedByHW: i32 = -200363; pub const DAQmxErrorOverloadedChansExistNotRead: i32 = -200362; pub const DAQmxErrorInputFIFOOverflow2: i32 = -200361; pub const DAQmxErrorCJCChanNotSpecd: i32 = -200360; pub const DAQmxErrorCtrExportSignalNotPossible: i32 = -200359; pub const DAQmxErrorRefTrigWhenContinuous: i32 = -200358; pub const DAQmxErrorIncompatibleSensorOutputAndDeviceInputRanges: i32 = -200357; pub const DAQmxErrorCustomScaleNameUsed: i32 = -200356; pub const DAQmxErrorPropertyValNotSupportedByHW: i32 = -200355; pub const DAQmxErrorPropertyValNotValidTermName: i32 = -200354; pub const DAQmxErrorResourcesInUseForProperty: i32 = -200353; pub const DAQmxErrorCJCChanAlreadyUsed: i32 = -200352; pub const DAQmxErrorForwardPolynomialCoefNotSpecd: i32 = -200351; pub const DAQmxErrorTableScaleNumPreScaledAndScaledValsNotEqual: i32 = -200350; pub const DAQmxErrorTableScalePreScaledValsNotSpecd: i32 = -200349; pub const DAQmxErrorTableScaleScaledValsNotSpecd: i32 = -200348; pub const DAQmxErrorIntermediateBufferSizeNotMultipleOfIncr: i32 = -200347; pub const DAQmxErrorEventPulseWidthOutOfRange: i32 = -200346; pub const DAQmxErrorEventDelayOutOfRange: i32 = -200345; pub const DAQmxErrorSampPerChanNotMultipleOfIncr: i32 = -200344; pub const DAQmxErrorCannotCalculateNumSampsTaskNotStarted: i32 = -200343; pub const DAQmxErrorScriptNotInMem: i32 = -200342; pub const DAQmxErrorOnboardMemTooSmall: i32 = -200341; pub const DAQmxErrorReadAllAvailableDataWithoutBuffer: i32 = -200340; pub const DAQmxErrorPulseActiveAtStart: i32 = -200339; pub const DAQmxErrorCalTempNotSupported: i32 = -200338; pub const DAQmxErrorDelayFromSampClkTooLong: i32 = -200337; pub const DAQmxErrorDelayFromSampClkTooShort: i32 = -200336; pub const DAQmxErrorAIConvRateTooHigh: i32 = -200335; pub const DAQmxErrorDelayFromStartTrigTooLong: i32 = -200334; pub const DAQmxErrorDelayFromStartTrigTooShort: i32 = -200333; pub const DAQmxErrorSampRateTooHigh: i32 = -200332; pub const DAQmxErrorSampRateTooLow: i32 = -200331; pub const DAQmxErrorPFI0UsedForAnalogAndDigitalSrc: i32 = -200330; pub const DAQmxErrorPrimingCfgFIFO: i32 = -200329; pub const DAQmxErrorCannotOpenTopologyCfgFile: i32 = -200328; pub const DAQmxErrorInvalidDTInsideWfmDataType: i32 = -200327; pub const DAQmxErrorRouteSrcAndDestSame: i32 = -200326; pub const DAQmxErrorReversePolynomialCoefNotSpecd: i32 = -200325; pub const DAQmxErrorDevAbsentOrUnavailable: i32 = -200324; pub const DAQmxErrorNoAdvTrigForMultiDevScan: i32 = -200323; pub const DAQmxErrorInterruptsInsufficientDataXferMech: i32 = -200322; pub const DAQmxErrorInvalidAttentuationBasedOnMinMax: i32 = -200321; pub const DAQmxErrorCabledModuleCannotRouteSSH: i32 = -200320; pub const DAQmxErrorCabledModuleCannotRouteConvClk: i32 = -200319; pub const DAQmxErrorInvalidExcitValForScaling: i32 = -200318; pub const DAQmxErrorNoDevMemForScript: i32 = -200317; pub const DAQmxErrorScriptDataUnderflow: i32 = -200316; pub const DAQmxErrorNoDevMemForWaveform: i32 = -200315; pub const DAQmxErrorStreamDCMBecameUnlocked: i32 = -200314; pub const DAQmxErrorStreamDCMLock: i32 = -200313; pub const DAQmxErrorWaveformNotInMem: i32 = -200312; pub const DAQmxErrorWaveformWriteOutOfBounds: i32 = -200311; pub const DAQmxErrorWaveformPreviouslyAllocated: i32 = -200310; pub const DAQmxErrorSampClkTbMasterTbDivNotAppropriateForSampTbSrc: i32 = -200309; pub const DAQmxErrorSampTbRateSampTbSrcMismatch: i32 = -200308; pub const DAQmxErrorMasterTbRateMasterTbSrcMismatch: i32 = -200307; pub const DAQmxErrorSampsPerChanTooBig: i32 = -200306; pub const DAQmxErrorFinitePulseTrainNotPossible: i32 = -200305; pub const DAQmxErrorExtMasterTimebaseRateNotSpecified: i32 = -200304; pub const DAQmxErrorExtSampClkSrcNotSpecified: i32 = -200303; pub const DAQmxErrorInputSignalSlowerThanMeasTime: i32 = -200302; pub const DAQmxErrorCannotUpdatePulseGenProperty: i32 = -200301; pub const DAQmxErrorInvalidTimingType: i32 = -200300; pub const DAQmxErrorPropertyUnavailWhenUsingOnboardMemory: i32 = -200297; pub const DAQmxErrorCannotWriteAfterStartWithOnboardMemory: i32 = -200295; pub const DAQmxErrorNotEnoughSampsWrittenForInitialXferRqstCondition: i32 = -200294; pub const DAQmxErrorNoMoreSpace: i32 = -200293; pub const DAQmxErrorSamplesCanNotYetBeWritten: i32 = -200292; pub const DAQmxErrorGenStoppedToPreventIntermediateBufferRegenOfOldSamples: i32 = -200291; pub const DAQmxErrorGenStoppedToPreventRegenOfOldSamples: i32 = -200290; pub const DAQmxErrorSamplesNoLongerWriteable: i32 = -200289; pub const DAQmxErrorSamplesWillNeverBeGenerated: i32 = -200288; pub const DAQmxErrorNegativeWriteSampleNumber: i32 = -200287; pub const DAQmxErrorNoAcqStarted: i32 = -200286; pub const DAQmxErrorSamplesNotYetAvailable: i32 = -200284; pub const DAQmxErrorAcqStoppedToPreventIntermediateBufferOverflow: i32 = -200283; pub const DAQmxErrorNoRefTrigConfigured: i32 = -200282; pub const DAQmxErrorCannotReadRelativeToRefTrigUntilDone: i32 = -200281; pub const DAQmxErrorSamplesNoLongerAvailable: i32 = -200279; pub const DAQmxErrorSamplesWillNeverBeAvailable: i32 = -200278; pub const DAQmxErrorNegativeReadSampleNumber: i32 = -200277; pub const DAQmxErrorExternalSampClkAndRefClkThruSameTerm: i32 = -200276; pub const DAQmxErrorExtSampClkRateTooLowForClkIn: i32 = -200275; pub const DAQmxErrorExtSampClkRateTooHighForBackplane: i32 = -200274; pub const DAQmxErrorSampClkRateAndDivCombo: i32 = -200273; pub const DAQmxErrorSampClkRateTooLowForDivDown: i32 = -200272; pub const DAQmxErrorProductOfAOMinAndGainTooSmall: i32 = -200271; pub const DAQmxErrorInterpolationRateNotPossible: i32 = -200270; pub const DAQmxErrorOffsetTooLarge: i32 = -200269; pub const DAQmxErrorOffsetTooSmall: i32 = -200268; pub const DAQmxErrorProductOfAOMaxAndGainTooLarge: i32 = -200267; pub const DAQmxErrorMinAndMaxNotSymmetric: i32 = -200266; pub const DAQmxErrorInvalidAnalogTrigSrc: i32 = -200265; pub const DAQmxErrorTooManyChansForAnalogRefTrig: i32 = -200264; pub const DAQmxErrorTooManyChansForAnalogPauseTrig: i32 = -200263; pub const DAQmxErrorTrigWhenOnDemandSampTiming: i32 = -200262; pub const DAQmxErrorInconsistentAnalogTrigSettings: i32 = -200261; pub const DAQmxErrorMemMapDataXferModeSampTimingCombo: i32 = -200260; pub const DAQmxErrorInvalidJumperedAttr: i32 = -200259; pub const DAQmxErrorInvalidGainBasedOnMinMax: i32 = -200258; pub const DAQmxErrorInconsistentExcit: i32 = -200257; pub const DAQmxErrorTopologyNotSupportedByCfgTermBlock: i32 = -200256; pub const DAQmxErrorBuiltInTempSensorNotSupported: i32 = -200255; pub const DAQmxErrorInvalidTerm: i32 = -200254; pub const DAQmxErrorCannotTristateTerm: i32 = -200253; pub const DAQmxErrorCannotTristateBusyTerm: i32 = -200252; pub const DAQmxErrorNoDMAChansAvailable: i32 = -200251; pub const DAQmxErrorInvalidWaveformLengthWithinLoopInScript: i32 = -200250; pub const DAQmxErrorInvalidSubsetLengthWithinLoopInScript: i32 = -200249; pub const DAQmxErrorMarkerPosInvalidForLoopInScript: i32 = -200248; pub const DAQmxErrorIntegerExpectedInScript: i32 = -200247; pub const DAQmxErrorPLLBecameUnlocked: i32 = -200246; pub const DAQmxErrorPLLLock: i32 = -200245; pub const DAQmxErrorDDCClkOutDCMBecameUnlocked: i32 = -200244; pub const DAQmxErrorDDCClkOutDCMLock: i32 = -200243; pub const DAQmxErrorClkDoublerDCMBecameUnlocked: i32 = -200242; pub const DAQmxErrorClkDoublerDCMLock: i32 = -200241; pub const DAQmxErrorSampClkDCMBecameUnlocked: i32 = -200240; pub const DAQmxErrorSampClkDCMLock: i32 = -200239; pub const DAQmxErrorSampClkTimebaseDCMBecameUnlocked: i32 = -200238; pub const DAQmxErrorSampClkTimebaseDCMLock: i32 = -200237; pub const DAQmxErrorAttrCannotBeReset: i32 = -200236; pub const DAQmxErrorExplanationNotFound: i32 = -200235; pub const DAQmxErrorWriteBufferTooSmall: i32 = -200234; pub const DAQmxErrorSpecifiedAttrNotValid: i32 = -200233; pub const DAQmxErrorAttrCannotBeRead: i32 = -200232; pub const DAQmxErrorAttrCannotBeSet: i32 = -200231; pub const DAQmxErrorNULLPtrForC_Api: i32 = -200230; pub const DAQmxErrorReadBufferTooSmall: i32 = -200229; pub const DAQmxErrorBufferTooSmallForString: i32 = -200228; pub const DAQmxErrorNoAvailTrigLinesOnDevice: i32 = -200227; pub const DAQmxErrorTrigBusLineNotAvail: i32 = -200226; pub const DAQmxErrorCouldNotReserveRequestedTrigLine: i32 = -200225; pub const DAQmxErrorTrigLineNotFound: i32 = -200224; pub const DAQmxErrorSCXI1126ThreshHystCombination: i32 = -200223; pub const DAQmxErrorAcqStoppedToPreventInputBufferOverwrite: i32 = -200222; pub const DAQmxErrorTimeoutExceeded: i32 = -200221; pub const DAQmxErrorInvalidDeviceID: i32 = -200220; pub const DAQmxErrorInvalidAOChanOrder: i32 = -200219; pub const DAQmxErrorSampleTimingTypeAndDataXferMode: i32 = -200218; pub const DAQmxErrorBufferWithOnDemandSampTiming: i32 = -200217; pub const DAQmxErrorBufferAndDataXferMode: i32 = -200216; pub const DAQmxErrorMemMapAndBuffer: i32 = -200215; pub const DAQmxErrorNoAnalogTrigHW: i32 = -200214; pub const DAQmxErrorTooManyPretrigPlusMinPostTrigSamps: i32 = -200213; pub const DAQmxErrorInconsistentUnitsSpecified: i32 = -200212; pub const DAQmxErrorMultipleRelaysForSingleRelayOp: i32 = -200211; pub const DAQmxErrorMultipleDevIDsPerChassisSpecifiedInList: i32 = -200210; pub const DAQmxErrorDuplicateDevIDInList: i32 = -200209; pub const DAQmxErrorInvalidRangeStatementCharInList: i32 = -200208; pub const DAQmxErrorInvalidDeviceIDInList: i32 = -200207; pub const DAQmxErrorTriggerPolarityConflict: i32 = -200206; pub const DAQmxErrorCannotScanWithCurrentTopology: i32 = -200205; pub const DAQmxErrorUnexpectedIdentifierInFullySpecifiedPathInList: i32 = -200204; pub const DAQmxErrorSwitchCannotDriveMultipleTrigLines: i32 = -200203; pub const DAQmxErrorInvalidRelayName: i32 = -200202; pub const DAQmxErrorSwitchScanlistTooBig: i32 = -200201; pub const DAQmxErrorSwitchChanInUse: i32 = -200200; pub const DAQmxErrorSwitchNotResetBeforeScan: i32 = -200199; pub const DAQmxErrorInvalidTopology: i32 = -200198; pub const DAQmxErrorAttrNotSupported: i32 = -200197; pub const DAQmxErrorUnexpectedEndOfActionsInList: i32 = -200196; pub const DAQmxErrorPowerLimitExceeded: i32 = -200195; pub const DAQmxErrorHWUnexpectedlyPoweredOffAndOn: i32 = -200194; pub const DAQmxErrorSwitchOperationNotSupported: i32 = -200193; pub const DAQmxErrorOnlyContinuousScanSupported: i32 = -200192; pub const DAQmxErrorSwitchDifferentTopologyWhenScanning: i32 = -200191; pub const DAQmxErrorDisconnectPathNotSameAsExistingPath: i32 = -200190; pub const DAQmxErrorConnectionNotPermittedOnChanReservedForRouting: i32 = -200189; pub const DAQmxErrorCannotConnectSrcChans: i32 = -200188; pub const DAQmxErrorCannotConnectChannelToItself: i32 = -200187; pub const DAQmxErrorChannelNotReservedForRouting: i32 = -200186; pub const DAQmxErrorCannotConnectChansDirectly: i32 = -200185; pub const DAQmxErrorChansAlreadyConnected: i32 = -200184; pub const DAQmxErrorChanDuplicatedInPath: i32 = -200183; pub const DAQmxErrorNoPathToDisconnect: i32 = -200182; pub const DAQmxErrorInvalidSwitchChan: i32 = -200181; pub const DAQmxErrorNoPathAvailableBetween2SwitchChans: i32 = -200180; pub const DAQmxErrorExplicitConnectionExists: i32 = -200179; pub const DAQmxErrorSwitchDifferentSettlingTimeWhenScanning: i32 = -200178; pub const DAQmxErrorOperationOnlyPermittedWhileScanning: i32 = -200177; pub const DAQmxErrorOperationNotPermittedWhileScanning: i32 = -200176; pub const DAQmxErrorHardwareNotResponding: i32 = -200175; pub const DAQmxErrorInvalidSampAndMasterTimebaseRateCombo: i32 = -200173; pub const DAQmxErrorNonZeroBufferSizeInProgIOXfer: i32 = -200172; pub const DAQmxErrorVirtualChanNameUsed: i32 = -200171; pub const DAQmxErrorPhysicalChanDoesNotExist: i32 = -200170; pub const DAQmxErrorMemMapOnlyForProgIOXfer: i32 = -200169; pub const DAQmxErrorTooManyChans: i32 = -200168; pub const DAQmxErrorCannotHaveCJTempWithOtherChans: i32 = -200167; pub const DAQmxErrorOutputBufferUnderwrite: i32 = -200166; pub const DAQmxErrorSensorInvalidCompletionResistance: i32 = -200163; pub const DAQmxErrorVoltageExcitIncompatibleWith2WireCfg: i32 = -200162; pub const DAQmxErrorIntExcitSrcNotAvailable: i32 = -200161; pub const DAQmxErrorCannotCreateChannelAfterTaskVerified: i32 = -200160; pub const DAQmxErrorLinesReservedForSCXIControl: i32 = -200159; pub const DAQmxErrorCouldNotReserveLinesForSCXIControl: i32 = -200158; pub const DAQmxErrorCalibrationFailed: i32 = -200157; pub const DAQmxErrorReferenceFrequencyInvalid: i32 = -200156; pub const DAQmxErrorReferenceResistanceInvalid: i32 = -200155; pub const DAQmxErrorReferenceCurrentInvalid: i32 = -200154; pub const DAQmxErrorReferenceVoltageInvalid: i32 = -200153; pub const DAQmxErrorEEPROMDataInvalid: i32 = -200152; pub const DAQmxErrorCabledModuleNotCapableOfRoutingAI: i32 = -200151; pub const DAQmxErrorChannelNotAvailableInParallelMode: i32 = -200150; pub const DAQmxErrorExternalTimebaseRateNotKnownForDelay: i32 = -200149; pub const DAQmxErrorFREQOUTCannotProduceDesiredFrequency: i32 = -200148; pub const DAQmxErrorMultipleCounterInputTask: i32 = -200147; pub const DAQmxErrorCounterStartPauseTriggerConflict: i32 = -200146; pub const DAQmxErrorCounterInputPauseTriggerAndSampleClockInvalid: i32 = -200145; pub const DAQmxErrorCounterOutputPauseTriggerInvalid: i32 = -200144; pub const DAQmxErrorCounterTimebaseRateNotSpecified: i32 = -200143; pub const DAQmxErrorCounterTimebaseRateNotFound: i32 = -200142; pub const DAQmxErrorCounterOverflow: i32 = -200141; pub const DAQmxErrorCounterNoTimebaseEdgesBetweenGates: i32 = -200140; pub const DAQmxErrorCounterMaxMinRangeFreq: i32 = -200139; pub const DAQmxErrorCounterMaxMinRangeTime: i32 = -200138; pub const DAQmxErrorSuitableTimebaseNotFoundTimeCombo: i32 = -200137; pub const DAQmxErrorSuitableTimebaseNotFoundFrequencyCombo: i32 = -200136; pub const DAQmxErrorInternalTimebaseSourceDivisorCombo: i32 = -200135; pub const DAQmxErrorInternalTimebaseSourceRateCombo: i32 = -200134; pub const DAQmxErrorInternalTimebaseRateDivisorSourceCombo: i32 = -200133; pub const DAQmxErrorExternalTimebaseRateNotknownForRate: i32 = -200132; pub const DAQmxErrorAnalogTrigChanNotFirstInScanList: i32 = -200131; pub const DAQmxErrorNoDivisorForExternalSignal: i32 = -200130; pub const DAQmxErrorAttributeInconsistentAcrossRepeatedPhysicalChannels: i32 = -200128; pub const DAQmxErrorCannotHandshakeWithPort0: i32 = -200127; pub const DAQmxErrorControlLineConflictOnPortC: i32 = -200126; pub const DAQmxErrorLines4To7ConfiguredForOutput: i32 = -200125; pub const DAQmxErrorLines4To7ConfiguredForInput: i32 = -200124; pub const DAQmxErrorLines0To3ConfiguredForOutput: i32 = -200123; pub const DAQmxErrorLines0To3ConfiguredForInput: i32 = -200122; pub const DAQmxErrorPortConfiguredForOutput: i32 = -200121; pub const DAQmxErrorPortConfiguredForInput: i32 = -200120; pub const DAQmxErrorPortConfiguredForStaticDigitalOps: i32 = -200119; pub const DAQmxErrorPortReservedForHandshaking: i32 = -200118; pub const DAQmxErrorPortDoesNotSupportHandshakingDataIO: i32 = -200117; pub const DAQmxErrorCannotTristate8255OutputLines: i32 = -200116; pub const DAQmxErrorTemperatureOutOfRangeForCalibration: i32 = -200113; pub const DAQmxErrorCalibrationHandleInvalid: i32 = -200112; pub const DAQmxErrorPasswordRequired: i32 = -200111; pub const DAQmxErrorIncorrectPassword: i32 = -200110; pub const DAQmxErrorPasswordTooLong: i32 = -200109; pub const DAQmxErrorCalibrationSessionAlreadyOpen: i32 = -200108; pub const DAQmxErrorSCXIModuleIncorrect: i32 = -200107; pub const DAQmxErrorAttributeInconsistentAcrossChannelsOnDevice: i32 = -200106; pub const DAQmxErrorSCXI1122ResistanceChanNotSupportedForCfg: i32 = -200105; pub const DAQmxErrorBracketPairingMismatchInList: i32 = -200104; pub const DAQmxErrorInconsistentNumSamplesToWrite: i32 = -200103; pub const DAQmxErrorIncorrectDigitalPattern: i32 = -200102; pub const DAQmxErrorIncorrectNumChannelsToWrite: i32 = -200101; pub const DAQmxErrorIncorrectReadFunction: i32 = -200100; pub const DAQmxErrorPhysicalChannelNotSpecified: i32 = -200099; pub const DAQmxErrorMoreThanOneTerminal: i32 = -200098; pub const DAQmxErrorMoreThanOneActiveChannelSpecified: i32 = -200097; pub const DAQmxErrorInvalidNumberSamplesToRead: i32 = -200096; pub const DAQmxErrorAnalogWaveformExpected: i32 = -200095; pub const DAQmxErrorDigitalWaveformExpected: i32 = -200094; pub const DAQmxErrorActiveChannelNotSpecified: i32 = -200093; pub const DAQmxErrorFunctionNotSupportedForDeviceTasks: i32 = -200092; pub const DAQmxErrorFunctionNotInLibrary: i32 = -200091; pub const DAQmxErrorLibraryNotPresent: i32 = -200090; pub const DAQmxErrorDuplicateTask: i32 = -200089; pub const DAQmxErrorInvalidTask: i32 = -200088; pub const DAQmxErrorInvalidChannel: i32 = -200087; pub const DAQmxErrorInvalidSyntaxForPhysicalChannelRange: i32 = -200086; pub const DAQmxErrorMinNotLessThanMax: i32 = -200082; pub const DAQmxErrorSampleRateNumChansConvertPeriodCombo: i32 = -200081; pub const DAQmxErrorAODuringCounter1DMAConflict: i32 = -200079; pub const DAQmxErrorAIDuringCounter0DMAConflict: i32 = -200078; pub const DAQmxErrorInvalidAttributeValue: i32 = -200077; pub const DAQmxErrorSuppliedCurrentDataOutsideSpecifiedRange: i32 = -200076; pub const DAQmxErrorSuppliedVoltageDataOutsideSpecifiedRange: i32 = -200075; pub const DAQmxErrorCannotStoreCalConst: i32 = -200074; pub const DAQmxErrorSCXIModuleNotFound: i32 = -200073; pub const DAQmxErrorDuplicatePhysicalChansNotSupported: i32 = -200072; pub const DAQmxErrorTooManyPhysicalChansInList: i32 = -200071; pub const DAQmxErrorInvalidAdvanceEventTriggerType: i32 = -200070; pub const DAQmxErrorDeviceIsNotAValidSwitch: i32 = -200069; pub const DAQmxErrorDeviceDoesNotSupportScanning: i32 = -200068; pub const DAQmxErrorScanListCannotBeTimed: i32 = -200067; pub const DAQmxErrorConnectOperatorInvalidAtPointInList: i32 = -200066; pub const DAQmxErrorUnexpectedSwitchActionInList: i32 = -200065; pub const DAQmxErrorUnexpectedSeparatorInList: i32 = -200064; pub const DAQmxErrorExpectedTerminatorInList: i32 = -200063; pub const DAQmxErrorExpectedConnectOperatorInList: i32 = -200062; pub const DAQmxErrorExpectedSeparatorInList: i32 = -200061; pub const DAQmxErrorFullySpecifiedPathInListContainsRange: i32 = -200060; pub const DAQmxErrorConnectionSeparatorAtEndOfList: i32 = -200059; pub const DAQmxErrorIdentifierInListTooLong: i32 = -200058; pub const DAQmxErrorDuplicateDeviceIDInListWhenSettling: i32 = -200057; pub const DAQmxErrorChannelNameNotSpecifiedInList: i32 = -200056; pub const DAQmxErrorDeviceIDNotSpecifiedInList: i32 = -200055; pub const DAQmxErrorSemicolonDoesNotFollowRangeInList: i32 = -200054; pub const DAQmxErrorSwitchActionInListSpansMultipleDevices: i32 = -200053; pub const DAQmxErrorRangeWithoutAConnectActionInList: i32 = -200052; pub const DAQmxErrorInvalidIdentifierFollowingSeparatorInList: i32 = -200051; pub const DAQmxErrorInvalidChannelNameInList: i32 = -200050; pub const DAQmxErrorInvalidNumberInRepeatStatementInList: i32 = -200049; pub const DAQmxErrorInvalidTriggerLineInList: i32 = -200048; pub const DAQmxErrorInvalidIdentifierInListFollowingDeviceID: i32 = -200047; pub const DAQmxErrorInvalidIdentifierInListAtEndOfSwitchAction: i32 = -200046; pub const DAQmxErrorDeviceRemoved: i32 = -200045; pub const DAQmxErrorRoutingPathNotAvailable: i32 = -200044; pub const DAQmxErrorRoutingHardwareBusy: i32 = -200043; pub const DAQmxErrorRequestedSignalInversionForRoutingNotPossible: i32 = -200042; pub const DAQmxErrorInvalidRoutingDestinationTerminalName: i32 = -200041; pub const DAQmxErrorInvalidRoutingSourceTerminalName: i32 = -200040; pub const DAQmxErrorRoutingNotSupportedForDevice: i32 = -200039; pub const DAQmxErrorWaitIsLastInstructionOfLoopInScript: i32 = -200038; pub const DAQmxErrorClearIsLastInstructionOfLoopInScript: i32 = -200037; pub const DAQmxErrorInvalidLoopIterationsInScript: i32 = -200036; pub const DAQmxErrorRepeatLoopNestingTooDeepInScript: i32 = -200035; pub const DAQmxErrorMarkerPositionOutsideSubsetInScript: i32 = -200034; pub const DAQmxErrorSubsetStartOffsetNotAlignedInScript: i32 = -200033; pub const DAQmxErrorInvalidSubsetLengthInScript: i32 = -200032; pub const DAQmxErrorMarkerPositionNotAlignedInScript: i32 = -200031; pub const DAQmxErrorSubsetOutsideWaveformInScript: i32 = -200030; pub const DAQmxErrorMarkerOutsideWaveformInScript: i32 = -200029; pub const DAQmxErrorWaveformInScriptNotInMem: i32 = -200028; pub const DAQmxErrorKeywordExpectedInScript: i32 = -200027; pub const DAQmxErrorBufferNameExpectedInScript: i32 = -200026; pub const DAQmxErrorProcedureNameExpectedInScript: i32 = -200025; pub const DAQmxErrorScriptHasInvalidIdentifier: i32 = -200024; pub const DAQmxErrorScriptHasInvalidCharacter: i32 = -200023; pub const DAQmxErrorResourceAlreadyReserved: i32 = -200022; pub const DAQmxErrorSelfTestFailed: i32 = -200020; pub const DAQmxErrorADCOverrun: i32 = -200019; pub const DAQmxErrorDACUnderflow: i32 = -200018; pub const DAQmxErrorInputFIFOUnderflow: i32 = -200017; pub const DAQmxErrorOutputFIFOUnderflow: i32 = -200016; pub const DAQmxErrorSCXISerialCommunication: i32 = -200015; pub const DAQmxErrorDigitalTerminalSpecifiedMoreThanOnce: i32 = -200014; pub const DAQmxErrorDigitalOutputNotSupported: i32 = -200012; pub const DAQmxErrorInconsistentChannelDirections: i32 = -200011; pub const DAQmxErrorInputFIFOOverflow: i32 = -200010; pub const DAQmxErrorTimeStampOverwritten: i32 = -200009; pub const DAQmxErrorStopTriggerHasNotOccurred: i32 = -200008; pub const DAQmxErrorRecordNotAvailable: i32 = -200007; pub const DAQmxErrorRecordOverwritten: i32 = -200006; pub const DAQmxErrorDataNotAvailable: i32 = -200005; pub const DAQmxErrorDataOverwrittenInDeviceMemory: i32 = -200004; pub const DAQmxErrorDuplicatedChannel: i32 = -200003; pub const DAQmxWarningTimestampCounterRolledOver: u32 = 200003; pub const DAQmxWarningInputTerminationOverloaded: u32 = 200004; pub const DAQmxWarningADCOverloaded: u32 = 200005; pub const DAQmxWarningPLLUnlocked: u32 = 200007; pub const DAQmxWarningCounter0DMADuringAIConflict: u32 = 200008; pub const DAQmxWarningCounter1DMADuringAOConflict: u32 = 200009; pub const DAQmxWarningStoppedBeforeDone: u32 = 200010; pub const DAQmxWarningRateViolatesSettlingTime: u32 = 200011; pub const DAQmxWarningRateViolatesMaxADCRate: u32 = 200012; pub const DAQmxWarningUserDefInfoStringTooLong: u32 = 200013; pub const DAQmxWarningTooManyInterruptsPerSecond: u32 = 200014; pub const DAQmxWarningPotentialGlitchDuringWrite: u32 = 200015; pub const DAQmxWarningDevNotSelfCalibratedWithDAQmx: u32 = 200016; pub const DAQmxWarningAISampRateTooLow: u32 = 200017; pub const DAQmxWarningAIConvRateTooLow: u32 = 200018; pub const DAQmxWarningReadOffsetCoercion: u32 = 200019; pub const DAQmxWarningPretrigCoercion: u32 = 200020; pub const DAQmxWarningSampValCoercedToMax: u32 = 200021; pub const DAQmxWarningSampValCoercedToMin: u32 = 200022; pub const DAQmxWarningPropertyVersionNew: u32 = 200024; pub const DAQmxWarningUserDefinedInfoTooLong: u32 = 200025; pub const DAQmxWarningCAPIStringTruncatedToFitBuffer: u32 = 200026; pub const DAQmxWarningSampClkRateTooLow: u32 = 200027; pub const DAQmxWarningPossiblyInvalidCTRSampsInFiniteDMAAcq: u32 = 200028; pub const DAQmxWarningRISAcqCompletedSomeBinsNotFilled: u32 = 200029; pub const DAQmxWarningPXIDevTempExceedsMaxOpTemp: u32 = 200030; pub const DAQmxWarningOutputGainTooLowForRFFreq: u32 = 200031; pub const DAQmxWarningOutputGainTooHighForRFFreq: u32 = 200032; pub const DAQmxWarningMultipleWritesBetweenSampClks: u32 = 200033; pub const DAQmxWarningDeviceMayShutDownDueToHighTemp: u32 = 200034; pub const DAQmxWarningRateViolatesMinADCRate: u32 = 200035; pub const DAQmxWarningSampClkRateAboveDevSpecs: u32 = 200036; pub const DAQmxWarningCOPrevDAQmxWriteSettingsOverwrittenForHWTimedSinglePoint: u32 = 200037; pub const DAQmxWarningLowpassFilterSettlingTimeExceedsUserTimeBetween2ADCConversions: u32 = 200038; pub const DAQmxWarningLowpassFilterSettlingTimeExceedsDriverTimeBetween2ADCConversions: u32 = 200039; pub const DAQmxWarningSampClkRateViolatesSettlingTimeForGen: u32 = 200040; pub const DAQmxWarningInvalidCalConstValueForAI: u32 = 200041; pub const DAQmxWarningInvalidCalConstValueForAO: u32 = 200042; pub const DAQmxWarningChanCalExpired: u32 = 200043; pub const DAQmxWarningUnrecognizedEnumValueEncounteredInStorage: u32 = 200044; pub const DAQmxWarningTableCRCNotCorrect: u32 = 200045; pub const DAQmxWarningExternalCRCNotCorrect: u32 = 200046; pub const DAQmxWarningSelfCalCRCNotCorrect: u32 = 200047; pub const DAQmxWarningDeviceSpecExceeded: u32 = 200048; pub const DAQmxWarningOnlyGainCalibrated: u32 = 200049; pub const DAQmxWarningReversePowerProtectionActivated: u32 = 200050; pub const DAQmxWarningOverVoltageProtectionActivated: u32 = 200051; pub const DAQmxWarningBufferSizeNotMultipleOfSectorSize: u32 = 200052; pub const DAQmxWarningSampleRateMayCauseAcqToFail: u32 = 200053; pub const DAQmxWarningUserAreaCRCNotCorrect: u32 = 200054; pub const DAQmxWarningPowerUpInfoCRCNotCorrect: u32 = 200055; pub const DAQmxWarningConnectionCountHasExceededRecommendedLimit: u32 = 200056; pub const DAQmxWarningNetworkDeviceAlreadyAdded: u32 = 200057; pub const DAQmxWarningAccessoryConnectionCountIsInvalid: u32 = 200058; pub const DAQmxWarningUnableToDisconnectPorts: u32 = 200059; pub const DAQmxWarningReadRepeatedData: u32 = 200060; pub const DAQmxWarningPXI5600_NotConfigured: u32 = 200061; pub const DAQmxWarningPXI5661_IncorrectlyConfigured: u32 = 200062; pub const DAQmxWarningPXIe5601_NotConfigured: u32 = 200063; pub const DAQmxWarningPXIe5663_IncorrectlyConfigured: u32 = 200064; pub const DAQmxWarningPXIe5663E_IncorrectlyConfigured: u32 = 200065; pub const DAQmxWarningPXIe5603_NotConfigured: u32 = 200066; pub const DAQmxWarningPXIe5665_5603_IncorrectlyConfigured: u32 = 200067; pub const DAQmxWarningPXIe5667_5603_IncorrectlyConfigured: u32 = 200068; pub const DAQmxWarningPXIe5605_NotConfigured: u32 = 200069; pub const DAQmxWarningPXIe5665_5605_IncorrectlyConfigured: u32 = 200070; pub const DAQmxWarningPXIe5667_5605_IncorrectlyConfigured: u32 = 200071; pub const DAQmxWarningPXIe5606_NotConfigured: u32 = 200072; pub const DAQmxWarningPXIe5665_5606_IncorrectlyConfigured: u32 = 200073; pub const DAQmxWarningPXI5610_NotConfigured: u32 = 200074; pub const DAQmxWarningPXI5610_IncorrectlyConfigured: u32 = 200075; pub const DAQmxWarningPXIe5611_NotConfigured: u32 = 200076; pub const DAQmxWarningPXIe5611_IncorrectlyConfigured: u32 = 200077; pub const DAQmxWarningUSBHotfixForDAQ: u32 = 200078; pub const DAQmxWarningNoChangeSupersededByIdleBehavior: u32 = 200079; pub const DAQmxWarningReadNotCompleteBeforeSampClk: u32 = 209800; pub const DAQmxWarningWriteNotCompleteBeforeSampClk: u32 = 209801; pub const DAQmxWarningWaitForNextSampClkDetectedMissedSampClk: u32 = 209802; pub const DAQmxWarningOutputDataTransferConditionNotSupported: u32 = 209803; pub const DAQmxWarningTimestampMayBeInvalid: u32 = 209804; pub const DAQmxWarningFirstSampleTimestampInaccurate: u32 = 209805; pub const DAQmxErrorInterfaceObsoleted_Routing: i32 = -89169; pub const DAQmxErrorRoCoServiceNotAvailable_Routing: i32 = -89168; pub const DAQmxErrorRoutingDestTermPXIDStarXNotInSystemTimingSlot_Routing: i32 = -89167; pub const DAQmxErrorRoutingSrcTermPXIDStarXNotInSystemTimingSlot_Routing: i32 = -89166; pub const DAQmxErrorRoutingSrcTermPXIDStarInNonDStarTriggerSlot_Routing: i32 = -89165; pub const DAQmxErrorRoutingDestTermPXIDStarInNonDStarTriggerSlot_Routing: i32 = -89164; pub const DAQmxErrorRoutingDestTermPXIClk10InNotInStarTriggerSlot_Routing: i32 = -89162; pub const DAQmxErrorRoutingDestTermPXIClk10InNotInSystemTimingSlot_Routing: i32 = -89161; pub const DAQmxErrorRoutingDestTermPXIStarXNotInStarTriggerSlot_Routing: i32 = -89160; pub const DAQmxErrorRoutingDestTermPXIStarXNotInSystemTimingSlot_Routing: i32 = -89159; pub const DAQmxErrorRoutingSrcTermPXIStarXNotInStarTriggerSlot_Routing: i32 = -89158; pub const DAQmxErrorRoutingSrcTermPXIStarXNotInSystemTimingSlot_Routing: i32 = -89157; pub const DAQmxErrorRoutingSrcTermPXIStarInNonStarTriggerSlot_Routing: i32 = -89156; pub const DAQmxErrorRoutingDestTermPXIStarInNonStarTriggerSlot_Routing: i32 = -89155; pub const DAQmxErrorRoutingDestTermPXIStarInStarTriggerSlot_Routing: i32 = -89154; pub const DAQmxErrorRoutingDestTermPXIStarInSystemTimingSlot_Routing: i32 = -89153; pub const DAQmxErrorRoutingSrcTermPXIStarInStarTriggerSlot_Routing: i32 = -89152; pub const DAQmxErrorRoutingSrcTermPXIStarInSystemTimingSlot_Routing: i32 = -89151; pub const DAQmxErrorInvalidSignalModifier_Routing: i32 = -89150; pub const DAQmxErrorRoutingDestTermPXIClk10InNotInSlot2_Routing: i32 = -89149; pub const DAQmxErrorRoutingDestTermPXIStarXNotInSlot2_Routing: i32 = -89148; pub const DAQmxErrorRoutingSrcTermPXIStarXNotInSlot2_Routing: i32 = -89147; pub const DAQmxErrorRoutingSrcTermPXIStarInSlot16AndAbove_Routing: i32 = -89146; pub const DAQmxErrorRoutingDestTermPXIStarInSlot16AndAbove_Routing: i32 = -89145; pub const DAQmxErrorRoutingDestTermPXIStarInSlot2_Routing: i32 = -89144; pub const DAQmxErrorRoutingSrcTermPXIStarInSlot2_Routing: i32 = -89143; pub const DAQmxErrorRoutingDestTermPXIChassisNotIdentified_Routing: i32 = -89142; pub const DAQmxErrorRoutingSrcTermPXIChassisNotIdentified_Routing: i32 = -89141; pub const DAQmxErrorTrigLineNotFoundSingleDevRoute_Routing: i32 = -89140; pub const DAQmxErrorNoCommonTrigLineForRoute_Routing: i32 = -89139; pub const DAQmxErrorResourcesInUseForRouteInTask_Routing: i32 = -89138; pub const DAQmxErrorResourcesInUseForRoute_Routing: i32 = -89137; pub const DAQmxErrorRouteNotSupportedByHW_Routing: i32 = -89136; pub const DAQmxErrorResourcesInUseForInversionInTask_Routing: i32 = -89135; pub const DAQmxErrorResourcesInUseForInversion_Routing: i32 = -89134; pub const DAQmxErrorInversionNotSupportedByHW_Routing: i32 = -89133; pub const DAQmxErrorResourcesInUseForProperty_Routing: i32 = -89132; pub const DAQmxErrorRouteSrcAndDestSame_Routing: i32 = -89131; pub const DAQmxErrorDevAbsentOrUnavailable_Routing: i32 = -89130; pub const DAQmxErrorInvalidTerm_Routing: i32 = -89129; pub const DAQmxErrorCannotTristateTerm_Routing: i32 = -89128; pub const DAQmxErrorCannotTristateBusyTerm_Routing: i32 = -89127; pub const DAQmxErrorCouldNotReserveRequestedTrigLine_Routing: i32 = -89126; pub const DAQmxErrorTrigLineNotFound_Routing: i32 = -89125; pub const DAQmxErrorRoutingPathNotAvailable_Routing: i32 = -89124; pub const DAQmxErrorRoutingHardwareBusy_Routing: i32 = -89123; pub const DAQmxErrorRequestedSignalInversionForRoutingNotPossible_Routing: i32 = -89122; pub const DAQmxErrorInvalidRoutingDestinationTerminalName_Routing: i32 = -89121; pub const DAQmxErrorInvalidRoutingSourceTerminalName_Routing: i32 = -89120; pub const DAQmxErrorServiceLocatorNotAvailable_Routing: i32 = -88907; pub const DAQmxErrorCouldNotConnectToServer_Routing: i32 = -88900; pub const DAQmxErrorDeviceNameContainsSpacesOrPunctuation_Routing: i32 = -88720; pub const DAQmxErrorDeviceNameContainsNonprintableCharacters_Routing: i32 = -88719; pub const DAQmxErrorDeviceNameIsEmpty_Routing: i32 = -88718; pub const DAQmxErrorDeviceNameNotFound_Routing: i32 = -88717; pub const DAQmxErrorLocalRemoteDriverVersionMismatch_Routing: i32 = -88716; pub const DAQmxErrorDuplicateDeviceName_Routing: i32 = -88715; pub const DAQmxErrorRuntimeAborting_Routing: i32 = -88710; pub const DAQmxErrorRuntimeAborted_Routing: i32 = -88709; pub const DAQmxErrorResourceNotInPool_Routing: i32 = -88708; pub const DAQmxErrorDriverDeviceGUIDNotFound_Routing: i32 = -88705; pub const DAQmxErrorPALUSBTransactionError: i32 = -50808; pub const DAQmxErrorPALIsocStreamBufferError: i32 = -50807; pub const DAQmxErrorPALInvalidAddressComponent: i32 = -50806; pub const DAQmxErrorPALSharingViolation: i32 = -50805; pub const DAQmxErrorPALInvalidDeviceState: i32 = -50804; pub const DAQmxErrorPALConnectionReset: i32 = -50803; pub const DAQmxErrorPALConnectionAborted: i32 = -50802; pub const DAQmxErrorPALConnectionRefused: i32 = -50801; pub const DAQmxErrorPALBusResetOccurred: i32 = -50800; pub const DAQmxErrorPALWaitInterrupted: i32 = -50700; pub const DAQmxErrorPALMessageUnderflow: i32 = -50651; pub const DAQmxErrorPALMessageOverflow: i32 = -50650; pub const DAQmxErrorPALThreadAlreadyDead: i32 = -50604; pub const DAQmxErrorPALThreadStackSizeNotSupported: i32 = -50603; pub const DAQmxErrorPALThreadControllerIsNotThreadCreator: i32 = -50602; pub const DAQmxErrorPALThreadHasNoThreadObject: i32 = -50601; pub const DAQmxErrorPALThreadCouldNotRun: i32 = -50600; pub const DAQmxErrorPALSyncAbandoned: i32 = -50551; pub const DAQmxErrorPALSyncTimedOut: i32 = -50550; pub const DAQmxErrorPALReceiverSocketInvalid: i32 = -50503; pub const DAQmxErrorPALSocketListenerInvalid: i32 = -50502; pub const DAQmxErrorPALSocketListenerAlreadyRegistered: i32 = -50501; pub const DAQmxErrorPALDispatcherAlreadyExported: i32 = -50500; pub const DAQmxErrorPALDMALinkEventMissed: i32 = -50450; pub const DAQmxErrorPALBusError: i32 = -50413; pub const DAQmxErrorPALRetryLimitExceeded: i32 = -50412; pub const DAQmxErrorPALTransferOverread: i32 = -50411; pub const DAQmxErrorPALTransferOverwritten: i32 = -50410; pub const DAQmxErrorPALPhysicalBufferFull: i32 = -50409; pub const DAQmxErrorPALPhysicalBufferEmpty: i32 = -50408; pub const DAQmxErrorPALLogicalBufferFull: i32 = -50407; pub const DAQmxErrorPALLogicalBufferEmpty: i32 = -50406; pub const DAQmxErrorPALTransferAborted: i32 = -50405; pub const DAQmxErrorPALTransferStopped: i32 = -50404; pub const DAQmxErrorPALTransferInProgress: i32 = -50403; pub const DAQmxErrorPALTransferNotInProgress: i32 = -50402; pub const DAQmxErrorPALCommunicationsFault: i32 = -50401; pub const DAQmxErrorPALTransferTimedOut: i32 = -50400; pub const DAQmxErrorPALMemoryHeapNotEmpty: i32 = -50355; pub const DAQmxErrorPALMemoryBlockCheckFailed: i32 = -50354; pub const DAQmxErrorPALMemoryPageLockFailed: i32 = -50353; pub const DAQmxErrorPALMemoryFull: i32 = -50352; pub const DAQmxErrorPALMemoryAlignmentFault: i32 = -50351; pub const DAQmxErrorPALMemoryConfigurationFault: i32 = -50350; pub const DAQmxErrorPALDeviceInitializationFault: i32 = -50303; pub const DAQmxErrorPALDeviceNotSupported: i32 = -50302; pub const DAQmxErrorPALDeviceUnknown: i32 = -50301; pub const DAQmxErrorPALDeviceNotFound: i32 = -50300; pub const DAQmxErrorPALFeatureDisabled: i32 = -50265; pub const DAQmxErrorPALComponentBusy: i32 = -50264; pub const DAQmxErrorPALComponentAlreadyInstalled: i32 = -50263; pub const DAQmxErrorPALComponentNotUnloadable: i32 = -50262; pub const DAQmxErrorPALComponentNeverLoaded: i32 = -50261; pub const DAQmxErrorPALComponentAlreadyLoaded: i32 = -50260; pub const DAQmxErrorPALComponentCircularDependency: i32 = -50259; pub const DAQmxErrorPALComponentInitializationFault: i32 = -50258; pub const DAQmxErrorPALComponentImageCorrupt: i32 = -50257; pub const DAQmxErrorPALFeatureNotSupported: i32 = -50256; pub const DAQmxErrorPALFunctionNotFound: i32 = -50255; pub const DAQmxErrorPALFunctionObsolete: i32 = -50254; pub const DAQmxErrorPALComponentTooNew: i32 = -50253; pub const DAQmxErrorPALComponentTooOld: i32 = -50252; pub const DAQmxErrorPALComponentNotFound: i32 = -50251; pub const DAQmxErrorPALVersionMismatch: i32 = -50250; pub const DAQmxErrorPALFileFault: i32 = -50209; pub const DAQmxErrorPALFileWriteFault: i32 = -50208; pub const DAQmxErrorPALFileReadFault: i32 = -50207; pub const DAQmxErrorPALFileSeekFault: i32 = -50206; pub const DAQmxErrorPALFileCloseFault: i32 = -50205; pub const DAQmxErrorPALFileOpenFault: i32 = -50204; pub const DAQmxErrorPALDiskFull: i32 = -50203; pub const DAQmxErrorPALOSFault: i32 = -50202; pub const DAQmxErrorPALOSInitializationFault: i32 = -50201; pub const DAQmxErrorPALOSUnsupported: i32 = -50200; pub const DAQmxErrorPALCalculationOverflow: i32 = -50175; pub const DAQmxErrorPALHardwareFault: i32 = -50152; pub const DAQmxErrorPALFirmwareFault: i32 = -50151; pub const DAQmxErrorPALSoftwareFault: i32 = -50150; pub const DAQmxErrorPALMessageQueueFull: i32 = -50108; pub const DAQmxErrorPALResourceAmbiguous: i32 = -50107; pub const DAQmxErrorPALResourceBusy: i32 = -50106; pub const DAQmxErrorPALResourceInitialized: i32 = -50105; pub const DAQmxErrorPALResourceNotInitialized: i32 = -50104; pub const DAQmxErrorPALResourceReserved: i32 = -50103; pub const DAQmxErrorPALResourceNotReserved: i32 = -50102; pub const DAQmxErrorPALResourceNotAvailable: i32 = -50101; pub const DAQmxErrorPALResourceOwnedBySystem: i32 = -50100; pub const DAQmxErrorPALBadToken: i32 = -50020; pub const DAQmxErrorPALBadThreadMultitask: i32 = -50019; pub const DAQmxErrorPALBadLibrarySpecifier: i32 = -50018; pub const DAQmxErrorPALBadAddressSpace: i32 = -50017; pub const DAQmxErrorPALBadWindowType: i32 = -50016; pub const DAQmxErrorPALBadAddressClass: i32 = -50015; pub const DAQmxErrorPALBadWriteCount: i32 = -50014; pub const DAQmxErrorPALBadWriteOffset: i32 = -50013; pub const DAQmxErrorPALBadWriteMode: i32 = -50012; pub const DAQmxErrorPALBadReadCount: i32 = -50011; pub const DAQmxErrorPALBadReadOffset: i32 = -50010; pub const DAQmxErrorPALBadReadMode: i32 = -50009; pub const DAQmxErrorPALBadCount: i32 = -50008; pub const DAQmxErrorPALBadOffset: i32 = -50007; pub const DAQmxErrorPALBadMode: i32 = -50006; pub const DAQmxErrorPALBadDataSize: i32 = -50005; pub const DAQmxErrorPALBadPointer: i32 = -50004; pub const DAQmxErrorPALBadSelector: i32 = -50003; pub const DAQmxErrorPALBadDevice: i32 = -50002; pub const DAQmxErrorPALIrrelevantAttribute: i32 = -50001; pub const DAQmxErrorPALValueConflict: i32 = -50000; pub const DAQmxWarningPALValueConflict: u32 = 50000; pub const DAQmxWarningPALIrrelevantAttribute: u32 = 50001; pub const DAQmxWarningPALBadDevice: u32 = 50002; pub const DAQmxWarningPALBadSelector: u32 = 50003; pub const DAQmxWarningPALBadPointer: u32 = 50004; pub const DAQmxWarningPALBadDataSize: u32 = 50005; pub const DAQmxWarningPALBadMode: u32 = 50006; pub const DAQmxWarningPALBadOffset: u32 = 50007; pub const DAQmxWarningPALBadCount: u32 = 50008; pub const DAQmxWarningPALBadReadMode: u32 = 50009; pub const DAQmxWarningPALBadReadOffset: u32 = 50010; pub const DAQmxWarningPALBadReadCount: u32 = 50011; pub const DAQmxWarningPALBadWriteMode: u32 = 50012; pub const DAQmxWarningPALBadWriteOffset: u32 = 50013; pub const DAQmxWarningPALBadWriteCount: u32 = 50014; pub const DAQmxWarningPALBadAddressClass: u32 = 50015; pub const DAQmxWarningPALBadWindowType: u32 = 50016; pub const DAQmxWarningPALBadThreadMultitask: u32 = 50019; pub const DAQmxWarningPALResourceOwnedBySystem: u32 = 50100; pub const DAQmxWarningPALResourceNotAvailable: u32 = 50101; pub const DAQmxWarningPALResourceNotReserved: u32 = 50102; pub const DAQmxWarningPALResourceReserved: u32 = 50103; pub const DAQmxWarningPALResourceNotInitialized: u32 = 50104; pub const DAQmxWarningPALResourceInitialized: u32 = 50105; pub const DAQmxWarningPALResourceBusy: u32 = 50106; pub const DAQmxWarningPALResourceAmbiguous: u32 = 50107; pub const DAQmxWarningPALFirmwareFault: u32 = 50151; pub const DAQmxWarningPALHardwareFault: u32 = 50152; pub const DAQmxWarningPALOSUnsupported: u32 = 50200; pub const DAQmxWarningPALOSFault: u32 = 50202; pub const DAQmxWarningPALFunctionObsolete: u32 = 50254; pub const DAQmxWarningPALFunctionNotFound: u32 = 50255; pub const DAQmxWarningPALFeatureNotSupported: u32 = 50256; pub const DAQmxWarningPALComponentInitializationFault: u32 = 50258; pub const DAQmxWarningPALComponentAlreadyLoaded: u32 = 50260; pub const DAQmxWarningPALComponentNotUnloadable: u32 = 50262; pub const DAQmxWarningPALMemoryAlignmentFault: u32 = 50351; pub const DAQmxWarningPALMemoryHeapNotEmpty: u32 = 50355; pub const DAQmxWarningPALTransferNotInProgress: u32 = 50402; pub const DAQmxWarningPALTransferInProgress: u32 = 50403; pub const DAQmxWarningPALTransferStopped: u32 = 50404; pub const DAQmxWarningPALTransferAborted: u32 = 50405; pub const DAQmxWarningPALLogicalBufferEmpty: u32 = 50406; pub const DAQmxWarningPALLogicalBufferFull: u32 = 50407; pub const DAQmxWarningPALPhysicalBufferEmpty: u32 = 50408; pub const DAQmxWarningPALPhysicalBufferFull: u32 = 50409; pub const DAQmxWarningPALTransferOverwritten: u32 = 50410; pub const DAQmxWarningPALTransferOverread: u32 = 50411; pub const DAQmxWarningPALDispatcherAlreadyExported: u32 = 50500; pub const DAQmxWarningPALSyncAbandoned: u32 = 50551; pub type int8 = ::std::os::raw::c_schar; pub type uInt8 = ::std::os::raw::c_uchar; pub type int16 = ::std::os::raw::c_short; pub type uInt16 = ::std::os::raw::c_ushort; pub type int32 = ::std::os::raw::c_long; pub type uInt32 = ::std::os::raw::c_ulong; pub type float32 = f32; pub type float64 = f64; pub type int64 = ::std::os::raw::c_longlong; pub type uInt64 = ::std::os::raw::c_ulonglong; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct CVITime { pub _bindgen_opaque_blob: [u32; 4usize], } #[test] fn bindgen_test_layout_CVITime() { assert_eq!( ::std::mem::size_of::<CVITime>(), 16usize, concat!("Size of: ", stringify!(CVITime)) ); assert_eq!( ::std::mem::align_of::<CVITime>(), 4usize, concat!("Alignment of ", stringify!(CVITime)) ); } #[repr(C)] #[derive(Copy, Clone)] pub union CVIAbsoluteTime { pub cviTime: CVITime, pub u32Data: [uInt32; 4usize], _bindgen_union_align: [u32; 4usize], } #[test] fn bindgen_test_layout_CVIAbsoluteTime() { assert_eq!( ::std::mem::size_of::<CVIAbsoluteTime>(), 16usize, concat!("Size of: ", stringify!(CVIAbsoluteTime)) ); assert_eq!( ::std::mem::align_of::<CVIAbsoluteTime>(), 4usize, concat!("Alignment of ", stringify!(CVIAbsoluteTime)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<CVIAbsoluteTime>())).cviTime as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(CVIAbsoluteTime), "::", stringify!(cviTime) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<CVIAbsoluteTime>())).u32Data as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(CVIAbsoluteTime), "::", stringify!(u32Data) ) ); } pub type bool32 = uInt32; pub type TaskHandle = *mut ::std::os::raw::c_void; pub type CalHandle = uInt32; extern "C" { pub fn DAQmxLoadTask( taskName: *const ::std::os::raw::c_char, taskHandle: *mut TaskHandle, ) -> int32; } extern "C" { pub fn DAQmxCreateTask( taskName: *const ::std::os::raw::c_char, taskHandle: *mut TaskHandle, ) -> int32; } extern "C" { pub fn DAQmxAddGlobalChansToTask( taskHandle: TaskHandle, channelNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxStartTask(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxStopTask(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxClearTask(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxWaitUntilTaskDone(taskHandle: TaskHandle, timeToWait: float64) -> int32; } extern "C" { pub fn DAQmxWaitForValidTimestamp( taskHandle: TaskHandle, timestampEvent: int32, timeout: float64, timestamp: *mut CVIAbsoluteTime, ) -> int32; } extern "C" { pub fn DAQmxIsTaskDone(taskHandle: TaskHandle, isTaskDone: *mut bool32) -> int32; } extern "C" { pub fn DAQmxTaskControl(taskHandle: TaskHandle, action: int32) -> int32; } extern "C" { pub fn DAQmxGetNthTaskChannel( taskHandle: TaskHandle, index: uInt32, buffer: *mut ::std::os::raw::c_char, bufferSize: int32, ) -> int32; } extern "C" { pub fn DAQmxGetNthTaskDevice( taskHandle: TaskHandle, index: uInt32, buffer: *mut ::std::os::raw::c_char, bufferSize: int32, ) -> int32; } extern "C" { pub fn DAQmxGetTaskAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } pub type DAQmxEveryNSamplesEventCallbackPtr = ::std::option::Option< unsafe extern "C" fn( taskHandle: TaskHandle, everyNsamplesEventType: int32, nSamples: uInt32, callbackData: *mut ::std::os::raw::c_void, ) -> int32, >; pub type DAQmxDoneEventCallbackPtr = ::std::option::Option< unsafe extern "C" fn( taskHandle: TaskHandle, status: int32, callbackData: *mut ::std::os::raw::c_void, ) -> int32, >; pub type DAQmxSignalEventCallbackPtr = ::std::option::Option< unsafe extern "C" fn( taskHandle: TaskHandle, signalID: int32, callbackData: *mut ::std::os::raw::c_void, ) -> int32, >; extern "C" { pub fn DAQmxRegisterEveryNSamplesEvent( task: TaskHandle, everyNsamplesEventType: int32, nSamples: uInt32, options: uInt32, callbackFunction: DAQmxEveryNSamplesEventCallbackPtr, callbackData: *mut ::std::os::raw::c_void, ) -> int32; } extern "C" { pub fn DAQmxRegisterDoneEvent( task: TaskHandle, options: uInt32, callbackFunction: DAQmxDoneEventCallbackPtr, callbackData: *mut ::std::os::raw::c_void, ) -> int32; } extern "C" { pub fn DAQmxRegisterSignalEvent( task: TaskHandle, signalID: int32, options: uInt32, callbackFunction: DAQmxSignalEventCallbackPtr, callbackData: *mut ::std::os::raw::c_void, ) -> int32; } extern "C" { pub fn DAQmxCreateAIVoltageChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAICurrentChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, shuntResistorLoc: int32, extShuntResistorVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIVoltageRMSChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAICurrentRMSChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, shuntResistorLoc: int32, extShuntResistorVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIThrmcplChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, thermocoupleType: int32, cjcSource: int32, cjcVal: float64, cjcChannel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIRTDChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, rtdType: int32, resistanceConfig: int32, currentExcitSource: int32, currentExcitVal: float64, r0: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateAIThrmstrChanIex( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, resistanceConfig: int32, currentExcitSource: int32, currentExcitVal: float64, a: float64, b: float64, c: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateAIThrmstrChanVex( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, resistanceConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, a: float64, b: float64, c: float64, r1: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateAIFreqVoltageChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, thresholdLevel: float64, hysteresis: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIResistanceChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, resistanceConfig: int32, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIStrainGageChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, strainConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, gageFactor: float64, initialBridgeVoltage: float64, nominalGageResistance: float64, poissonRatio: float64, leadWireResistance: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIRosetteStrainGageChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, rosetteType: int32, gageOrientation: float64, rosetteMeasTypes: *const int32, numRosetteMeasTypes: uInt32, strainConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, gageFactor: float64, nominalGageResistance: float64, poissonRatio: float64, leadWireResistance: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateAIForceBridgeTwoPointLinChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, firstElectricalVal: float64, secondElectricalVal: float64, electricalUnits: int32, firstPhysicalVal: float64, secondPhysicalVal: float64, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIForceBridgeTableChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, electricalVals: *const float64, numElectricalVals: uInt32, electricalUnits: int32, physicalVals: *const float64, numPhysicalVals: uInt32, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIForceBridgePolynomialChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, forwardCoeffs: *const float64, numForwardCoeffs: uInt32, reverseCoeffs: *const float64, numReverseCoeffs: uInt32, electricalUnits: int32, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIPressureBridgeTwoPointLinChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, firstElectricalVal: float64, secondElectricalVal: float64, electricalUnits: int32, firstPhysicalVal: float64, secondPhysicalVal: float64, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIPressureBridgeTableChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, electricalVals: *const float64, numElectricalVals: uInt32, electricalUnits: int32, physicalVals: *const float64, numPhysicalVals: uInt32, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIPressureBridgePolynomialChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, forwardCoeffs: *const float64, numForwardCoeffs: uInt32, reverseCoeffs: *const float64, numReverseCoeffs: uInt32, electricalUnits: int32, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAITorqueBridgeTwoPointLinChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, firstElectricalVal: float64, secondElectricalVal: float64, electricalUnits: int32, firstPhysicalVal: float64, secondPhysicalVal: float64, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAITorqueBridgeTableChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, electricalVals: *const float64, numElectricalVals: uInt32, electricalUnits: int32, physicalVals: *const float64, numPhysicalVals: uInt32, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAITorqueBridgePolynomialChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, forwardCoeffs: *const float64, numForwardCoeffs: uInt32, reverseCoeffs: *const float64, numReverseCoeffs: uInt32, electricalUnits: int32, physicalUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIBridgeChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, nominalBridgeResistance: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIVoltageChanWithExcit( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, bridgeConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, useExcitForScaling: bool32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAITempBuiltInSensorChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, units: int32, ) -> int32; } extern "C" { pub fn DAQmxCreateAIAccelChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, sensitivity: float64, sensitivityUnits: int32, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIVelocityIEPEChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, sensitivity: float64, sensitivityUnits: int32, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIForceIEPEChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, sensitivity: float64, sensitivityUnits: int32, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIMicrophoneChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, units: int32, micSensitivity: float64, maxSndPressLevel: float64, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIChargeChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIAccelChargeChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, sensitivity: float64, sensitivityUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIAccel4WireDCVoltageChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, sensitivity: float64, sensitivityUnits: int32, voltageExcitSource: int32, voltageExcitVal: float64, useExcitForScaling: bool32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIPosLVDTChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, sensitivity: float64, sensitivityUnits: int32, voltageExcitSource: int32, voltageExcitVal: float64, voltageExcitFreq: float64, ACExcitWireMode: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIPosRVDTChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, sensitivity: float64, sensitivityUnits: int32, voltageExcitSource: int32, voltageExcitVal: float64, voltageExcitFreq: float64, ACExcitWireMode: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIPosEddyCurrProxProbeChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, sensitivity: float64, sensitivityUnits: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAIDeviceTempChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, units: int32, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIVoltageChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAICurrentChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, shuntResistorLoc: int32, extShuntResistorVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIThrmcplChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, cjcSource: int32, cjcVal: float64, cjcChannel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIRTDChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, resistanceConfig: int32, currentExcitSource: int32, currentExcitVal: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIThrmstrChanIex( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, resistanceConfig: int32, currentExcitSource: int32, currentExcitVal: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIThrmstrChanVex( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, resistanceConfig: int32, voltageExcitSource: int32, voltageExcitVal: float64, r1: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIResistanceChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, resistanceConfig: int32, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIStrainGageChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, voltageExcitSource: int32, voltageExcitVal: float64, initialBridgeVoltage: float64, leadWireResistance: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIForceBridgeChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, voltageExcitSource: int32, voltageExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIPressureBridgeChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, voltageExcitSource: int32, voltageExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAITorqueBridgeChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, voltageExcitSource: int32, voltageExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIBridgeChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, voltageExcitSource: int32, voltageExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIVoltageChanWithExcit( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, voltageExcitSource: int32, voltageExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIAccelChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIForceIEPEChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, minVal: float64, maxVal: float64, units: int32, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIMicrophoneChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, terminalConfig: int32, units: int32, maxSndPressLevel: float64, currentExcitSource: int32, currentExcitVal: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIPosLVDTChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, voltageExcitSource: int32, voltageExcitVal: float64, voltageExcitFreq: float64, ACExcitWireMode: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTEDSAIPosRVDTChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, voltageExcitSource: int32, voltageExcitVal: float64, voltageExcitFreq: float64, ACExcitWireMode: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAOVoltageChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAOCurrentChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateAOFuncGenChan( taskHandle: TaskHandle, physicalChannel: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, type_: int32, freq: float64, amplitude: float64, offset: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateDIChan( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, nameToAssignToLines: *const ::std::os::raw::c_char, lineGrouping: int32, ) -> int32; } extern "C" { pub fn DAQmxCreateDOChan( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, nameToAssignToLines: *const ::std::os::raw::c_char, lineGrouping: int32, ) -> int32; } extern "C" { pub fn DAQmxCreateCIFreqChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, edge: int32, measMethod: int32, measTime: float64, divisor: uInt32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCIPeriodChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, edge: int32, measMethod: int32, measTime: float64, divisor: uInt32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCICountEdgesChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, edge: int32, initialCount: uInt32, countDirection: int32, ) -> int32; } extern "C" { pub fn DAQmxCreateCIDutyCycleChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minFreq: float64, maxFreq: float64, edge: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCIPulseWidthChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, startingEdge: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCISemiPeriodChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCITwoEdgeSepChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, firstEdge: int32, secondEdge: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCIPulseChanFreq( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, ) -> int32; } extern "C" { pub fn DAQmxCreateCIPulseChanTime( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, units: int32, ) -> int32; } extern "C" { pub fn DAQmxCreateCIPulseChanTicks( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, sourceTerminal: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateCILinEncoderChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, decodingType: int32, ZidxEnable: bool32, ZidxVal: float64, ZidxPhase: int32, units: int32, distPerPulse: float64, initialPos: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCIAngEncoderChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, decodingType: int32, ZidxEnable: bool32, ZidxVal: float64, ZidxPhase: int32, units: int32, pulsesPerRev: uInt32, initialAngle: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCILinVelocityChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, decodingType: int32, units: int32, distPerPulse: float64, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCIAngVelocityChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, minVal: float64, maxVal: float64, decodingType: int32, units: int32, pulsesPerRev: uInt32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCIGPSTimestampChan( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, units: int32, syncMethod: int32, customScaleName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateCOPulseChanFreq( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, units: int32, idleState: int32, initialDelay: float64, freq: float64, dutyCycle: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateCOPulseChanTime( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, units: int32, idleState: int32, initialDelay: float64, lowTime: float64, highTime: float64, ) -> int32; } extern "C" { pub fn DAQmxCreateCOPulseChanTicks( taskHandle: TaskHandle, counter: *const ::std::os::raw::c_char, nameToAssignToChannel: *const ::std::os::raw::c_char, sourceTerminal: *const ::std::os::raw::c_char, idleState: int32, initialDelay: int32, lowTicks: int32, highTicks: int32, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalCalDate( taskHandle: TaskHandle, channelName: *const ::std::os::raw::c_char, year: *mut uInt32, month: *mut uInt32, day: *mut uInt32, hour: *mut uInt32, minute: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalCalDate( taskHandle: TaskHandle, channelName: *const ::std::os::raw::c_char, year: uInt32, month: uInt32, day: uInt32, hour: uInt32, minute: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalExpDate( taskHandle: TaskHandle, channelName: *const ::std::os::raw::c_char, year: *mut uInt32, month: *mut uInt32, day: *mut uInt32, hour: *mut uInt32, minute: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalExpDate( taskHandle: TaskHandle, channelName: *const ::std::os::raw::c_char, year: uInt32, month: uInt32, day: uInt32, hour: uInt32, minute: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetChanAttribute( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetChanAttribute( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, attribute: int32, ... ) -> int32; } extern "C" { pub fn DAQmxResetChanAttribute( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, attribute: int32, ) -> int32; } extern "C" { pub fn DAQmxCfgSampClkTiming( taskHandle: TaskHandle, source: *const ::std::os::raw::c_char, rate: float64, activeEdge: int32, sampleMode: int32, sampsPerChan: uInt64, ) -> int32; } extern "C" { pub fn DAQmxCfgHandshakingTiming( taskHandle: TaskHandle, sampleMode: int32, sampsPerChan: uInt64, ) -> int32; } extern "C" { pub fn DAQmxCfgBurstHandshakingTimingImportClock( taskHandle: TaskHandle, sampleMode: int32, sampsPerChan: uInt64, sampleClkRate: float64, sampleClkSrc: *const ::std::os::raw::c_char, sampleClkActiveEdge: int32, pauseWhen: int32, readyEventActiveLevel: int32, ) -> int32; } extern "C" { pub fn DAQmxCfgBurstHandshakingTimingExportClock( taskHandle: TaskHandle, sampleMode: int32, sampsPerChan: uInt64, sampleClkRate: float64, sampleClkOutpTerm: *const ::std::os::raw::c_char, sampleClkPulsePolarity: int32, pauseWhen: int32, readyEventActiveLevel: int32, ) -> int32; } extern "C" { pub fn DAQmxCfgChangeDetectionTiming( taskHandle: TaskHandle, risingEdgeChan: *const ::std::os::raw::c_char, fallingEdgeChan: *const ::std::os::raw::c_char, sampleMode: int32, sampsPerChan: uInt64, ) -> int32; } extern "C" { pub fn DAQmxCfgImplicitTiming( taskHandle: TaskHandle, sampleMode: int32, sampsPerChan: uInt64, ) -> int32; } extern "C" { pub fn DAQmxCfgPipelinedSampClkTiming( taskHandle: TaskHandle, source: *const ::std::os::raw::c_char, rate: float64, activeEdge: int32, sampleMode: int32, sampsPerChan: uInt64, ) -> int32; } extern "C" { pub fn DAQmxGetTimingAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetTimingAttribute(taskHandle: TaskHandle, attribute: int32, ...) -> int32; } extern "C" { pub fn DAQmxResetTimingAttribute(taskHandle: TaskHandle, attribute: int32) -> int32; } extern "C" { pub fn DAQmxGetTimingAttributeEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetTimingAttributeEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, attribute: int32, ... ) -> int32; } extern "C" { pub fn DAQmxResetTimingAttributeEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, attribute: int32, ) -> int32; } extern "C" { pub fn DAQmxDisableStartTrig(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxCfgDigEdgeStartTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerEdge: int32, ) -> int32; } extern "C" { pub fn DAQmxCfgAnlgEdgeStartTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerSlope: int32, triggerLevel: float64, ) -> int32; } extern "C" { pub fn DAQmxCfgAnlgMultiEdgeStartTrig( taskHandle: TaskHandle, triggerSources: *const ::std::os::raw::c_char, triggerSlopeArray: *mut int32, triggerLevelArray: *mut float64, arraySize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxCfgAnlgWindowStartTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerWhen: int32, windowTop: float64, windowBottom: float64, ) -> int32; } extern "C" { pub fn DAQmxCfgTimeStartTrig( taskHandle: TaskHandle, when: CVIAbsoluteTime, timescale: int32, ) -> int32; } extern "C" { pub fn DAQmxCfgDigPatternStartTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerPattern: *const ::std::os::raw::c_char, triggerWhen: int32, ) -> int32; } extern "C" { pub fn DAQmxDisableRefTrig(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxCfgDigEdgeRefTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerEdge: int32, pretriggerSamples: uInt32, ) -> int32; } extern "C" { pub fn DAQmxCfgAnlgEdgeRefTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerSlope: int32, triggerLevel: float64, pretriggerSamples: uInt32, ) -> int32; } extern "C" { pub fn DAQmxCfgAnlgMultiEdgeRefTrig( taskHandle: TaskHandle, triggerSources: *const ::std::os::raw::c_char, triggerSlopeArray: *mut int32, triggerLevelArray: *mut float64, pretriggerSamples: uInt32, arraySize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxCfgAnlgWindowRefTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerWhen: int32, windowTop: float64, windowBottom: float64, pretriggerSamples: uInt32, ) -> int32; } extern "C" { pub fn DAQmxCfgDigPatternRefTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerPattern: *const ::std::os::raw::c_char, triggerWhen: int32, pretriggerSamples: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetTrigAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetTrigAttribute(taskHandle: TaskHandle, attribute: int32, ...) -> int32; } extern "C" { pub fn DAQmxResetTrigAttribute(taskHandle: TaskHandle, attribute: int32) -> int32; } extern "C" { pub fn DAQmxReadAnalogF64( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut float64, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadAnalogScalarF64( taskHandle: TaskHandle, timeout: float64, value: *mut float64, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadBinaryI16( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut int16, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadBinaryU16( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut uInt16, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadBinaryI32( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut int32, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadBinaryU32( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut uInt32, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadDigitalU8( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut uInt8, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadDigitalU16( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut uInt16, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadDigitalU32( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut uInt32, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadDigitalScalarU32( taskHandle: TaskHandle, timeout: float64, value: *mut uInt32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadDigitalLines( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut uInt8, arraySizeInBytes: uInt32, sampsPerChanRead: *mut int32, numBytesPerSamp: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCounterF64( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, readArray: *mut float64, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCounterU32( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, readArray: *mut uInt32, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCounterF64Ex( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut float64, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCounterU32Ex( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, fillMode: bool32, readArray: *mut uInt32, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCounterScalarF64( taskHandle: TaskHandle, timeout: float64, value: *mut float64, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCounterScalarU32( taskHandle: TaskHandle, timeout: float64, value: *mut uInt32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCtrFreq( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, interleaved: bool32, readArrayFrequency: *mut float64, readArrayDutyCycle: *mut float64, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCtrTime( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, interleaved: bool32, readArrayHighTime: *mut float64, readArrayLowTime: *mut float64, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCtrTicks( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, interleaved: bool32, readArrayHighTicks: *mut uInt32, readArrayLowTicks: *mut uInt32, arraySizeInSamps: uInt32, sampsPerChanRead: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCtrFreqScalar( taskHandle: TaskHandle, timeout: float64, frequency: *mut float64, dutyCycle: *mut float64, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCtrTimeScalar( taskHandle: TaskHandle, timeout: float64, highTime: *mut float64, lowTime: *mut float64, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadCtrTicksScalar( taskHandle: TaskHandle, timeout: float64, highTicks: *mut uInt32, lowTicks: *mut uInt32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxReadRaw( taskHandle: TaskHandle, numSampsPerChan: int32, timeout: float64, readArray: *mut ::std::os::raw::c_void, arraySizeInBytes: uInt32, sampsRead: *mut int32, numBytesPerSamp: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetNthTaskReadChannel( taskHandle: TaskHandle, index: uInt32, buffer: *mut ::std::os::raw::c_char, bufferSize: int32, ) -> int32; } extern "C" { pub fn DAQmxGetReadAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetReadAttribute(taskHandle: TaskHandle, attribute: int32, ...) -> int32; } extern "C" { pub fn DAQmxResetReadAttribute(taskHandle: TaskHandle, attribute: int32) -> int32; } extern "C" { pub fn DAQmxConfigureLogging( taskHandle: TaskHandle, filePath: *const ::std::os::raw::c_char, loggingMode: int32, groupName: *const ::std::os::raw::c_char, operation: int32, ) -> int32; } extern "C" { pub fn DAQmxStartNewFile( taskHandle: TaskHandle, filePath: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxWriteAnalogF64( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const float64, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteAnalogScalarF64( taskHandle: TaskHandle, autoStart: bool32, timeout: float64, value: float64, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteBinaryI16( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const int16, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteBinaryU16( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const uInt16, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteBinaryI32( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const int32, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteBinaryU32( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const uInt32, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteDigitalU8( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const uInt8, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteDigitalU16( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const uInt16, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteDigitalU32( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const uInt32, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteDigitalScalarU32( taskHandle: TaskHandle, autoStart: bool32, timeout: float64, value: uInt32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteDigitalLines( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, writeArray: *const uInt8, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteCtrFreq( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, frequency: *const float64, dutyCycle: *const float64, numSampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteCtrFreqScalar( taskHandle: TaskHandle, autoStart: bool32, timeout: float64, frequency: float64, dutyCycle: float64, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteCtrTime( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, highTime: *const float64, lowTime: *const float64, numSampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteCtrTimeScalar( taskHandle: TaskHandle, autoStart: bool32, timeout: float64, highTime: float64, lowTime: float64, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteCtrTicks( taskHandle: TaskHandle, numSampsPerChan: int32, autoStart: bool32, timeout: float64, dataLayout: bool32, highTicks: *const uInt32, lowTicks: *const uInt32, numSampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteCtrTicksScalar( taskHandle: TaskHandle, autoStart: bool32, timeout: float64, highTicks: uInt32, lowTicks: uInt32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxWriteRaw( taskHandle: TaskHandle, numSamps: int32, autoStart: bool32, timeout: float64, writeArray: *const ::std::os::raw::c_void, sampsPerChanWritten: *mut int32, reserved: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetWriteAttribute(taskHandle: TaskHandle, attribute: int32, ...) -> int32; } extern "C" { pub fn DAQmxResetWriteAttribute(taskHandle: TaskHandle, attribute: int32) -> int32; } extern "C" { pub fn DAQmxExportSignal( taskHandle: TaskHandle, signalID: int32, outputTerminal: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetExportedSignalAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetExportedSignalAttribute(taskHandle: TaskHandle, attribute: int32, ...) -> int32; } extern "C" { pub fn DAQmxResetExportedSignalAttribute(taskHandle: TaskHandle, attribute: int32) -> int32; } extern "C" { pub fn DAQmxCreateLinScale( name: *const ::std::os::raw::c_char, slope: float64, yIntercept: float64, preScaledUnits: int32, scaledUnits: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateMapScale( name: *const ::std::os::raw::c_char, prescaledMin: float64, prescaledMax: float64, scaledMin: float64, scaledMax: float64, preScaledUnits: int32, scaledUnits: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreatePolynomialScale( name: *const ::std::os::raw::c_char, forwardCoeffs: *const float64, numForwardCoeffsIn: uInt32, reverseCoeffs: *const float64, numReverseCoeffsIn: uInt32, preScaledUnits: int32, scaledUnits: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCreateTableScale( name: *const ::std::os::raw::c_char, prescaledVals: *const float64, numPrescaledValsIn: uInt32, scaledVals: *const float64, numScaledValsIn: uInt32, preScaledUnits: int32, scaledUnits: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxCalculateReversePolyCoeff( forwardCoeffs: *const float64, numForwardCoeffsIn: uInt32, minValX: float64, maxValX: float64, numPointsToCompute: int32, reversePolyOrder: int32, reverseCoeffs: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetScaleAttribute( scaleName: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetScaleAttribute( scaleName: *const ::std::os::raw::c_char, attribute: int32, ... ) -> int32; } extern "C" { pub fn DAQmxCfgInputBuffer(taskHandle: TaskHandle, numSampsPerChan: uInt32) -> int32; } extern "C" { pub fn DAQmxCfgOutputBuffer(taskHandle: TaskHandle, numSampsPerChan: uInt32) -> int32; } extern "C" { pub fn DAQmxGetBufferAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ) -> int32; } extern "C" { pub fn DAQmxSetBufferAttribute(taskHandle: TaskHandle, attribute: int32, ...) -> int32; } extern "C" { pub fn DAQmxResetBufferAttribute(taskHandle: TaskHandle, attribute: int32) -> int32; } extern "C" { pub fn DAQmxSwitchCreateScanList( scanList: *const ::std::os::raw::c_char, taskHandle: *mut TaskHandle, ) -> int32; } extern "C" { pub fn DAQmxSwitchConnect( switchChannel1: *const ::std::os::raw::c_char, switchChannel2: *const ::std::os::raw::c_char, waitForSettling: bool32, ) -> int32; } extern "C" { pub fn DAQmxSwitchConnectMulti( connectionList: *const ::std::os::raw::c_char, waitForSettling: bool32, ) -> int32; } extern "C" { pub fn DAQmxSwitchDisconnect( switchChannel1: *const ::std::os::raw::c_char, switchChannel2: *const ::std::os::raw::c_char, waitForSettling: bool32, ) -> int32; } extern "C" { pub fn DAQmxSwitchDisconnectMulti( connectionList: *const ::std::os::raw::c_char, waitForSettling: bool32, ) -> int32; } extern "C" { pub fn DAQmxSwitchDisconnectAll( deviceName: *const ::std::os::raw::c_char, waitForSettling: bool32, ) -> int32; } extern "C" { pub fn DAQmxSwitchSetTopologyAndReset( deviceName: *const ::std::os::raw::c_char, newTopology: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxSwitchFindPath( switchChannel1: *const ::std::os::raw::c_char, switchChannel2: *const ::std::os::raw::c_char, path: *mut ::std::os::raw::c_char, pathBufferSize: uInt32, pathStatus: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSwitchOpenRelays( relayList: *const ::std::os::raw::c_char, waitForSettling: bool32, ) -> int32; } extern "C" { pub fn DAQmxSwitchCloseRelays( relayList: *const ::std::os::raw::c_char, waitForSettling: bool32, ) -> int32; } extern "C" { pub fn DAQmxSwitchGetSingleRelayCount( relayName: *const ::std::os::raw::c_char, count: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSwitchGetMultiRelayCount( relayList: *const ::std::os::raw::c_char, count: *mut uInt32, countArraySize: uInt32, numRelayCountsRead: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSwitchGetSingleRelayPos( relayName: *const ::std::os::raw::c_char, relayPos: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSwitchGetMultiRelayPos( relayList: *const ::std::os::raw::c_char, relayPos: *mut uInt32, relayPosArraySize: uInt32, numRelayPossRead: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSwitchWaitForSettling(deviceName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanAttribute( switchChannelName: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ) -> int32; } extern "C" { pub fn DAQmxSetSwitchChanAttribute( switchChannelName: *const ::std::os::raw::c_char, attribute: int32, ... ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDeviceAttribute( deviceName: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetSwitchDeviceAttribute( deviceName: *const ::std::os::raw::c_char, attribute: int32, ... ) -> int32; } extern "C" { pub fn DAQmxGetSwitchScanAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ) -> int32; } extern "C" { pub fn DAQmxSetSwitchScanAttribute(taskHandle: TaskHandle, attribute: int32, ...) -> int32; } extern "C" { pub fn DAQmxResetSwitchScanAttribute(taskHandle: TaskHandle, attribute: int32) -> int32; } extern "C" { pub fn DAQmxDisableAdvTrig(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxCfgDigEdgeAdvTrig( taskHandle: TaskHandle, triggerSource: *const ::std::os::raw::c_char, triggerEdge: int32, ) -> int32; } extern "C" { pub fn DAQmxSendSoftwareTrigger(taskHandle: TaskHandle, triggerID: int32) -> int32; } extern "C" { pub fn DAQmxConnectTerms( sourceTerminal: *const ::std::os::raw::c_char, destinationTerminal: *const ::std::os::raw::c_char, signalModifiers: int32, ) -> int32; } extern "C" { pub fn DAQmxDisconnectTerms( sourceTerminal: *const ::std::os::raw::c_char, destinationTerminal: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxTristateOutputTerm(outputTerminal: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxResetDevice(deviceName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxSelfTestDevice(deviceName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetDeviceAttribute( deviceName: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxCreateWatchdogTimerTask( deviceName: *const ::std::os::raw::c_char, taskName: *const ::std::os::raw::c_char, taskHandle: *mut TaskHandle, timeout: float64, lines: *const ::std::os::raw::c_char, expState: int32, ... ) -> int32; } extern "C" { pub fn DAQmxCreateWatchdogTimerTaskEx( deviceName: *const ::std::os::raw::c_char, taskName: *const ::std::os::raw::c_char, taskHandle: *mut TaskHandle, timeout: float64, ) -> int32; } extern "C" { pub fn DAQmxControlWatchdogTask(taskHandle: TaskHandle, action: int32) -> int32; } extern "C" { pub fn DAQmxCfgWatchdogAOExpirStates( taskHandle: TaskHandle, channelNames: *const ::std::os::raw::c_char, expirStateArray: *const float64, outputTypeArray: *const int32, arraySize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxCfgWatchdogCOExpirStates( taskHandle: TaskHandle, channelNames: *const ::std::os::raw::c_char, expirStateArray: *const int32, arraySize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxCfgWatchdogDOExpirStates( taskHandle: TaskHandle, channelNames: *const ::std::os::raw::c_char, expirStateArray: *const int32, arraySize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWatchdogAttribute( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetWatchdogAttribute( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, attribute: int32, ... ) -> int32; } extern "C" { pub fn DAQmxResetWatchdogAttribute( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, attribute: int32, ) -> int32; } extern "C" { pub fn DAQmxSelfCal(deviceName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxPerformBridgeOffsetNullingCal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxPerformBridgeOffsetNullingCalEx( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, skipUnsupportedChannels: bool32, ) -> int32; } extern "C" { pub fn DAQmxPerformThrmcplLeadOffsetNullingCal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, skipUnsupportedChannels: bool32, ) -> int32; } extern "C" { pub fn DAQmxPerformStrainShuntCal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, shuntResistorValue: float64, shuntResistorLocation: int32, skipUnsupportedChannels: bool32, ) -> int32; } extern "C" { pub fn DAQmxPerformStrainShuntCalEx( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, shuntResistorValue: float64, shuntResistorLocation: int32, shuntResistorSelect: int32, shuntResistorSource: int32, skipUnsupportedChannels: bool32, ) -> int32; } extern "C" { pub fn DAQmxPerformBridgeShuntCal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, shuntResistorValue: float64, shuntResistorLocation: int32, bridgeResistance: float64, skipUnsupportedChannels: bool32, ) -> int32; } extern "C" { pub fn DAQmxPerformBridgeShuntCalEx( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, shuntResistorValue: float64, shuntResistorLocation: int32, shuntResistorSelect: int32, shuntResistorSource: int32, bridgeResistance: float64, skipUnsupportedChannels: bool32, ) -> int32; } extern "C" { pub fn DAQmxGetSelfCalLastDateAndTime( deviceName: *const ::std::os::raw::c_char, year: *mut uInt32, month: *mut uInt32, day: *mut uInt32, hour: *mut uInt32, minute: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetExtCalLastDateAndTime( deviceName: *const ::std::os::raw::c_char, year: *mut uInt32, month: *mut uInt32, day: *mut uInt32, hour: *mut uInt32, minute: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxRestoreLastExtCalConst(deviceName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxESeriesCalAdjust(calHandle: CalHandle, referenceVoltage: float64) -> int32; } extern "C" { pub fn DAQmxMSeriesCalAdjust(calHandle: CalHandle, referenceVoltage: float64) -> int32; } extern "C" { pub fn DAQmxSSeriesCalAdjust(calHandle: CalHandle, referenceVoltage: float64) -> int32; } extern "C" { pub fn DAQmxSCBaseboardCalAdjust(calHandle: CalHandle, referenceVoltage: float64) -> int32; } extern "C" { pub fn DAQmxAOSeriesCalAdjust(calHandle: CalHandle, referenceVoltage: float64) -> int32; } extern "C" { pub fn DAQmxXSeriesCalAdjust(calHandle: CalHandle, referenceVoltage: float64) -> int32; } extern "C" { pub fn DAQmxDeviceSupportsCal( deviceName: *const ::std::os::raw::c_char, calSupported: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetCalInfoAttribute( deviceName: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetCalInfoAttribute( deviceName: *const ::std::os::raw::c_char, attribute: int32, ... ) -> int32; } extern "C" { pub fn DAQmxInitExtCal( deviceName: *const ::std::os::raw::c_char, password: *const ::std::os::raw::c_char, calHandle: *mut CalHandle, ) -> int32; } extern "C" { pub fn DAQmxCloseExtCal(calHandle: CalHandle, action: int32) -> int32; } extern "C" { pub fn DAQmxChangeExtCalPassword( deviceName: *const ::std::os::raw::c_char, password: *const ::std::os::raw::c_char, newPassword: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxDSASetCalTemp(calHandle: CalHandle, temperature: float64) -> int32; } extern "C" { pub fn DAQmxAdjustDSAAICal(calHandle: CalHandle, referenceVoltage: float64) -> int32; } extern "C" { pub fn DAQmxAdjustDSAAICalEx( calHandle: CalHandle, referenceVoltage: float64, inputsShorted: bool32, ) -> int32; } extern "C" { pub fn DAQmxAdjustDSAAICalWithGainAndCoupling( calHandle: CalHandle, coupling: int32, gain: float64, referenceVoltage: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjustDSAAOCal( calHandle: CalHandle, channel: uInt32, requestedLowVoltage: float64, actualLowVoltage: float64, requestedHighVoltage: float64, actualHighVoltage: float64, gainSetting: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust4610Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, offset: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjustDSATimebaseCal(calHandle: CalHandle, referenceFrequency: float64) -> int32; } extern "C" { pub fn DAQmxAdjustDSAAOTimebaseCal( calHandle: CalHandle, measuredFrequency: float64, calComplete: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetupDSAAOTimebaseCal( calHandle: CalHandle, expectedFrequency: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGet4463AdjustPoints( calHandle: CalHandle, terminalConfig: int32, gain: float64, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust4463Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, referenceVoltage: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup4463Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, terminalConfig: int32, gain: float64, outputVoltage: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup4480Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, calMode: int32, ) -> int32; } extern "C" { pub fn DAQmxAdjustTIOTimebaseCal(calHandle: CalHandle, referenceFrequency: float64) -> int32; } extern "C" { pub fn DAQmxAdjust4204Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, lowPassFreq: float64, trackHoldEnabled: bool32, inputVal: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust4220Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, gain: float64, inputVal: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust4224Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, gain: float64, inputVal: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust4225Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, gain: float64, inputVal: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup433xCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, excitationVoltage: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust433xCal( calHandle: CalHandle, refVoltage: float64, refExcitation: float64, shuntLocation: int32, ) -> int32; } extern "C" { pub fn DAQmxSetup4339Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, calMode: int32, rangeMax: float64, rangeMin: float64, excitationVoltage: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust4339Cal(calHandle: CalHandle, refVoltage: float64) -> int32; } extern "C" { pub fn DAQmxGet4339CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust4300Cal(calHandle: CalHandle, refVoltage: float64) -> int32; } extern "C" { pub fn DAQmxSetup4302Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, ) -> int32; } extern "C" { pub fn DAQmxGet4302CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust4302Cal(calHandle: CalHandle, refVoltage: float64) -> int32; } extern "C" { pub fn DAQmxSetup4303Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, ) -> int32; } extern "C" { pub fn DAQmxGet4303CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust4303Cal(calHandle: CalHandle, refVoltage: float64) -> int32; } extern "C" { pub fn DAQmxSetup4304Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, ) -> int32; } extern "C" { pub fn DAQmxGet4304CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust4304Cal(calHandle: CalHandle, refVoltage: float64) -> int32; } extern "C" { pub fn DAQmxSetup4305Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, ) -> int32; } extern "C" { pub fn DAQmxGet4305CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust4305Cal(calHandle: CalHandle, refVoltage: float64) -> int32; } extern "C" { pub fn DAQmxAdjust4309Cal(calHandle: CalHandle, refVoltage: float64) -> int32; } extern "C" { pub fn DAQmxAdjust4310Cal(calHandle: CalHandle, refVoltage: float64) -> int32; } extern "C" { pub fn DAQmxAdjust4353Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, refVal: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust4357Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, refVals: *const float64, numRefVals: int32, ) -> int32; } extern "C" { pub fn DAQmxSetup4322Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, outputType: int32, outputVal: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust4322Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, refVal: float64, ) -> int32; } extern "C" { pub fn DAQmxGet4322CalAdjustPoints( calHandle: CalHandle, outputType: int32, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxConnectSCExpressCalAccChans( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, connection: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxDisconnectSCExpressCalAccChans(calHandle: CalHandle) -> int32; } extern "C" { pub fn DAQmxGetPossibleSCExpressCalAccConnections( deviceName: *const ::std::os::raw::c_char, channelNames: *const ::std::os::raw::c_char, connections: *mut ::std::os::raw::c_char, connectionsBufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetSCExpressCalAccBridgeOutput( calHandle: CalHandle, voltsPerVolt: float64, ) -> int32; } extern "C" { pub fn DAQmxFieldDAQSetCalTemp(calHandle: CalHandle, temperature: float64) -> int32; } extern "C" { pub fn DAQmxGet11603CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust11603Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet11613CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust11613Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet11614CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust11614Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup11634Cal(calHandle: CalHandle, rangeMin: float64, rangeMax: float64) -> int32; } extern "C" { pub fn DAQmxGet11634CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust11634Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup11637Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, bridgeConfig: int32, voltageExcitation: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust11637Cal( calHandle: CalHandle, value: float64, actualReading: *mut float64, asFoundGainError: *mut float64, asFoundOffsetError: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGet9201CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxCSeriesSetCalTemp(calHandle: CalHandle, temperature: float64) -> int32; } extern "C" { pub fn DAQmxAdjust9201Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9202CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9202Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9203CalAdjustPoints( calHandle: CalHandle, rangeMin: float64, rangeMax: float64, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9203GainCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, value: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9203OffsetCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9205Cal(calHandle: CalHandle, value: float64) -> int32; } extern "C" { pub fn DAQmxAdjust9206Cal(calHandle: CalHandle, value: float64) -> int32; } extern "C" { pub fn DAQmxGet9207CalAdjustPoints( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9207GainCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9207OffsetCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGet9208CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9208GainCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9208OffsetCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGet9209CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9209GainCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, terminalConfig: int32, value: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9209OffsetCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxAdjust9210Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9211Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9212CalAdjustPoints( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9212Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9213CalAdjustPoints( calHandle: CalHandle, rangeMin: float64, rangeMax: float64, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9213Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9214CalAdjustPoints( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9214Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9215CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9215Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9216CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9216Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9217CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9217Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup9218Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, measType: int32, ) -> int32; } extern "C" { pub fn DAQmxGet9218CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9218Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup9219Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, rangeMin: float64, rangeMax: float64, measType: int32, bridgeConfig: int32, ) -> int32; } extern "C" { pub fn DAQmxGet9219CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9219Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9220CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9220Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9221CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9221Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9222CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9222Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9223CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9223Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9224CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9224Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9225CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9225Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9226CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9226Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9227CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9227Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9228CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9228Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9229CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9229Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9230CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9230Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9231CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9231Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9232CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9232Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9234CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9234GainCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9234OffsetCal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGet9238CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9238Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9239CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9239Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9242CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup9242Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9242Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9244CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup9244Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust9244Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9246CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9246Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9247CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9247Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9250CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9250Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9251CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9251Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9260CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut int32, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup9260Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: int32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9260Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9263CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut int32, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup9263Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: int32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9263Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9264CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut int32, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup9264Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: int32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9264Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9265CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut int32, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup9265Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: int32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9265Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9266CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut int32, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup9266Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: int32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9266Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9269CalAdjustPoints( calHandle: CalHandle, adjustmentPoints: *mut int32, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup9269Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: int32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9269Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, ) -> int32; } extern "C" { pub fn DAQmxGet9775CalAdjustPoints( calHandle: CalHandle, coupling: uInt32, adjustmentPoints: *mut float64, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust9775Cal( calHandle: CalHandle, channelNames: *const ::std::os::raw::c_char, value: float64, coupling: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetup1102Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1102Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1104Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxAdjust1104Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1112Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxAdjust1112Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1122Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1122Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1124Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, range: int32, dacValue: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAdjust1124Cal(calHandle: CalHandle, measOutput: float64) -> int32; } extern "C" { pub fn DAQmxSetup1125Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1125Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1126Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, upperFreqLimit: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1126Cal(calHandle: CalHandle, refFreq: float64, measOutput: float64) -> int32; } extern "C" { pub fn DAQmxSetup1141Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1141Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1142Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1142Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1143Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1143Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1502Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1502Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1503Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1503Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1503CurrentCal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, measCurrent: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1520Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1520Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1521Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxAdjust1521Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup153xCal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, gain: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust153xCal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, ) -> int32; } extern "C" { pub fn DAQmxSetup1540Cal( calHandle: CalHandle, channelName: *const ::std::os::raw::c_char, excitationVoltage: float64, excitationFreq: float64, ) -> int32; } extern "C" { pub fn DAQmxAdjust1540Cal( calHandle: CalHandle, refVoltage: float64, measOutput: float64, inputCalSource: int32, ) -> int32; } extern "C" { pub fn DAQmxConfigureTEDS( physicalChannel: *const ::std::os::raw::c_char, filePath: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxClearTEDS(physicalChannel: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxWriteToTEDSFromArray( physicalChannel: *const ::std::os::raw::c_char, bitStream: *const uInt8, arraySize: uInt32, basicTEDSOptions: int32, ) -> int32; } extern "C" { pub fn DAQmxWriteToTEDSFromFile( physicalChannel: *const ::std::os::raw::c_char, filePath: *const ::std::os::raw::c_char, basicTEDSOptions: int32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAttribute( physicalChannel: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxWaitForNextSampleClock( taskHandle: TaskHandle, timeout: float64, isLate: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetRealTimeAttribute( taskHandle: TaskHandle, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetRealTimeAttribute(taskHandle: TaskHandle, attribute: int32, ...) -> int32; } extern "C" { pub fn DAQmxResetRealTimeAttribute(taskHandle: TaskHandle, attribute: int32) -> int32; } extern "C" { pub fn DAQmxIsReadOrWriteLate(errorCode: int32) -> bool32; } extern "C" { pub fn DAQmxSaveTask( taskHandle: TaskHandle, saveAs: *const ::std::os::raw::c_char, author: *const ::std::os::raw::c_char, options: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSaveGlobalChan( taskHandle: TaskHandle, channelName: *const ::std::os::raw::c_char, saveAs: *const ::std::os::raw::c_char, author: *const ::std::os::raw::c_char, options: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSaveScale( scaleName: *const ::std::os::raw::c_char, saveAs: *const ::std::os::raw::c_char, author: *const ::std::os::raw::c_char, options: uInt32, ) -> int32; } extern "C" { pub fn DAQmxDeleteSavedTask(taskName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxDeleteSavedGlobalChan(channelName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxDeleteSavedScale(scaleName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetPersistedTaskAttribute( taskName: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxGetPersistedChanAttribute( channel: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxGetPersistedScaleAttribute( scaleName: *const ::std::os::raw::c_char, attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxGetSystemInfoAttribute( attribute: int32, value: *mut ::std::os::raw::c_void, ... ) -> int32; } extern "C" { pub fn DAQmxSetDigitalPowerUpStates( deviceName: *const ::std::os::raw::c_char, channelNames: *const ::std::os::raw::c_char, state: int32, ... ) -> int32; } extern "C" { pub fn DAQmxGetDigitalPowerUpStates( deviceName: *const ::std::os::raw::c_char, channelName: *const ::std::os::raw::c_char, state: *mut int32, ... ) -> int32; } extern "C" { pub fn DAQmxSetDigitalPullUpPullDownStates( deviceName: *const ::std::os::raw::c_char, channelName: *const ::std::os::raw::c_char, state: int32, ... ) -> int32; } extern "C" { pub fn DAQmxGetDigitalPullUpPullDownStates( deviceName: *const ::std::os::raw::c_char, channelName: *const ::std::os::raw::c_char, state: *mut int32, ... ) -> int32; } extern "C" { pub fn DAQmxSetAnalogPowerUpStates( deviceName: *const ::std::os::raw::c_char, channelNames: *const ::std::os::raw::c_char, state: float64, channelType: int32, ... ) -> int32; } extern "C" { pub fn DAQmxSetAnalogPowerUpStatesWithOutputType( channelNames: *const ::std::os::raw::c_char, stateArray: *const float64, channelTypeArray: *const int32, arraySize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAnalogPowerUpStates( deviceName: *const ::std::os::raw::c_char, channelName: *const ::std::os::raw::c_char, state: *mut float64, channelType: int32, ... ) -> int32; } extern "C" { pub fn DAQmxGetAnalogPowerUpStatesWithOutputType( channelNames: *const ::std::os::raw::c_char, stateArray: *mut float64, channelTypeArray: *mut int32, arraySizePtr: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigitalLogicFamilyPowerUpState( deviceName: *const ::std::os::raw::c_char, logicFamily: int32, ) -> int32; } extern "C" { pub fn DAQmxGetDigitalLogicFamilyPowerUpState( deviceName: *const ::std::os::raw::c_char, logicFamily: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxAddNetworkDevice( IPAddress: *const ::std::os::raw::c_char, deviceName: *const ::std::os::raw::c_char, attemptReservation: bool32, timeout: float64, deviceNameOut: *mut ::std::os::raw::c_char, deviceNameOutBufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxDeleteNetworkDevice(deviceName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxReserveNetworkDevice( deviceName: *const ::std::os::raw::c_char, overrideReservation: bool32, ) -> int32; } extern "C" { pub fn DAQmxUnreserveNetworkDevice(deviceName: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxAutoConfigureCDAQSyncConnections( chassisDevicesPorts: *const ::std::os::raw::c_char, timeout: float64, ) -> int32; } extern "C" { pub fn DAQmxGetAutoConfiguredCDAQSyncConnections( portList: *mut ::std::os::raw::c_char, portListSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAreConfiguredCDAQSyncPortsDisconnected( chassisDevicesPorts: *const ::std::os::raw::c_char, timeout: float64, disconnectedPortsExist: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDisconnectedCDAQSyncPorts( portList: *mut ::std::os::raw::c_char, portListSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxAddCDAQSyncConnection(portList: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxRemoveCDAQSyncConnection(portList: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetErrorString( errorCode: int32, errorString: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetExtendedErrorInfo( errorString: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { #[doc = " NI-DAQmx Specific Attribute Get/Set/Reset Function Declarations **********"] pub fn DAQmxGetBufInputBufSize(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetBufInputBufSize(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetBufInputBufSize(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetBufInputOnbrdBufSize(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetBufOutputBufSize(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetBufOutputBufSize(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetBufOutputBufSize(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetBufOutputOnbrdBufSize(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetBufOutputOnbrdBufSize(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetBufOutputOnbrdBufSize(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSelfCalSupported( deviceName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetSelfCalLastTemp( deviceName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetExtCalRecommendedInterval( deviceName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetExtCalLastTemp( deviceName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetCalUserDefinedInfo( deviceName: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCalUserDefinedInfo( deviceName: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCalUserDefinedInfoMaxSize( deviceName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetCalDevTemp( deviceName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetCalAccConnectionCount( deviceName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCalAccConnectionCount( deviceName: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetCalRecommendedAccConnectionCountLimit( deviceName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAIMax( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIMax( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIMax(taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetAIMin( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIMin( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIMin(taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetAICustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAICustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAICustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIMeasType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetAIVoltageUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIVoltageUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIVoltageUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIVoltagedBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIVoltagedBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIVoltagedBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIVoltageACRMSUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIVoltageACRMSUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIVoltageACRMSUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAITempUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAITempUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAITempUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmcplType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIThrmcplType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIThrmcplType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmcplScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIThrmcplScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIThrmcplScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmcplCJCSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmcplCJCVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIThrmcplCJCVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIThrmcplCJCVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmcplCJCChan( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAIRTDType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIRTDType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIRTDType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRTDR0( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIRTDR0( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIRTDR0( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRTDA( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIRTDA( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIRTDA( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRTDB( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIRTDB( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIRTDB( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRTDC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIRTDC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIRTDC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmstrA( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIThrmstrA( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIThrmstrA( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmstrB( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIThrmstrB( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIThrmstrB( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmstrC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIThrmstrC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIThrmstrC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmstrR1( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIThrmstrR1( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIThrmstrR1( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIForceReadFromChan( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIForceReadFromChan( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIForceReadFromChan( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAICurrentUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAICurrentUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAICurrentUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAICurrentACRMSUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAICurrentACRMSUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAICurrentACRMSUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIStrainUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIStrainUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIStrainUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIStrainGageForceReadFromChan( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIStrainGageForceReadFromChan( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIStrainGageForceReadFromChan( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIStrainGageGageFactor( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIStrainGageGageFactor( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIStrainGageGageFactor( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIStrainGagePoissonRatio( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIStrainGagePoissonRatio( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIStrainGagePoissonRatio( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIStrainGageCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIStrainGageCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIStrainGageCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRosetteStrainGageRosetteType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetAIRosetteStrainGageOrientation( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIRosetteStrainGageOrientation( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIRosetteStrainGageOrientation( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRosetteStrainGageStrainChans( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAIRosetteStrainGageRosetteMeasType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIRosetteStrainGageRosetteMeasType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIRosetteStrainGageRosetteMeasType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIResistanceUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIResistanceUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIResistanceUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFreqThreshVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIFreqThreshVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIFreqThreshVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFreqHyst( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIFreqHyst( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIFreqHyst( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILVDTUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAILVDTUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAILVDTUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILVDTSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAILVDTSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAILVDTSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILVDTSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAILVDTSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAILVDTSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRVDTUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIRVDTUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIRVDTUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRVDTSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIRVDTSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIRVDTSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRVDTSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIRVDTSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIRVDTSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIEddyCurrentProxProbeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIEddyCurrentProxProbeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIEddyCurrentProxProbeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIEddyCurrentProxProbeSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIEddyCurrentProxProbeSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIEddyCurrentProxProbeSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIEddyCurrentProxProbeSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIEddyCurrentProxProbeSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIEddyCurrentProxProbeSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAISoundPressureMaxSoundPressureLvl( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAISoundPressureMaxSoundPressureLvl( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAISoundPressureMaxSoundPressureLvl( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAISoundPressureUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAISoundPressureUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAISoundPressureUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAISoundPressuredBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAISoundPressuredBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAISoundPressuredBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIMicrophoneSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIMicrophoneSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIMicrophoneSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAccelUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIAccelUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIAccelUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAcceldBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIAcceldBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIAcceldBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAccel4WireDCVoltageSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIAccel4WireDCVoltageSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIAccel4WireDCVoltageSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAccel4WireDCVoltageSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIAccel4WireDCVoltageSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIAccel4WireDCVoltageSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAccelSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIAccelSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIAccelSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAccelSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIAccelSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIAccelSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAccelChargeSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIAccelChargeSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIAccelChargeSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAccelChargeSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIAccelChargeSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIAccelChargeSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIVelocityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIVelocityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIVelocityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIVelocityIEPESensordBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIVelocityIEPESensordBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIVelocityIEPESensordBRef( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIVelocityIEPESensorSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIVelocityIEPESensorSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIVelocityIEPESensorSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIVelocityIEPESensorSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIVelocityIEPESensorSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIVelocityIEPESensorSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIForceUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIForceUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIForceUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIForceIEPESensorSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIForceIEPESensorSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIForceIEPESensorSensitivity( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIForceIEPESensorSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIForceIEPESensorSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIForceIEPESensorSensitivityUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIPressureUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIPressureUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIPressureUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAITorqueUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAITorqueUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAITorqueUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeElectricalUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeElectricalUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeElectricalUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgePhysicalUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgePhysicalUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgePhysicalUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeTwoPointLinFirstElectricalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeTwoPointLinFirstElectricalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeTwoPointLinFirstElectricalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeTwoPointLinFirstPhysicalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeTwoPointLinFirstPhysicalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeTwoPointLinFirstPhysicalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeTwoPointLinSecondElectricalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeTwoPointLinSecondElectricalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeTwoPointLinSecondElectricalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeTwoPointLinSecondPhysicalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeTwoPointLinSecondPhysicalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeTwoPointLinSecondPhysicalVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeTableElectricalVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeTableElectricalVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeTableElectricalVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeTablePhysicalVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeTablePhysicalVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeTablePhysicalVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgePolyForwardCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgePolyForwardCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgePolyForwardCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgePolyReverseCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgePolyReverseCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgePolyReverseCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChargeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChargeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChargeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIIsTEDS( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetAITEDSUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAICoupling( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAICoupling( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAICoupling( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAITermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAITermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAITermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIInputSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIInputSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAIInputSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIResistanceCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIResistanceCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIResistanceCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILeadWireResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAILeadWireResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAILeadWireResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeNomResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeNomResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeNomResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeInitialVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeInitialVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeInitialVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeInitialRatio( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeInitialRatio( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeInitialRatio( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeShuntCalEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeShuntCalEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeShuntCalEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeShuntCalSelect( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeShuntCalSelect( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeShuntCalSelect( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeShuntCalShuntCalASrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeShuntCalShuntCalASrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeShuntCalShuntCalASrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeShuntCalGainAdjust( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeShuntCalGainAdjust( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeShuntCalGainAdjust( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeShuntCalShuntCalAResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeShuntCalShuntCalAResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeShuntCalShuntCalAResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeShuntCalShuntCalAActualResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeShuntCalShuntCalAActualResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeShuntCalShuntCalAActualResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeShuntCalShuntCalBResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeShuntCalShuntCalBResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeShuntCalShuntCalBResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeShuntCalShuntCalBActualResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeShuntCalShuntCalBActualResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeShuntCalShuntCalBActualResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeBalanceCoarsePot( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeBalanceCoarsePot( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeBalanceCoarsePot( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIBridgeBalanceFinePot( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIBridgeBalanceFinePot( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIBridgeBalanceFinePot( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAICurrentShuntLoc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAICurrentShuntLoc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAICurrentShuntLoc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAICurrentShuntResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAICurrentShuntResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAICurrentShuntResistance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitSense( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitSense( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitSense( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitUseForScaling( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitUseForScaling( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitUseForScaling( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitUseMultiplexed( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitUseMultiplexed( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitUseMultiplexed( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitActualVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitActualVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitActualVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitDCorAC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitDCorAC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitDCorAC( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitVoltageOrCurrent( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitVoltageOrCurrent( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitVoltageOrCurrent( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIExcitIdleOutputBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIExcitIdleOutputBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIExcitIdleOutputBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIACExcitFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIACExcitFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIACExcitFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIACExcitSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIACExcitSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIACExcitSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIACExcitWireMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIACExcitWireMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIACExcitWireMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAISensorPowerVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAISensorPowerVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAISensorPowerVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAISensorPowerCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAISensorPowerCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAISensorPowerCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAISensorPowerType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAISensorPowerType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAISensorPowerType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIOpenThrmcplDetectEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIOpenThrmcplDetectEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIOpenThrmcplDetectEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIThrmcplLeadOffsetVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIThrmcplLeadOffsetVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIThrmcplLeadOffsetVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAtten( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIAtten( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIAtten( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIProbeAtten( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIProbeAtten( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIProbeAtten( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILowpassEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAILowpassEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAILowpassEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILowpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAILowpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAILowpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILowpassSwitchCapClkSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAILowpassSwitchCapClkSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAILowpassSwitchCapClkSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILowpassSwitchCapExtClkFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAILowpassSwitchCapExtClkFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAILowpassSwitchCapExtClkFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILowpassSwitchCapExtClkDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAILowpassSwitchCapExtClkDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAILowpassSwitchCapExtClkDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILowpassSwitchCapOutClkDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAILowpassSwitchCapOutClkDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAILowpassSwitchCapOutClkDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrResponse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrResponse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrResponse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrOrder( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrOrder( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrOrder( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrLowpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrLowpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrLowpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrHighpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrHighpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrHighpassCutoffFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrBandpassCenterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrBandpassCenterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrBandpassCenterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrBandpassWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrBandpassWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrBandpassWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrNotchCenterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrNotchCenterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrNotchCenterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrNotchWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrNotchWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrNotchWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDigFltrCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDigFltrCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFilterEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIFilterEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIFilterEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFilterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIFilterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIFilterFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFilterResponse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIFilterResponse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIFilterResponse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFilterOrder( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIFilterOrder( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIFilterOrder( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFilterDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetAIFilterDelayUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIFilterDelayUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIFilterDelayUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRemoveFilterDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIRemoveFilterDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIRemoveFilterDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIFilterDelayAdjustment( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIFilterDelayAdjustment( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIFilterDelayAdjustment( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAveragingWinSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIAveragingWinSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIAveragingWinSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIResolutionUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetAIResolution( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetAIRawSampSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAIRawSampJustification( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetAIADCTimingMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIADCTimingMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIADCTimingMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIADCCustomTimingMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIADCCustomTimingMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIADCCustomTimingMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDitherEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDitherEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDitherEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalHasValidCalInfo( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalEnableCal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalEnableCal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalEnableCal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalApplyCalIfExp( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalApplyCalIfExp( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalApplyCalIfExp( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalScaleType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalTablePreScaledVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalTablePreScaledVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalTablePreScaledVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalTableScaledVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalTableScaledVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalTableScaledVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalPolyForwardCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalPolyForwardCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalPolyForwardCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalPolyReverseCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalPolyReverseCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalPolyReverseCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalOperatorName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalOperatorName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalOperatorName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalDesc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalDesc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalDesc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalVerifRefVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalVerifRefVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalVerifRefVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChanCalVerifAcqVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChanCalVerifAcqVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChanCalVerifAcqVals( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRngHigh( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIRngHigh( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIRngHigh( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRngLow( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIRngLow( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIRngLow( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDCOffset( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIDCOffset( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIDCOffset( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIGain( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIGain( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIGain( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAISampAndHoldEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAISampAndHoldEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAISampAndHoldEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIAutoZeroMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIAutoZeroMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIAutoZeroMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIChopEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIChopEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIChopEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDataXferMaxRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIDataXferMaxRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIDataXferMaxRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDataXferCustomThreshold( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIDataXferCustomThreshold( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIDataXferCustomThreshold( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIRawDataCompressionType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIRawDataCompressionType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIRawDataCompressionType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAILossyLSBRemovalCompressedSampSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAILossyLSBRemovalCompressedSampSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAILossyLSBRemovalCompressedSampSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIDevScalingCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAIEnhancedAliasRejectionEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIEnhancedAliasRejectionEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIEnhancedAliasRejectionEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIOpenChanDetectEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIOpenChanDetectEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIOpenChanDetectEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOMax( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOMax( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOMax(taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetAOMin( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOMin( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOMin(taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetAOCustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAOCustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAOCustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOOutputType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetAOVoltageUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAOVoltageUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAOVoltageUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOVoltageCurrentLimit( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOVoltageCurrentLimit( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOVoltageCurrentLimit( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOCurrentUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAOCurrentUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAOCurrentUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFuncGenType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAOFuncGenType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAOFuncGenType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFuncGenFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOFuncGenFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOFuncGenFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFuncGenAmplitude( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOFuncGenAmplitude( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOFuncGenAmplitude( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFuncGenOffset( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOFuncGenOffset( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOFuncGenOffset( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFuncGenSquareDutyCycle( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOFuncGenSquareDutyCycle( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOFuncGenSquareDutyCycle( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFuncGenModulationType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAOFuncGenModulationType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAOFuncGenModulationType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFuncGenFMDeviation( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOFuncGenFMDeviation( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOFuncGenFMDeviation( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOOutputImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOOutputImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOOutputImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOLoadImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOLoadImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOLoadImpedance( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOIdleOutputBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAOIdleOutputBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAOIdleOutputBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAOTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAOTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOResolutionUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAOResolutionUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAOResolutionUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOResolution( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetAODACRngHigh( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAODACRngHigh( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAODACRngHigh( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACRngLow( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAODACRngLow( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAODACRngLow( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACRefConnToGnd( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAODACRefConnToGnd( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAODACRefConnToGnd( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACRefAllowConnToGnd( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAODACRefAllowConnToGnd( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAODACRefAllowConnToGnd( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACRefSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAODACRefSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAODACRefSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACRefExtSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAODACRefExtSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAODACRefExtSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACRefVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAODACRefVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAODACRefVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACOffsetSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAODACOffsetSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAODACOffsetSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACOffsetExtSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAODACOffsetExtSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAODACOffsetExtSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODACOffsetVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAODACOffsetVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAODACOffsetVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOReglitchEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAOReglitchEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAOReglitchEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFilterDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOFilterDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOFilterDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFilterDelayUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAOFilterDelayUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAOFilterDelayUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFilterDelayAdjustment( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOFilterDelayAdjustment( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOFilterDelayAdjustment( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOGain( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAOGain( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAOGain( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAODevScalingCoeff( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAOEnhancedImageRejectionEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAOEnhancedImageRejectionEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAOEnhancedImageRejectionEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIInvertLines( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDIInvertLines( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDIInvertLines( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDINumLines( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDIDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDIDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDIDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDIDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDIDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIDigFltrEnableBusMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDIDigFltrEnableBusMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDIDigFltrEnableBusMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDIDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDIDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDIDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDIDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDIDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDIDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDITristate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDITristate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDITristate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDILogicFamily( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDILogicFamily( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDILogicFamily( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetDIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetDIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDIAcquireOn( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDIAcquireOn( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDIAcquireOn( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOOutputDriveType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDOOutputDriveType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDOOutputDriveType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOInvertLines( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDOInvertLines( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDOInvertLines( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDONumLines( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDOTristate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDOTristate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDOTristate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOLineStatesStartState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDOLineStatesStartState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDOLineStatesStartState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOLineStatesPausedState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDOLineStatesPausedState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDOLineStatesPausedState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOLineStatesDoneState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDOLineStatesDoneState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDOLineStatesDoneState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOLogicFamily( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDOLogicFamily( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDOLogicFamily( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOOvercurrentLimit( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDOOvercurrentLimit( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDOOvercurrentLimit( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOOvercurrentAutoReenable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDOOvercurrentAutoReenable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDOOvercurrentAutoReenable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOOvercurrentReenablePeriod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDOOvercurrentReenablePeriod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDOOvercurrentReenablePeriod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetDOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetDOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetDOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDOGenerateOn( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDOGenerateOn( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDOGenerateOn( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIMax( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIMax( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIMax(taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetCIMin( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIMin( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIMin(taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxGetCICustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICustomScaleName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIMeasType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqMeasMeth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqMeasMeth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqMeasMeth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqEnableAveraging( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqEnableAveraging( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqEnableAveraging( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIFreqDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIFreqDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCIFreqDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodMeasMeth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodMeasMeth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodMeasMeth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodEnableAveraging( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodEnableAveraging( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodEnableAveraging( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPeriodDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPeriodDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPeriodDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesDir( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesDir( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesDir( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesDirTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesDirTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesDirTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountDirTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountDirTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountDirTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountDirLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountDirLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountDirLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountDirDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountDirDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountDirDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountDirDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountDirDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountDirDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountDirDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountDirDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountDirDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountDirDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountDirDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountDirDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountDirDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountDirDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountDirDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesInitialCnt( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesInitialCnt( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesInitialCnt( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetResetCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetResetCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetResetCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesCountResetActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesCountResetActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesCountResetActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICountEdgesGateWhen( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICountEdgesGateWhen( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICountEdgesGateWhen( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDutyCycleTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDutyCycleTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIDutyCycleTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDutyCycleTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDutyCycleTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIDutyCycleTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDutyCycleLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDutyCycleLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIDutyCycleLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDutyCycleDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDutyCycleDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIDutyCycleDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDutyCycleDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIDutyCycleDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIDutyCycleDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDutyCycleDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDutyCycleDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIDutyCycleDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDutyCycleDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIDutyCycleDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIDutyCycleDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDutyCycleStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDutyCycleStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIDutyCycleStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIAngEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIAngEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIAngEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIAngEncoderPulsesPerRev( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIAngEncoderPulsesPerRev( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCIAngEncoderPulsesPerRev( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIAngEncoderInitialAngle( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIAngEncoderInitialAngle( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIAngEncoderInitialAngle( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCILinEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCILinEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCILinEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCILinEncoderDistPerPulse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCILinEncoderDistPerPulse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCILinEncoderDistPerPulse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCILinEncoderInitialPos( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCILinEncoderInitialPos( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCILinEncoderInitialPos( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderDecodingType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderDecodingType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderDecodingType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderAInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderAInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderAInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderAInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderAInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderAInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderAInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderAInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderAInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderAInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderAInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderAInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderAInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderAInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderAInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderAInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderAInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderAInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderAInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderAInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderAInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderAInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderAInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderAInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderBInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderBInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderBInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderBInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderBInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderBInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderBInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderBInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderBInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderBInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderBInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderBInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderBInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderBInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderBInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderBInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderBInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderBInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderBInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderBInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderBInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderBInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderBInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderBInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZInputDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZIndexEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZIndexEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZIndexEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZIndexVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZIndexVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZIndexVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIEncoderZIndexPhase( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIEncoderZIndexPhase( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIEncoderZIndexPhase( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseWidthStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseWidthStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseWidthStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITimestampUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCITimestampUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCITimestampUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITimestampInitialSeconds( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCITimestampInitialSeconds( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCITimestampInitialSeconds( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIGPSSyncMethod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIGPSSyncMethod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIGPSSyncMethod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIGPSSyncSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIGPSSyncSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIGPSSyncSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityAngEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityAngEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityAngEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityAngEncoderPulsesPerRev( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityAngEncoderPulsesPerRev( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityAngEncoderPulsesPerRev( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityLinEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityLinEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityLinEncoderUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityLinEncoderDistPerPulse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityLinEncoderDistPerPulse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityLinEncoderDistPerPulse( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderDecodingType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderDecodingType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderDecodingType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderAInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderAInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderAInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderAInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderAInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderAInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderAInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderAInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderAInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderAInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderAInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderAInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderAInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderAInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderAInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderAInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderAInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderAInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderAInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderAInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderAInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderBInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderBInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderBInputTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderBInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderBInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderBInputTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderBInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderBInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderBInputLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderBInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderBInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderBInputDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderBInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderBInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderBInputDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderBInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderBInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderBInputDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityEncoderBInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityEncoderBInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityEncoderBInputDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityMeasTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIVelocityDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIVelocityDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCIVelocityDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepFirstEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepFirstEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepFirstEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCITwoEdgeSepSecondEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCITwoEdgeSepSecondEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCITwoEdgeSepSecondEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISemiPeriodStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCISemiPeriodStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCISemiPeriodStartingEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseFreqStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseFreqStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseFreqStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTimeStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTimeStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTimeStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksTermCfg( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksLogicLvlBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPulseTicksStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPulseTicksStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPulseTicksStartEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIThreshVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIThreshVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIThreshVoltage( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCICount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetCIOutputState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetCITCReached( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetCICtrTimebaseMasterTimebaseDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCICtrTimebaseMasterTimebaseDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCICtrTimebaseMasterTimebaseDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISampClkOverrunBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCISampClkOverrunBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCISampClkOverrunBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCISampClkOverrunSentinelVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCISampClkOverrunSentinelVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCISampClkOverrunSentinelVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIDataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCIDataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCIUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCIUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCINumPossiblyInvalidSamps( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetCIDupCountPrevent( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCIDupCountPrevent( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCIDupCountPrevent( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIPrescaler( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCIPrescaler( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCIPrescaler( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCIMaxMeasPeriod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCIMaxMeasPeriod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCIMaxMeasPeriod( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOOutputType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseIdleState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseIdleState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseIdleState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseTerm( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseTimeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseTimeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseTimeUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseHighTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseHighTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseHighTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseLowTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseLowTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseLowTime( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseTimeInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseTimeInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseTimeInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseDutyCyc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseDutyCyc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseDutyCyc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseFreqUnits( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseFreq( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseFreqInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseFreqInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseFreqInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseHighTicks( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseHighTicks( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseHighTicks( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseLowTicks( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseLowTicks( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseLowTicks( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseTicksInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOPulseTicksInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCOPulseTicksInitialDelay( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseActiveEdge( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseDigFltrEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseDigFltrMinPulseWidth( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseDigFltrTimebaseSrc( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseDigFltrTimebaseRate( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseDigSyncEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetCOOutputState( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetCOAutoIncrCnt( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOAutoIncrCnt( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCOAutoIncrCnt( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOCtrTimebaseMasterTimebaseDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOCtrTimebaseMasterTimebaseDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCOCtrTimebaseMasterTimebaseDiv( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPulseDone( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetCOEnableInitialDelayOnRetrigger( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCOEnableInitialDelayOnRetrigger( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCOEnableInitialDelayOnRetrigger( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOConstrainedGenMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCOConstrainedGenMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCOConstrainedGenMode( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCOUseOnlyOnBrdMem( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCODataXferMech( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetCODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetCODataXferReqCond( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCOUsbXferReqSize( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCOUsbXferReqCount( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetCOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetCOMemMapEnable( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCOPrescaler( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetCOPrescaler( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetCOPrescaler( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetCORdyForNewVal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetChanType( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetPhysicalChanName( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetChanDescr( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetChanDescr( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetChanDescr( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetChanIsGlobal( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetChanSyncUnlockBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetChanSyncUnlockBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetChanSyncUnlockBehavior( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDevIsSimulated( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevProductCategory( device: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetDevProductType( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevProductNum(device: *const ::std::os::raw::c_char, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetDevSerialNum(device: *const ::std::os::raw::c_char, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetDevAccessoryProductTypes( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAccessoryProductNums( device: *const ::std::os::raw::c_char, data: *mut uInt32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAccessorySerialNums( device: *const ::std::os::raw::c_char, data: *mut uInt32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetCarrierSerialNum( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetFieldDAQDevName( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetFieldDAQBankDevNames( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevChassisModuleDevNames( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAnlgTrigSupported( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevDigTrigSupported( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevTimeTrigSupported( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIPhysicalChans( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAISupportedMeasTypes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIMaxSingleChanRate( device: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIMaxMultiChanRate( device: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIMinRate(device: *const ::std::os::raw::c_char, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetDevAISimultaneousSamplingSupported( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAINumSampTimingEngines( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAISampModes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAINumSyncPulseSrcs( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAITrigUsage(device: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetDevAIVoltageRngs( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIVoltageIntExcitDiscreteVals( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIVoltageIntExcitRangeVals( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIChargeRngs( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAICurrentRngs( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAICurrentIntExcitDiscreteVals( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIBridgeRngs( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIResistanceRngs( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIFreqRngs( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIGains( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAICouplings(device: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetDevAILowpassCutoffFreqDiscreteVals( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAILowpassCutoffFreqRangeVals( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAIDigFltrTypes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIDigFltrLowpassCutoffFreqDiscreteVals( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAIDigFltrLowpassCutoffFreqRangeVals( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAOPhysicalChans( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAOSupportedOutputTypes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAOMaxRate(device: *const ::std::os::raw::c_char, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetDevAOMinRate(device: *const ::std::os::raw::c_char, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetDevAOSampClkSupported( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAONumSampTimingEngines( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAOSampModes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAONumSyncPulseSrcs( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAOTrigUsage(device: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetDevAOVoltageRngs( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAOCurrentRngs( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevAOGains( device: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevDILines( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevDIPorts( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevDIMaxRate(device: *const ::std::os::raw::c_char, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetDevDINumSampTimingEngines( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevDITrigUsage(device: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetDevDOLines( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevDOPorts( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevDOMaxRate(device: *const ::std::os::raw::c_char, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetDevDONumSampTimingEngines( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevDOTrigUsage(device: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetDevCIPhysicalChans( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCISupportedMeasTypes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCITrigUsage(device: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetDevCISampClkSupported( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCISampModes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCIMaxSize(device: *const ::std::os::raw::c_char, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetDevCIMaxTimebase( device: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetDevCOPhysicalChans( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCOSupportedOutputTypes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCOSampClkSupported( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCOSampModes( device: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCOTrigUsage(device: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetDevCOMaxSize(device: *const ::std::os::raw::c_char, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetDevCOMaxTimebase( device: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetDevTEDSHWTEDSSupported( device: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetDevNumDMAChans( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevBusType(device: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetDevPCIBusNum(device: *const ::std::os::raw::c_char, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetDevPCIDevNum(device: *const ::std::os::raw::c_char, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetDevPXIChassisNum( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevPXISlotNum(device: *const ::std::os::raw::c_char, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetDevCompactDAQChassisDevName( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCompactDAQSlotNum( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCompactRIOChassisDevName( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevCompactRIOSlotNum( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevTCPIPHostname( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevTCPIPEthernetIP( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevTCPIPWirelessIP( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevTerminals( device: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevNumTimeTrigs( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDevNumTimestampEngines( device: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetExportedAIConvClkOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedAIConvClkOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedAIConvClkOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAIConvClkPulsePolarity( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetExported10MHzRefClkOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExported10MHzRefClkOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExported10MHzRefClkOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExported20MHzTimebaseOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExported20MHzTimebaseOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExported20MHzTimebaseOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedSampClkOutputBehavior(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetExportedSampClkOutputBehavior(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedSampClkOutputBehavior(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedSampClkOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedSampClkOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedSampClkOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedSampClkDelayOffset(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetExportedSampClkDelayOffset(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetExportedSampClkDelayOffset(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedSampClkPulsePolarity(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetExportedSampClkPulsePolarity(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedSampClkPulsePolarity(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedSampClkTimebaseOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedSampClkTimebaseOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedSampClkTimebaseOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedDividedSampClkTimebaseOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedDividedSampClkTimebaseOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedDividedSampClkTimebaseOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAdvTrigOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedAdvTrigOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedAdvTrigOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAdvTrigPulsePolarity(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetExportedAdvTrigPulseWidthUnits( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedAdvTrigPulseWidthUnits(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedAdvTrigPulseWidthUnits(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAdvTrigPulseWidth(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetExportedAdvTrigPulseWidth(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetExportedAdvTrigPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedPauseTrigOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedPauseTrigOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedPauseTrigOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedPauseTrigLvlActiveLvl(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetExportedPauseTrigLvlActiveLvl(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedPauseTrigLvlActiveLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedRefTrigOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedRefTrigOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedRefTrigOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedRefTrigPulsePolarity(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetExportedRefTrigPulsePolarity(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedRefTrigPulsePolarity(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedStartTrigOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedStartTrigOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedStartTrigOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedStartTrigPulsePolarity( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedStartTrigPulsePolarity(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedStartTrigPulsePolarity(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAdvCmpltEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedAdvCmpltEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedAdvCmpltEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAdvCmpltEventDelay(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetExportedAdvCmpltEventDelay(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetExportedAdvCmpltEventDelay(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAdvCmpltEventPulsePolarity( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedAdvCmpltEventPulsePolarity(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedAdvCmpltEventPulsePolarity(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAdvCmpltEventPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetExportedAdvCmpltEventPulseWidth(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetExportedAdvCmpltEventPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAIHoldCmpltEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedAIHoldCmpltEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedAIHoldCmpltEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedAIHoldCmpltEventPulsePolarity( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedAIHoldCmpltEventPulsePolarity( taskHandle: TaskHandle, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedAIHoldCmpltEventPulsePolarity(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedChangeDetectEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedChangeDetectEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedChangeDetectEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedChangeDetectEventPulsePolarity( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedChangeDetectEventPulsePolarity( taskHandle: TaskHandle, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedChangeDetectEventPulsePolarity(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedCtrOutEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedCtrOutEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedCtrOutEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedCtrOutEventOutputBehavior( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedCtrOutEventOutputBehavior(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedCtrOutEventOutputBehavior(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedCtrOutEventPulsePolarity( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedCtrOutEventPulsePolarity(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedCtrOutEventPulsePolarity(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedCtrOutEventToggleIdleState( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedCtrOutEventToggleIdleState(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedCtrOutEventToggleIdleState(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedHshkEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedHshkEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedHshkEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedHshkEventOutputBehavior( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedHshkEventOutputBehavior(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedHshkEventOutputBehavior(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedHshkEventDelay(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetExportedHshkEventDelay(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetExportedHshkEventDelay(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedHshkEventInterlockedAssertedLvl( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedHshkEventInterlockedAssertedLvl( taskHandle: TaskHandle, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedHshkEventInterlockedAssertedLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedHshkEventInterlockedAssertOnStart( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedHshkEventInterlockedAssertOnStart( taskHandle: TaskHandle, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedHshkEventInterlockedAssertOnStart(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedHshkEventInterlockedDeassertDelay( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetExportedHshkEventInterlockedDeassertDelay( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetExportedHshkEventInterlockedDeassertDelay(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedHshkEventPulsePolarity( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedHshkEventPulsePolarity(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetExportedHshkEventPulsePolarity(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedHshkEventPulseWidth(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetExportedHshkEventPulseWidth(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetExportedHshkEventPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedRdyForXferEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedRdyForXferEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedRdyForXferEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedRdyForXferEventLvlActiveLvl( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedRdyForXferEventLvlActiveLvl( taskHandle: TaskHandle, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedRdyForXferEventLvlActiveLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedRdyForXferEventDeassertCond( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedRdyForXferEventDeassertCond( taskHandle: TaskHandle, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedRdyForXferEventDeassertCond(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedRdyForXferEventDeassertCondCustomThreshold( taskHandle: TaskHandle, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedRdyForXferEventDeassertCondCustomThreshold( taskHandle: TaskHandle, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedRdyForXferEventDeassertCondCustomThreshold( taskHandle: TaskHandle, ) -> int32; } extern "C" { pub fn DAQmxGetExportedDataActiveEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedDataActiveEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedDataActiveEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedDataActiveEventLvlActiveLvl( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedDataActiveEventLvlActiveLvl( taskHandle: TaskHandle, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedDataActiveEventLvlActiveLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedRdyForStartEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedRdyForStartEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedRdyForStartEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedRdyForStartEventLvlActiveLvl( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedRdyForStartEventLvlActiveLvl( taskHandle: TaskHandle, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetExportedRdyForStartEventLvlActiveLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedSyncPulseEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedSyncPulseEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedSyncPulseEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetExportedWatchdogExpiredEventOutputTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetExportedWatchdogExpiredEventOutputTerm( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetExportedWatchdogExpiredEventOutputTerm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetPersistedChanAuthor( channel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPersistedChanAllowInteractiveEditing( channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPersistedChanAllowInteractiveDeletion( channel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPersistedScaleAuthor( scaleName: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPersistedScaleAllowInteractiveEditing( scaleName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPersistedScaleAllowInteractiveDeletion( scaleName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPersistedTaskAuthor( taskName: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPersistedTaskAllowInteractiveEditing( taskName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPersistedTaskAllowInteractiveDeletion( taskName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAISupportedMeasTypes( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAITermCfgs( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAIInputSrcs( physicalChannel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAISensorPowerTypes( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAISensorPowerVoltageRangeVals( physicalChannel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAIPowerControlVoltage( physicalChannel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetPhysicalChanAIPowerControlVoltage( physicalChannel: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetPhysicalChanAIPowerControlVoltage( physicalChannel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAIPowerControlEnable( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetPhysicalChanAIPowerControlEnable( physicalChannel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetPhysicalChanAIPowerControlEnable( physicalChannel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAIPowerControlType( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetPhysicalChanAIPowerControlType( physicalChannel: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetPhysicalChanAIPowerControlType( physicalChannel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAISensorPowerOpenChan( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAISensorPowerOvercurrent( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAOSupportedOutputTypes( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAOSupportedPowerUpOutputTypes( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAOTermCfgs( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAOManualControlEnable( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetPhysicalChanAOManualControlEnable( physicalChannel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetPhysicalChanAOManualControlEnable( physicalChannel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAOManualControlShortDetected( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAOManualControlAmplitude( physicalChannel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanAOManualControlFreq( physicalChannel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetAOPowerAmpChannelEnable( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAOPowerAmpChannelEnable( physicalChannel: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAOPowerAmpChannelEnable( physicalChannel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOPowerAmpScalingCoeff( physicalChannel: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAOPowerAmpOvercurrent( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetAOPowerAmpGain( physicalChannel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetAOPowerAmpOffset( physicalChannel: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanDIPortWidth( physicalChannel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanDISampClkSupported( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanDISampModes( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanDIChangeDetectSupported( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanDOPortWidth( physicalChannel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanDOSampClkSupported( physicalChannel: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanDOSampModes( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanCISupportedMeasTypes( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanCOSupportedOutputTypes( physicalChannel: *const ::std::os::raw::c_char, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanTEDSMfgID( physicalChannel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanTEDSModelNum( physicalChannel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanTEDSSerialNum( physicalChannel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanTEDSVersionNum( physicalChannel: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanTEDSVersionLetter( physicalChannel: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanTEDSBitStream( physicalChannel: *const ::std::os::raw::c_char, data: *mut uInt8, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetPhysicalChanTEDSTemplateIDs( physicalChannel: *const ::std::os::raw::c_char, data: *mut uInt32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadRelativeTo(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetReadRelativeTo(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetReadRelativeTo(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetReadOffset(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetReadOffset(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetReadOffset(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetReadChannelsToRead( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetReadChannelsToRead( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetReadChannelsToRead(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetReadReadAllAvailSamp(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetReadReadAllAvailSamp(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetReadReadAllAvailSamp(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetReadAutoStart(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetReadAutoStart(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetReadAutoStart(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetReadOverWrite(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetReadOverWrite(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetReadOverWrite(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetLoggingFilePath( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetLoggingFilePath( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetLoggingFilePath(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetLoggingMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetLoggingMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetLoggingMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetLoggingTDMSGroupName( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetLoggingTDMSGroupName( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetLoggingTDMSGroupName(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetLoggingTDMSOperation(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetLoggingTDMSOperation(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetLoggingTDMSOperation(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetLoggingPause(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetLoggingPause(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetLoggingPause(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetLoggingSampsPerFile(taskHandle: TaskHandle, data: *mut uInt64) -> int32; } extern "C" { pub fn DAQmxSetLoggingSampsPerFile(taskHandle: TaskHandle, data: uInt64) -> int32; } extern "C" { pub fn DAQmxResetLoggingSampsPerFile(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetLoggingFileWriteSize(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetLoggingFileWriteSize(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetLoggingFileWriteSize(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetLoggingFilePreallocationSize(taskHandle: TaskHandle, data: *mut uInt64) -> int32; } extern "C" { pub fn DAQmxSetLoggingFilePreallocationSize(taskHandle: TaskHandle, data: uInt64) -> int32; } extern "C" { pub fn DAQmxResetLoggingFilePreallocationSize(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetReadCurrReadPos(taskHandle: TaskHandle, data: *mut uInt64) -> int32; } extern "C" { pub fn DAQmxGetReadAvailSampPerChan(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetReadTotalSampPerChanAcquired(taskHandle: TaskHandle, data: *mut uInt64) -> int32; } extern "C" { pub fn DAQmxGetReadCommonModeRangeErrorChansExist( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetReadCommonModeRangeErrorChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadExcitFaultChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetReadExcitFaultChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOvercurrentChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetReadOvercurrentChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOvertemperatureChansExist( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOvertemperatureChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOpenChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetReadOpenChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOpenChansDetails( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOpenCurrentLoopChansExist( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOpenCurrentLoopChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOpenThrmcplChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetReadOpenThrmcplChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadOverloadedChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetReadOverloadedChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadPLLUnlockedChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetReadPLLUnlockedChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadSyncUnlockedChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetReadSyncUnlockedChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadAccessoryInsertionOrRemovalDetected( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetReadDevsWithInsertedOrRemovedAccessories( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetReadChangeDetectHasOverflowed( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetReadRawDataWidth(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetReadNumChans(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetReadDigitalLinesBytesPerChan(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetReadWaitMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetReadWaitMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetReadWaitMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetReadSleepTime(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetReadSleepTime(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetReadSleepTime(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRealTimeConvLateErrorsToWarnings( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetRealTimeConvLateErrorsToWarnings(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetRealTimeConvLateErrorsToWarnings(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRealTimeNumOfWarmupIters(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetRealTimeNumOfWarmupIters(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetRealTimeNumOfWarmupIters(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRealTimeWaitForNextSampClkWaitMode( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetRealTimeWaitForNextSampClkWaitMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetRealTimeWaitForNextSampClkWaitMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRealTimeReportMissedSamp(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetRealTimeReportMissedSamp(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetRealTimeReportMissedSamp(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRealTimeWriteRecoveryMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetRealTimeWriteRecoveryMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetRealTimeWriteRecoveryMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetScaleDescr( scaleName: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetScaleDescr( scaleName: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetScaleScaledUnits( scaleName: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetScaleScaledUnits( scaleName: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetScalePreScaledUnits( scaleName: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetScalePreScaledUnits( scaleName: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxGetScaleType(scaleName: *const ::std::os::raw::c_char, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxGetScaleLinSlope( scaleName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetScaleLinSlope(scaleName: *const ::std::os::raw::c_char, data: float64) -> int32; } extern "C" { pub fn DAQmxGetScaleLinYIntercept( scaleName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetScaleLinYIntercept( scaleName: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxGetScaleMapScaledMax( scaleName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetScaleMapScaledMax( scaleName: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxGetScaleMapPreScaledMax( scaleName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetScaleMapPreScaledMax( scaleName: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxGetScaleMapScaledMin( scaleName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetScaleMapScaledMin( scaleName: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxGetScaleMapPreScaledMin( scaleName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetScaleMapPreScaledMin( scaleName: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxGetScalePolyForwardCoeff( scaleName: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetScalePolyForwardCoeff( scaleName: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetScalePolyReverseCoeff( scaleName: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetScalePolyReverseCoeff( scaleName: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetScaleTableScaledVals( scaleName: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetScaleTableScaledVals( scaleName: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetScaleTablePreScaledVals( scaleName: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetScaleTablePreScaledVals( scaleName: *const ::std::os::raw::c_char, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanUsage( switchChannelName: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetSwitchChanUsage( switchChannelName: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanAnlgBusSharingEnable( switchChannelName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetSwitchChanAnlgBusSharingEnable( switchChannelName: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxACCarryCurrent( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxACSwitchCurrent( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxACCarryPwr( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxACSwitchPwr( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxDCCarryCurrent( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxDCSwitchCurrent( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxDCCarryPwr( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxDCSwitchPwr( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxACVoltage( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanMaxDCVoltage( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanWireMode( switchChannelName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanBandwidth( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchChanImpedance( switchChannelName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevSettlingTime( deviceName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetSwitchDevSettlingTime( deviceName: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevAutoConnAnlgBus( deviceName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetSwitchDevAutoConnAnlgBus( deviceName: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevPwrDownLatchRelaysAfterSettling( deviceName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetSwitchDevPwrDownLatchRelaysAfterSettling( deviceName: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevSettled( deviceName: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevRelayList( deviceName: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevNumRelays( deviceName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevSwitchChanList( deviceName: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevNumSwitchChans( deviceName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevNumRows( deviceName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevNumColumns( deviceName: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevTopology( deviceName: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchDevTemperature( deviceName: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetSwitchScanBreakMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSwitchScanBreakMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSwitchScanBreakMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSwitchScanRepeatMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSwitchScanRepeatMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSwitchScanRepeatMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSwitchScanWaitingForAdv(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetSysGlobalChans(data: *mut ::std::os::raw::c_char, bufferSize: uInt32) -> int32; } extern "C" { pub fn DAQmxGetSysScales(data: *mut ::std::os::raw::c_char, bufferSize: uInt32) -> int32; } extern "C" { pub fn DAQmxGetSysTasks(data: *mut ::std::os::raw::c_char, bufferSize: uInt32) -> int32; } extern "C" { pub fn DAQmxGetSysDevNames(data: *mut ::std::os::raw::c_char, bufferSize: uInt32) -> int32; } extern "C" { pub fn DAQmxGetSysNIDAQMajorVersion(data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetSysNIDAQMinorVersion(data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetSysNIDAQUpdateVersion(data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetTaskName( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetTaskChannels( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetTaskNumChans(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetTaskDevices( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetTaskNumDevices(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetTaskComplete(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetSampQuantSampMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSampQuantSampMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSampQuantSampMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampQuantSampPerChan(taskHandle: TaskHandle, data: *mut uInt64) -> int32; } extern "C" { pub fn DAQmxSetSampQuantSampPerChan(taskHandle: TaskHandle, data: uInt64) -> int32; } extern "C" { pub fn DAQmxResetSampQuantSampPerChan(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampTimingType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSampTimingType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSampTimingType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetSampClkRate(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetSampClkRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkMaxRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetSampClkSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetSampClkSrc(taskHandle: TaskHandle, data: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxResetSampClkSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkActiveEdge(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSampClkActiveEdge(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSampClkActiveEdge(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkOverrunBehavior(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSampClkOverrunBehavior(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSampClkOverrunBehavior(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkUnderflowBehavior(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSampClkUnderflowBehavior(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSampClkUnderflowBehavior(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkTimebaseDiv(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetSampClkTimebaseDiv(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetSampClkTimebaseDiv(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSampClkTimebaseRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetSampClkTimebaseRate(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetSampClkTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetSampClkTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetSampClkTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkTimebaseActiveEdge(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSampClkTimebaseActiveEdge(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSampClkTimebaseActiveEdge(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkTimebaseMasterTimebaseDiv( taskHandle: TaskHandle, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetSampClkTimebaseMasterTimebaseDiv(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetSampClkTimebaseMasterTimebaseDiv(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkTimebaseTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSampClkDigFltrEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetSampClkDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetSampClkDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkDigFltrMinPulseWidth(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetSampClkDigFltrMinPulseWidth(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetSampClkDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetSampClkDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetSampClkDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkDigFltrTimebaseRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetSampClkDigFltrTimebaseRate(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetSampClkDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkDigSyncEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetSampClkDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetSampClkDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampClkWriteWfmUseInitialWfmDT( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetSampClkWriteWfmUseInitialWfmDT(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetSampClkWriteWfmUseInitialWfmDT(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetHshkDelayAfterXfer(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetHshkDelayAfterXfer(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetHshkDelayAfterXfer(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetHshkStartCond(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetHshkStartCond(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetHshkStartCond(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetHshkSampleInputDataWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetHshkSampleInputDataWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetHshkSampleInputDataWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetChangeDetectDIRisingEdgePhysicalChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetChangeDetectDIRisingEdgePhysicalChans( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetChangeDetectDIRisingEdgePhysicalChans(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetChangeDetectDIFallingEdgePhysicalChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetChangeDetectDIFallingEdgePhysicalChans( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetChangeDetectDIFallingEdgePhysicalChans(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetChangeDetectDITristate(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetChangeDetectDITristate(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetChangeDetectDITristate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetOnDemandSimultaneousAOEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetOnDemandSimultaneousAOEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetOnDemandSimultaneousAOEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetImplicitUnderflowBehavior(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetImplicitUnderflowBehavior(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetImplicitUnderflowBehavior(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAIConvRate(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAIConvRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvRateEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvRateEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvRateEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvMaxRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetAIConvMaxRateEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvSrc(taskHandle: TaskHandle, data: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxResetAIConvSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvActiveEdge(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAIConvActiveEdge(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAIConvActiveEdge(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvActiveEdgeEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvActiveEdgeEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvActiveEdgeEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvTimebaseDiv(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetAIConvTimebaseDiv(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetAIConvTimebaseDiv(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvTimebaseDivEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvTimebaseDivEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvTimebaseDivEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvTimebaseSrc(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAIConvTimebaseSrc(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAIConvTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvTimebaseSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvTimebaseSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvTimebaseSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDelayFromSampClkDelayUnits(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDelayFromSampClkDelayUnits(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDelayFromSampClkDelayUnits(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDelayFromSampClkDelayUnitsEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetDelayFromSampClkDelayUnitsEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetDelayFromSampClkDelayUnitsEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetDelayFromSampClkDelay(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetDelayFromSampClkDelay(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetDelayFromSampClkDelay(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDelayFromSampClkDelayEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDelayFromSampClkDelayEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDelayFromSampClkDelayEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigFltrEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigFltrEnableEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigFltrEnableEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigFltrEnableEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigFltrMinPulseWidth(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigFltrMinPulseWidth(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigFltrMinPulseWidthEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigFltrMinPulseWidthEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigFltrMinPulseWidthEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigFltrTimebaseSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigFltrTimebaseSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigFltrTimebaseSrcEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigFltrTimebaseRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigFltrTimebaseRate(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigFltrTimebaseRateEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigFltrTimebaseRateEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigFltrTimebaseRateEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigSyncEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAIConvDigSyncEnableEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAIConvDigSyncEnableEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetAIConvDigSyncEnableEx( taskHandle: TaskHandle, deviceNames: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetMasterTimebaseRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetMasterTimebaseRate(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetMasterTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetMasterTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetMasterTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetMasterTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefClkRate(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetRefClkRate(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetRefClkRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefClkSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetRefClkSrc(taskHandle: TaskHandle, data: *const ::std::os::raw::c_char) -> int32; } extern "C" { pub fn DAQmxResetRefClkSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSyncPulseType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSyncPulseType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetSyncPulseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetSyncPulseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseTimeWhen(taskHandle: TaskHandle, data: *mut CVIAbsoluteTime) -> int32; } extern "C" { pub fn DAQmxSetSyncPulseTimeWhen(taskHandle: TaskHandle, data: CVIAbsoluteTime) -> int32; } extern "C" { pub fn DAQmxResetSyncPulseTimeWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseTimeTimescale(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSyncPulseTimeTimescale(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSyncPulseTimeTimescale(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseSyncTime(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseMinDelayToStart(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetSyncPulseMinDelayToStart(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetSyncPulseMinDelayToStart(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseResetTime(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseResetDelay(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetSyncPulseResetDelay(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetSyncPulseResetDelay(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSyncPulseTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSyncClkInterval(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetSyncClkInterval(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetSyncClkInterval(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetSampTimingEngine(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetSampTimingEngine(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetSampTimingEngine(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetFirstSampTimestampEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetFirstSampTimestampEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetFirstSampTimestampEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetFirstSampTimestampTimescale(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetFirstSampTimestampTimescale(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetFirstSampTimestampTimescale(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetFirstSampTimestampVal( taskHandle: TaskHandle, data: *mut CVIAbsoluteTime, ) -> int32; } extern "C" { pub fn DAQmxGetFirstSampClkWhen(taskHandle: TaskHandle, data: *mut CVIAbsoluteTime) -> int32; } extern "C" { pub fn DAQmxSetFirstSampClkWhen(taskHandle: TaskHandle, data: CVIAbsoluteTime) -> int32; } extern "C" { pub fn DAQmxResetFirstSampClkWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetFirstSampClkTimescale(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetFirstSampClkTimescale(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetFirstSampClkTimescale(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetStartTrigType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetStartTrigType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeStartTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeStartTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeStartTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeStartTrigEdge(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeStartTrigEdge(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeStartTrigEdge(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeStartTrigDigFltrEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeStartTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeStartTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeStartTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeStartTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeStartTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeStartTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeStartTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeStartTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeStartTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeStartTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeStartTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeStartTrigDigSyncEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeStartTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeStartTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternStartTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigPatternStartTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigPatternStartTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternStartTrigPattern( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigPatternStartTrigPattern( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigPatternStartTrigPattern(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternStartTrigWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigPatternStartTrigWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigPatternStartTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigSlope(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigSlope(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigSlope(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigLvl(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigLvl(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigHyst(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigHyst(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigHyst(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigCoupling(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigCoupling(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigCoupling(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigDigFltrEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeStartTrigDigSyncEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeStartTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeStartTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeStartTrigSrcs( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeStartTrigSrcs( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeStartTrigSrcs(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeStartTrigSlopes( taskHandle: TaskHandle, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeStartTrigSlopes( taskHandle: TaskHandle, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeStartTrigSlopes(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeStartTrigLvls( taskHandle: TaskHandle, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeStartTrigLvls( taskHandle: TaskHandle, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeStartTrigLvls(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeStartTrigHysts( taskHandle: TaskHandle, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeStartTrigHysts( taskHandle: TaskHandle, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeStartTrigHysts(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeStartTrigCouplings( taskHandle: TaskHandle, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeStartTrigCouplings( taskHandle: TaskHandle, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeStartTrigCouplings(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigTop(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigTop(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigTop(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigBtm(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigBtm(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigBtm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigCoupling(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigCoupling(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigCoupling(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigDigFltrEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinStartTrigDigSyncEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinStartTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinStartTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigTrigWhen(taskHandle: TaskHandle, data: *mut CVIAbsoluteTime) -> int32; } extern "C" { pub fn DAQmxSetStartTrigTrigWhen(taskHandle: TaskHandle, data: CVIAbsoluteTime) -> int32; } extern "C" { pub fn DAQmxResetStartTrigTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigTimescale(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetStartTrigTimescale(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetStartTrigTimescale(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigTimestampEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetStartTrigTimestampEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetStartTrigTimestampEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigTimestampTimescale(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetStartTrigTimestampTimescale(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetStartTrigTimestampTimescale(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigTimestampVal( taskHandle: TaskHandle, data: *mut CVIAbsoluteTime, ) -> int32; } extern "C" { pub fn DAQmxGetStartTrigDelay(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetStartTrigDelay(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetStartTrigDelay(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigDelayUnits(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetStartTrigDelayUnits(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetStartTrigDelayUnits(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigRetriggerable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetStartTrigRetriggerable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetStartTrigRetriggerable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigTrigWin(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetStartTrigTrigWin(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetStartTrigTrigWin(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigRetriggerWin(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetStartTrigRetriggerWin(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetStartTrigRetriggerWin(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetStartTrigMaxNumTrigsToDetect(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetStartTrigMaxNumTrigsToDetect(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetStartTrigMaxNumTrigsToDetect(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetRefTrigType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetRefTrigType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigPretrigSamples(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetRefTrigPretrigSamples(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetRefTrigPretrigSamples(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeRefTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeRefTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeRefTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeRefTrigEdge(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeRefTrigEdge(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeRefTrigEdge(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeRefTrigDigFltrEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeRefTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeRefTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeRefTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeRefTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeRefTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeRefTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeRefTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeRefTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeRefTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeRefTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeRefTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeRefTrigDigSyncEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeRefTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeRefTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternRefTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigPatternRefTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigPatternRefTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternRefTrigPattern( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigPatternRefTrigPattern( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigPatternRefTrigPattern(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternRefTrigWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigPatternRefTrigWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigPatternRefTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigSlope(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigSlope(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigSlope(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigLvl(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigLvl(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigHyst(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigHyst(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigHyst(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigCoupling(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigCoupling(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigCoupling(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigDigFltrEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgEdgeRefTrigDigSyncEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetAnlgEdgeRefTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgEdgeRefTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeRefTrigSrcs( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeRefTrigSrcs( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeRefTrigSrcs(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeRefTrigSlopes( taskHandle: TaskHandle, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeRefTrigSlopes( taskHandle: TaskHandle, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeRefTrigSlopes(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeRefTrigLvls( taskHandle: TaskHandle, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeRefTrigLvls( taskHandle: TaskHandle, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeRefTrigLvls(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeRefTrigHysts( taskHandle: TaskHandle, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeRefTrigHysts( taskHandle: TaskHandle, data: *mut float64, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeRefTrigHysts(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgMultiEdgeRefTrigCouplings( taskHandle: TaskHandle, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgMultiEdgeRefTrigCouplings( taskHandle: TaskHandle, data: *mut int32, arraySizeInElements: uInt32, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgMultiEdgeRefTrigCouplings(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigTop(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigTop(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigTop(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigBtm(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigBtm(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigBtm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigCoupling(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigCoupling(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigCoupling(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigDigFltrEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinRefTrigDigSyncEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinRefTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinRefTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigAutoTrigEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetRefTrigAutoTrigEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetRefTrigAutoTrigEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigAutoTriggered(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetRefTrigTimestampEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetRefTrigTimestampEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetRefTrigTimestampEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigTimestampTimescale(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetRefTrigTimestampTimescale(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetRefTrigTimestampTimescale(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigTimestampVal(taskHandle: TaskHandle, data: *mut CVIAbsoluteTime) -> int32; } extern "C" { pub fn DAQmxGetRefTrigDelay(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetRefTrigDelay(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetRefTrigDelay(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigRetriggerable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetRefTrigRetriggerable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetRefTrigRetriggerable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigTrigWin(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetRefTrigTrigWin(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetRefTrigTrigWin(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigRetriggerWin(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetRefTrigRetriggerWin(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetRefTrigRetriggerWin(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetRefTrigMaxNumTrigsToDetect(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxSetRefTrigMaxNumTrigsToDetect(taskHandle: TaskHandle, data: uInt32) -> int32; } extern "C" { pub fn DAQmxResetRefTrigMaxNumTrigsToDetect(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAdvTrigType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAdvTrigType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAdvTrigType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeAdvTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeAdvTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeAdvTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeAdvTrigEdge(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeAdvTrigEdge(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeAdvTrigEdge(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeAdvTrigDigFltrEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeAdvTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeAdvTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetHshkTrigType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetHshkTrigType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetHshkTrigType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetInterlockedHshkTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetInterlockedHshkTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetInterlockedHshkTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetInterlockedHshkTrigAssertedLvl( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetInterlockedHshkTrigAssertedLvl(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetInterlockedHshkTrigAssertedLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetPauseTrigType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetPauseTrigType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetPauseTrigType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetPauseTrigTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigLvl(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigLvl(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigLvl(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigHyst(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigHyst(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigHyst(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigCoupling(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigCoupling(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigCoupling(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigDigFltrEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgLvlPauseTrigDigSyncEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgLvlPauseTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgLvlPauseTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigTop(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigTop(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigTop(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigBtm(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigBtm(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigBtm(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigCoupling(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigCoupling(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigCoupling(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigDigFltrEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetAnlgWinPauseTrigDigSyncEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetAnlgWinPauseTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetAnlgWinPauseTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigLvlPauseTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigLvlPauseTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigLvlPauseTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigLvlPauseTrigWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigLvlPauseTrigWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigLvlPauseTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigLvlPauseTrigDigFltrEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetDigLvlPauseTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigLvlPauseTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigLvlPauseTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDigLvlPauseTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDigLvlPauseTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigLvlPauseTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigLvlPauseTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigLvlPauseTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigLvlPauseTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDigLvlPauseTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDigLvlPauseTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigLvlPauseTrigDigSyncEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetDigLvlPauseTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigLvlPauseTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternPauseTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigPatternPauseTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigPatternPauseTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternPauseTrigPattern( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigPatternPauseTrigPattern( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigPatternPauseTrigPattern(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigPatternPauseTrigWhen(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigPatternPauseTrigWhen(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigPatternPauseTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetArmStartTrigType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetArmStartTrigType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetArmStartTrigType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetArmStartTerm( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeArmStartTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeArmStartTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeArmStartTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeArmStartTrigEdge(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeArmStartTrigEdge(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeArmStartTrigEdge(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeArmStartTrigDigFltrEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeArmStartTrigDigFltrEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeArmStartTrigDigFltrEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeArmStartTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeArmStartTrigDigFltrMinPulseWidth( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeArmStartTrigDigFltrMinPulseWidth(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeArmStartTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeArmStartTrigDigFltrTimebaseSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeArmStartTrigDigFltrTimebaseSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeArmStartTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeArmStartTrigDigFltrTimebaseRate( taskHandle: TaskHandle, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeArmStartTrigDigFltrTimebaseRate(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeArmStartTrigDigSyncEnable( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeArmStartTrigDigSyncEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeArmStartTrigDigSyncEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetArmStartTrigTrigWhen( taskHandle: TaskHandle, data: *mut CVIAbsoluteTime, ) -> int32; } extern "C" { pub fn DAQmxSetArmStartTrigTrigWhen(taskHandle: TaskHandle, data: CVIAbsoluteTime) -> int32; } extern "C" { pub fn DAQmxResetArmStartTrigTrigWhen(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetArmStartTrigTimescale(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetArmStartTrigTimescale(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetArmStartTrigTimescale(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetArmStartTrigTimestampEnable(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxSetArmStartTrigTimestampEnable(taskHandle: TaskHandle, data: bool32) -> int32; } extern "C" { pub fn DAQmxResetArmStartTrigTimestampEnable(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetArmStartTrigTimestampTimescale( taskHandle: TaskHandle, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetArmStartTrigTimestampTimescale(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetArmStartTrigTimestampTimescale(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetArmStartTrigTimestampVal( taskHandle: TaskHandle, data: *mut CVIAbsoluteTime, ) -> int32; } extern "C" { pub fn DAQmxGetTriggerSyncType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetTriggerSyncType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetTriggerSyncType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWatchdogTimeout(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetWatchdogTimeout(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetWatchdogTimeout(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWatchdogExpirTrigType(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetWatchdogExpirTrigType(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetWatchdogExpirTrigType(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWatchdogExpirTrigTrigOnNetworkConnLoss( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxSetWatchdogExpirTrigTrigOnNetworkConnLoss( taskHandle: TaskHandle, data: bool32, ) -> int32; } extern "C" { pub fn DAQmxResetWatchdogExpirTrigTrigOnNetworkConnLoss(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeWatchdogExpirTrigSrc( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeWatchdogExpirTrigSrc( taskHandle: TaskHandle, data: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeWatchdogExpirTrigSrc(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetDigEdgeWatchdogExpirTrigEdge(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetDigEdgeWatchdogExpirTrigEdge(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetDigEdgeWatchdogExpirTrigEdge(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWatchdogDOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetWatchdogDOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetWatchdogDOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetWatchdogAOOutputType( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetWatchdogAOOutputType( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetWatchdogAOOutputType( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetWatchdogAOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, data: *mut float64, ) -> int32; } extern "C" { pub fn DAQmxSetWatchdogAOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, data: float64, ) -> int32; } extern "C" { pub fn DAQmxResetWatchdogAOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetWatchdogCOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, data: *mut int32, ) -> int32; } extern "C" { pub fn DAQmxSetWatchdogCOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, data: int32, ) -> int32; } extern "C" { pub fn DAQmxResetWatchdogCOExpirState( taskHandle: TaskHandle, lines: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetWatchdogHasExpired(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetWriteRelativeTo(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetWriteRelativeTo(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetWriteRelativeTo(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWriteOffset(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetWriteOffset(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetWriteOffset(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWriteRegenMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetWriteRegenMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetWriteRegenMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWriteCurrWritePos(taskHandle: TaskHandle, data: *mut uInt64) -> int32; } extern "C" { pub fn DAQmxGetWriteOvercurrentChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetWriteOvercurrentChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteOvertemperatureChansExist( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteOvertemperatureChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteExternalOvervoltageChansExist( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteExternalOvervoltageChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteOverloadedChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetWriteOverloadedChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteOpenCurrentLoopChansExist( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteOpenCurrentLoopChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWritePowerSupplyFaultChansExist( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetWritePowerSupplyFaultChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteSyncUnlockedChansExist(taskHandle: TaskHandle, data: *mut bool32) -> int32; } extern "C" { pub fn DAQmxGetWriteSyncUnlockedChans( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteSpaceAvail(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetWriteTotalSampPerChanGenerated( taskHandle: TaskHandle, data: *mut uInt64, ) -> int32; } extern "C" { pub fn DAQmxGetWriteAccessoryInsertionOrRemovalDetected( taskHandle: TaskHandle, data: *mut bool32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteDevsWithInsertedOrRemovedAccessories( taskHandle: TaskHandle, data: *mut ::std::os::raw::c_char, bufferSize: uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetWriteRawDataWidth(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetWriteNumChans(taskHandle: TaskHandle, data: *mut uInt32) -> int32; } extern "C" { pub fn DAQmxGetWriteWaitMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetWriteWaitMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetWriteWaitMode(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWriteSleepTime(taskHandle: TaskHandle, data: *mut float64) -> int32; } extern "C" { pub fn DAQmxSetWriteSleepTime(taskHandle: TaskHandle, data: float64) -> int32; } extern "C" { pub fn DAQmxResetWriteSleepTime(taskHandle: TaskHandle) -> int32; } extern "C" { pub fn DAQmxGetWriteDigitalLinesBytesPerChan( taskHandle: TaskHandle, data: *mut uInt32, ) -> int32; } extern "C" { pub fn DAQmxGetSampClkTimingResponseMode(taskHandle: TaskHandle, data: *mut int32) -> int32; } extern "C" { pub fn DAQmxSetSampClkTimingResponseMode(taskHandle: TaskHandle, data: int32) -> int32; } extern "C" { pub fn DAQmxResetSampClkTimingResponseMode(taskHandle: TaskHandle) -> int32; }
32.183338
100
0.677827
e2bb9aae1ee12a2d2988ea6fbd57f480b99b0924
2,985
use super::{Ast, BindingsHandle, Malvi, Result}; use std::rc::Rc; use crate::im::Vector; pub fn nimpl(_: &mut Malvi, _: &BindingsHandle, _: Vector<Rc<Ast>>) -> Result<Ast> { bail!("Not implemented") } #[macro_export] macro_rules! declare_macros_for_builtins { ($this:expr) => { let this = $this; #[allow(unused_macros)] macro_rules! builtin_notimpl_macro { ($n:expr) => {{ let s = this.sym($n); let b = this.builtins.insert(Rc::new($crate::stdfn_utils::nimpl)); this.root_bindings .borrow_mut() .at_this_level .insert(s, Ast::BuiltinMacro(b)); }}; } #[allow(unused_macros)] macro_rules! builtin_func { ($n:expr, $f:expr) => {{ let s = this.sym($n); let b = this.builtins.insert(Rc::new($f)); this.root_bindings .borrow_mut() .at_this_level .insert(s, Ast::BuiltinFunction(b)); }}; } #[allow(unused_macros)] macro_rules! builtin_func0 { ($n:expr, $f:expr) => {{ builtin_func!($n, |m,env,x|{ if x.len() != 0 { bail!("This function has exactly 0 arguments"); } $f(m,env) }); }}; } #[allow(unused_macros)] macro_rules! builtin_func1 { ($n:expr, $f:expr) => {{ builtin_func!($n, |m,env,mut x|{ if x.len() != 1 { bail!("This function has exactly 1 argument"); } let arg = x.pop_front().unwrap(); $f(m,env,arg) }); }}; } #[allow(unused_macros)] macro_rules! builtin_func2 { ($n:expr, $f:expr) => {{ builtin_func!($n, |m,env,mut x|{ if x.len() != 2 { bail!("This function has exactly 2 arguments"); } let arg1 : Rc<Ast> = x.pop_front().unwrap(); let arg2 : Rc<Ast> = x.pop_front().unwrap(); $f(m,env,arg1,arg2) }); }}; } #[allow(unused_macros)] macro_rules! builtin_macro { ($n:expr, $f:expr) => {{ let s = this.sym($n); let b = this.builtins.insert(Rc::new($f)); this.root_bindings .borrow_mut() .at_this_level .insert(s, Ast::BuiltinMacro(b)); }}; } } } impl super::Bindings { pub fn depth(&self) -> usize { if let Some(x) = self.parent.as_ref() { 1 + x.borrow().depth() } else { 0 } } }
30.459184
84
0.40938
5bec800472a4ce2a300a3a7e177adf21426efd21
568
#![doc(hidden)] mod callsite; pub use self::callsite::CallSite; pub(crate) use self::callsite::Source; pub mod bytes { //! Types provided by the `bytes` crate pub use bytes::*; } pub mod tower { //! Types provided by the `tower` crate pub use tower_service::Service; } pub mod http { //! Types provided by the `http` crate. pub use http::*; } pub mod futures { //! Types provided by the `futures` crate. pub use futures::*; } pub mod serde { pub use serde::*; } #[cfg(feature = "async-await-preview")] pub mod async_await;
16.228571
46
0.632042
de1d6e69fcb25398e33422458ea252c691699ca9
498
// xfail-fast - check-fast doesn't understand aux-build // aux-build:cci_nested_lib.rs use cci_nested_lib; import cci_nested_lib::*; fn main() { let lst = new_int_alist(); alist_add(lst, 22, ~"hi"); alist_add(lst, 44, ~"ho"); assert alist_get(lst, 22) == ~"hi"; assert alist_get(lst, 44) == ~"ho"; let lst = new_int_alist_2(); alist_add(lst, 22, ~"hi"); alist_add(lst, 44, ~"ho"); assert alist_get(lst, 22) == ~"hi"; assert alist_get(lst, 44) == ~"ho"; }
24.9
55
0.604418
d931ae2ded0dfaaa01ddccd6b6fefeaf836d0eb3
239
// Copyright (c) The Dijets Core Contributors // SPDX-License-Identifier: Apache-2.0 mod bcs_test; mod compat_test; mod cross_test; mod cryptohasher; mod ed25519_test; mod hash_test; mod hkdf_test; mod multi_ed25519_test; mod noise_test;
18.384615
45
0.794979
5d08ed0453c7895cd68b9ec4a2c9ebd9536b39f8
1,539
//! //! The Zinc compiler arguments. //! use std::path::PathBuf; use structopt::StructOpt; /// /// The Zinc compiler arguments. /// #[derive(Debug, StructOpt)] #[structopt(name = zinc_const::app_name::COMPILER, about = "The Zinc compiler")] pub struct Arguments { /// Prints more logs, if passed several times. #[structopt(short = "v", long = "verbose", parse(from_occurrences))] pub verbosity: usize, /// The path to the Zinc project manifest file. #[structopt( long = "manifest-path", parse(from_os_str), default_value = "./Zargo.toml" )] pub manifest_path: PathBuf, /// The path to the source code directory. #[structopt(parse(from_os_str), default_value = "./src/")] pub source_directory_path: PathBuf, /// The path to the keys, template, and other auxiliary data directory. #[structopt(long = "data", parse(from_os_str), default_value = "./data/")] pub data_directory_path: PathBuf, /// The path to the bytecode file. #[structopt( long = "binary", parse(from_os_str), default_value = "./build/main.znb" )] pub binary_path: PathBuf, /// Builds only the unit tests. #[structopt(long = "test-only")] pub test_only: bool, /// Enables the dead function code elimination optimization. #[structopt(long = "opt-dfe")] pub optimize_dead_function_elimination: bool, } impl Arguments { /// /// A shortcut constructor. /// pub fn new() -> Self { Self::from_args() } }
25.65
80
0.62963
1e9f861ed833217a5804601a4b8c821a2721d534
140,213
//! Get info on your team's private channels. #[allow(unused_imports)] use std::collections::HashMap; use std::convert::From; use std::error::Error; use std::fmt; use serde_json; use crate::requests::SlackWebRequestSender; /// Archives a private channel. /// /// Wraps https://api.slack.com/methods/groups.archive pub fn archive<R>( client: &R, token: &str, request: &ArchiveRequest<'_>, ) -> Result<ArchiveResponse, ArchiveError<R::Error>> where R: SlackWebRequestSender, { let params = vec![Some(("token", token)), Some(("channel", request.channel))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.archive"); client .send(&url, &params[..]) .map_err(ArchiveError::Client) .and_then(|result| { serde_json::from_str::<ArchiveResponse>(&result) .map_err(ArchiveError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct ArchiveRequest<'a> { /// Private channel to archive pub channel: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct ArchiveResponse { error: Option<String>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<ArchiveResponse, ArchiveError<E>>> for ArchiveResponse { fn into(self) -> Result<ArchiveResponse, ArchiveError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum ArchiveError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Group has already been archived. AlreadyArchived, /// Multi-channel guests cannot archive groups containing others. GroupContainsOthers, /// A team preference prevents the authenticated user from archiving. RestrictedAction, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// This method cannot be called by a single channel guest. UserIsUltraRestricted, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for ArchiveError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => ArchiveError::ChannelNotFound, "already_archived" => ArchiveError::AlreadyArchived, "group_contains_others" => ArchiveError::GroupContainsOthers, "restricted_action" => ArchiveError::RestrictedAction, "not_authed" => ArchiveError::NotAuthed, "invalid_auth" => ArchiveError::InvalidAuth, "account_inactive" => ArchiveError::AccountInactive, "user_is_bot" => ArchiveError::UserIsBot, "user_is_ultra_restricted" => ArchiveError::UserIsUltraRestricted, "invalid_arg_name" => ArchiveError::InvalidArgName, "invalid_array_arg" => ArchiveError::InvalidArrayArg, "invalid_charset" => ArchiveError::InvalidCharset, "invalid_form_data" => ArchiveError::InvalidFormData, "invalid_post_type" => ArchiveError::InvalidPostType, "missing_post_type" => ArchiveError::MissingPostType, "team_added_to_org" => ArchiveError::TeamAddedToOrg, "request_timeout" => ArchiveError::RequestTimeout, _ => ArchiveError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for ArchiveError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for ArchiveError<E> { fn description(&self) -> &str { match *self { ArchiveError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", ArchiveError::AlreadyArchived => "already_archived: Group has already been archived.", ArchiveError::GroupContainsOthers => "group_contains_others: Multi-channel guests cannot archive groups containing others.", ArchiveError::RestrictedAction => "restricted_action: A team preference prevents the authenticated user from archiving.", ArchiveError::NotAuthed => "not_authed: No authentication token provided.", ArchiveError::InvalidAuth => "invalid_auth: Invalid authentication token.", ArchiveError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", ArchiveError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", ArchiveError::UserIsUltraRestricted => "user_is_ultra_restricted: This method cannot be called by a single channel guest.", ArchiveError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", ArchiveError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", ArchiveError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", ArchiveError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", ArchiveError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", ArchiveError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", ArchiveError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", ArchiveError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", ArchiveError::MalformedResponse(ref e) => e.description(), ArchiveError::Unknown(ref s) => s, ArchiveError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { ArchiveError::MalformedResponse(ref e) => Some(e), ArchiveError::Client(ref inner) => Some(inner), _ => None, } } } /// Closes a private channel. /// /// Wraps https://api.slack.com/methods/groups.close pub fn close<R>( client: &R, token: &str, request: &CloseRequest<'_>, ) -> Result<CloseResponse, CloseError<R::Error>> where R: SlackWebRequestSender, { let params = vec![Some(("token", token)), Some(("channel", request.channel))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.close"); client .send(&url, &params[..]) .map_err(CloseError::Client) .and_then(|result| { serde_json::from_str::<CloseResponse>(&result).map_err(CloseError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct CloseRequest<'a> { /// Private channel to close. pub channel: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct CloseResponse { error: Option<String>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<CloseResponse, CloseError<E>>> for CloseResponse { fn into(self) -> Result<CloseResponse, CloseError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum CloseError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for CloseError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => CloseError::ChannelNotFound, "not_authed" => CloseError::NotAuthed, "invalid_auth" => CloseError::InvalidAuth, "account_inactive" => CloseError::AccountInactive, "invalid_arg_name" => CloseError::InvalidArgName, "invalid_array_arg" => CloseError::InvalidArrayArg, "invalid_charset" => CloseError::InvalidCharset, "invalid_form_data" => CloseError::InvalidFormData, "invalid_post_type" => CloseError::InvalidPostType, "missing_post_type" => CloseError::MissingPostType, "team_added_to_org" => CloseError::TeamAddedToOrg, "request_timeout" => CloseError::RequestTimeout, _ => CloseError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for CloseError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for CloseError<E> { fn description(&self) -> &str { match *self { CloseError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", CloseError::NotAuthed => "not_authed: No authentication token provided.", CloseError::InvalidAuth => "invalid_auth: Invalid authentication token.", CloseError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", CloseError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", CloseError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", CloseError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", CloseError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", CloseError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", CloseError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", CloseError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", CloseError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", CloseError::MalformedResponse(ref e) => e.description(), CloseError::Unknown(ref s) => s, CloseError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { CloseError::MalformedResponse(ref e) => Some(e), CloseError::Client(ref inner) => Some(inner), _ => None, } } } /// Creates a private channel. /// /// Wraps https://api.slack.com/methods/groups.create pub fn create<R>( client: &R, token: &str, request: &CreateRequest<'_>, ) -> Result<CreateResponse, CreateError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), Some(("name", request.name)), request .validate .map(|validate| ("validate", if validate { "1" } else { "0" })), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.create"); client .send(&url, &params[..]) .map_err(CreateError::Client) .and_then(|result| { serde_json::from_str::<CreateResponse>(&result).map_err(CreateError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct CreateRequest<'a> { /// Name of private channel to create pub name: &'a str, /// Whether to return errors on invalid channel name instead of modifying it to meet the specified criteria. pub validate: Option<bool>, } #[derive(Clone, Debug, Deserialize)] pub struct CreateResponse { error: Option<String>, pub group: Option<crate::Group>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<CreateResponse, CreateError<E>>> for CreateResponse { fn into(self) -> Result<CreateResponse, CreateError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum CreateError<E: Error> { /// No group name was passed. NoChannel, /// A team preference prevents the authenticated user from creating groups. RestrictedAction, /// A group cannot be created with the given name. NameTaken, /// Value passed for name was empty. InvalidNameRequired, /// Value passed for name contained only punctuation. InvalidNamePunctuation, /// Value passed for name exceeded max length. InvalidNameMaxlength, /// Value passed for name contained unallowed special characters or upper case characters. InvalidNameSpecials, /// Value passed for name was invalid. InvalidName, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// This method cannot be called by a single channel guest. UserIsUltraRestricted, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for CreateError<E> { fn from(s: &'a str) -> Self { match s { "no_channel" => CreateError::NoChannel, "restricted_action" => CreateError::RestrictedAction, "name_taken" => CreateError::NameTaken, "invalid_name_required" => CreateError::InvalidNameRequired, "invalid_name_punctuation" => CreateError::InvalidNamePunctuation, "invalid_name_maxlength" => CreateError::InvalidNameMaxlength, "invalid_name_specials" => CreateError::InvalidNameSpecials, "invalid_name" => CreateError::InvalidName, "not_authed" => CreateError::NotAuthed, "invalid_auth" => CreateError::InvalidAuth, "account_inactive" => CreateError::AccountInactive, "user_is_bot" => CreateError::UserIsBot, "user_is_ultra_restricted" => CreateError::UserIsUltraRestricted, "invalid_arg_name" => CreateError::InvalidArgName, "invalid_array_arg" => CreateError::InvalidArrayArg, "invalid_charset" => CreateError::InvalidCharset, "invalid_form_data" => CreateError::InvalidFormData, "invalid_post_type" => CreateError::InvalidPostType, "missing_post_type" => CreateError::MissingPostType, "team_added_to_org" => CreateError::TeamAddedToOrg, "request_timeout" => CreateError::RequestTimeout, _ => CreateError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for CreateError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for CreateError<E> { fn description(&self) -> &str { match *self { CreateError::NoChannel => "no_channel: No group name was passed.", CreateError::RestrictedAction => "restricted_action: A team preference prevents the authenticated user from creating groups.", CreateError::NameTaken => "name_taken: A group cannot be created with the given name.", CreateError::InvalidNameRequired => "invalid_name_required: Value passed for name was empty.", CreateError::InvalidNamePunctuation => "invalid_name_punctuation: Value passed for name contained only punctuation.", CreateError::InvalidNameMaxlength => "invalid_name_maxlength: Value passed for name exceeded max length.", CreateError::InvalidNameSpecials => "invalid_name_specials: Value passed for name contained unallowed special characters or upper case characters.", CreateError::InvalidName => "invalid_name: Value passed for name was invalid.", CreateError::NotAuthed => "not_authed: No authentication token provided.", CreateError::InvalidAuth => "invalid_auth: Invalid authentication token.", CreateError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", CreateError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", CreateError::UserIsUltraRestricted => "user_is_ultra_restricted: This method cannot be called by a single channel guest.", CreateError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", CreateError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", CreateError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", CreateError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", CreateError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", CreateError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", CreateError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", CreateError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", CreateError::MalformedResponse(ref e) => e.description(), CreateError::Unknown(ref s) => s, CreateError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { CreateError::MalformedResponse(ref e) => Some(e), CreateError::Client(ref inner) => Some(inner), _ => None, } } } /// Clones and archives a private channel. /// /// Wraps https://api.slack.com/methods/groups.createChild pub fn create_child<R>( client: &R, token: &str, request: &CreateChildRequest<'_>, ) -> Result<CreateChildResponse, CreateChildError<R::Error>> where R: SlackWebRequestSender, { let params = vec![Some(("token", token)), Some(("channel", request.channel))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.createChild"); client .send(&url, &params[..]) .map_err(CreateChildError::Client) .and_then(|result| { serde_json::from_str::<CreateChildResponse>(&result) .map_err(CreateChildError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct CreateChildRequest<'a> { /// Private channel to clone and archive. pub channel: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct CreateChildResponse { error: Option<String>, pub group: Option<crate::Group>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<CreateChildResponse, CreateChildError<E>>> for CreateChildResponse { fn into(self) -> Result<CreateChildResponse, CreateChildError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum CreateChildError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// An archived group cannot be cloned AlreadyArchived, /// A team preference prevents the authenticated user from creating groups. RestrictedAction, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// This method cannot be called by a single channel guest. UserIsUltraRestricted, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for CreateChildError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => CreateChildError::ChannelNotFound, "already_archived" => CreateChildError::AlreadyArchived, "restricted_action" => CreateChildError::RestrictedAction, "not_authed" => CreateChildError::NotAuthed, "invalid_auth" => CreateChildError::InvalidAuth, "account_inactive" => CreateChildError::AccountInactive, "user_is_bot" => CreateChildError::UserIsBot, "user_is_ultra_restricted" => CreateChildError::UserIsUltraRestricted, "invalid_arg_name" => CreateChildError::InvalidArgName, "invalid_array_arg" => CreateChildError::InvalidArrayArg, "invalid_charset" => CreateChildError::InvalidCharset, "invalid_form_data" => CreateChildError::InvalidFormData, "invalid_post_type" => CreateChildError::InvalidPostType, "missing_post_type" => CreateChildError::MissingPostType, "team_added_to_org" => CreateChildError::TeamAddedToOrg, "request_timeout" => CreateChildError::RequestTimeout, _ => CreateChildError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for CreateChildError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for CreateChildError<E> { fn description(&self) -> &str { match *self { CreateChildError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", CreateChildError::AlreadyArchived => "already_archived: An archived group cannot be cloned", CreateChildError::RestrictedAction => "restricted_action: A team preference prevents the authenticated user from creating groups.", CreateChildError::NotAuthed => "not_authed: No authentication token provided.", CreateChildError::InvalidAuth => "invalid_auth: Invalid authentication token.", CreateChildError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", CreateChildError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", CreateChildError::UserIsUltraRestricted => "user_is_ultra_restricted: This method cannot be called by a single channel guest.", CreateChildError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", CreateChildError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", CreateChildError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", CreateChildError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", CreateChildError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", CreateChildError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", CreateChildError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", CreateChildError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", CreateChildError::MalformedResponse(ref e) => e.description(), CreateChildError::Unknown(ref s) => s, CreateChildError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { CreateChildError::MalformedResponse(ref e) => Some(e), CreateChildError::Client(ref inner) => Some(inner), _ => None, } } } /// Fetches history of messages and events from a private channel. /// /// Wraps https://api.slack.com/methods/groups.history pub fn history<R>( client: &R, token: &str, request: &HistoryRequest<'_>, ) -> Result<HistoryResponse, HistoryError<R::Error>> where R: SlackWebRequestSender, { let count = request.count.map(|count| count.to_string()); let params = vec![ Some(("token", token)), Some(("channel", request.channel)), request.latest.map(|latest| ("latest", latest)), request.oldest.map(|oldest| ("oldest", oldest)), request .inclusive .map(|inclusive| ("inclusive", if inclusive { "1" } else { "0" })), count.as_ref().map(|count| ("count", &count[..])), request .unreads .map(|unreads| ("unreads", if unreads { "1" } else { "0" })), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.history"); client .send(&url, &params[..]) .map_err(HistoryError::Client) .and_then(|result| { serde_json::from_str::<HistoryResponse>(&result) .map_err(HistoryError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct HistoryRequest<'a> { /// Private channel to fetch history for. pub channel: &'a str, /// End of time range of messages to include in results. pub latest: Option<&'a str>, /// Start of time range of messages to include in results. pub oldest: Option<&'a str>, /// Include messages with latest or oldest timestamp in results. pub inclusive: Option<bool>, /// Number of messages to return, between 1 and 1000. pub count: Option<u32>, /// Include unread_count_display in the output? pub unreads: Option<bool>, } #[derive(Clone, Debug, Deserialize)] pub struct HistoryResponse { error: Option<String>, pub has_more: Option<bool>, pub latest: Option<String>, pub messages: Option<Vec<crate::Message>>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<HistoryResponse, HistoryError<E>>> for HistoryResponse { fn into(self) -> Result<HistoryResponse, HistoryError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum HistoryError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Value passed for latest was invalid InvalidTsLatest, /// Value passed for oldest was invalid InvalidTsOldest, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for HistoryError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => HistoryError::ChannelNotFound, "invalid_ts_latest" => HistoryError::InvalidTsLatest, "invalid_ts_oldest" => HistoryError::InvalidTsOldest, "not_authed" => HistoryError::NotAuthed, "invalid_auth" => HistoryError::InvalidAuth, "account_inactive" => HistoryError::AccountInactive, "invalid_arg_name" => HistoryError::InvalidArgName, "invalid_array_arg" => HistoryError::InvalidArrayArg, "invalid_charset" => HistoryError::InvalidCharset, "invalid_form_data" => HistoryError::InvalidFormData, "invalid_post_type" => HistoryError::InvalidPostType, "missing_post_type" => HistoryError::MissingPostType, "team_added_to_org" => HistoryError::TeamAddedToOrg, "request_timeout" => HistoryError::RequestTimeout, _ => HistoryError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for HistoryError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for HistoryError<E> { fn description(&self) -> &str { match *self { HistoryError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", HistoryError::InvalidTsLatest => "invalid_ts_latest: Value passed for latest was invalid", HistoryError::InvalidTsOldest => "invalid_ts_oldest: Value passed for oldest was invalid", HistoryError::NotAuthed => "not_authed: No authentication token provided.", HistoryError::InvalidAuth => "invalid_auth: Invalid authentication token.", HistoryError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", HistoryError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", HistoryError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", HistoryError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", HistoryError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", HistoryError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", HistoryError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", HistoryError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", HistoryError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", HistoryError::MalformedResponse(ref e) => e.description(), HistoryError::Unknown(ref s) => s, HistoryError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { HistoryError::MalformedResponse(ref e) => Some(e), HistoryError::Client(ref inner) => Some(inner), _ => None, } } } /// Gets information about a private channel. /// /// Wraps https://api.slack.com/methods/groups.info pub fn info<R>( client: &R, token: &str, request: &InfoRequest<'_>, ) -> Result<InfoResponse, InfoError<R::Error>> where R: SlackWebRequestSender, { let params = vec![Some(("token", token)), Some(("channel", request.channel))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.info"); client .send(&url, &params[..]) .map_err(InfoError::Client) .and_then(|result| { serde_json::from_str::<InfoResponse>(&result).map_err(InfoError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct InfoRequest<'a> { /// Private channel to get info on pub channel: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct InfoResponse { error: Option<String>, pub group: Option<crate::Group>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<InfoResponse, InfoError<E>>> for InfoResponse { fn into(self) -> Result<InfoResponse, InfoError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum InfoError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for InfoError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => InfoError::ChannelNotFound, "not_authed" => InfoError::NotAuthed, "invalid_auth" => InfoError::InvalidAuth, "account_inactive" => InfoError::AccountInactive, "invalid_arg_name" => InfoError::InvalidArgName, "invalid_array_arg" => InfoError::InvalidArrayArg, "invalid_charset" => InfoError::InvalidCharset, "invalid_form_data" => InfoError::InvalidFormData, "invalid_post_type" => InfoError::InvalidPostType, "missing_post_type" => InfoError::MissingPostType, "team_added_to_org" => InfoError::TeamAddedToOrg, "request_timeout" => InfoError::RequestTimeout, _ => InfoError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for InfoError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for InfoError<E> { fn description(&self) -> &str { match *self { InfoError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", InfoError::NotAuthed => "not_authed: No authentication token provided.", InfoError::InvalidAuth => "invalid_auth: Invalid authentication token.", InfoError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", InfoError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", InfoError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", InfoError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", InfoError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", InfoError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", InfoError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", InfoError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", InfoError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", InfoError::MalformedResponse(ref e) => e.description(), InfoError::Unknown(ref s) => s, InfoError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { InfoError::MalformedResponse(ref e) => Some(e), InfoError::Client(ref inner) => Some(inner), _ => None, } } } /// Invites a user to a private channel. /// /// Wraps https://api.slack.com/methods/groups.invite pub fn invite<R>( client: &R, token: &str, request: &InviteRequest<'_>, ) -> Result<InviteResponse, InviteError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), Some(("channel", request.channel)), Some(("user", request.user)), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.invite"); client .send(&url, &params[..]) .map_err(InviteError::Client) .and_then(|result| { serde_json::from_str::<InviteResponse>(&result).map_err(InviteError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct InviteRequest<'a> { /// Private channel to invite user to. pub channel: &'a str, /// User to invite. pub user: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct InviteResponse { error: Option<String>, pub group: Option<crate::Group>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<InviteResponse, InviteError<E>>> for InviteResponse { fn into(self) -> Result<InviteResponse, InviteError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum InviteError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Value passed for user was invalid. UserNotFound, /// Authenticated user cannot invite themselves to a group. CantInviteSelf, /// Group has been archived. IsArchived, /// User cannot be invited to this group. CantInvite, /// URA is already in the maximum number of channels. UraMaxChannels, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// This method cannot be called by a single channel guest. UserIsUltraRestricted, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for InviteError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => InviteError::ChannelNotFound, "user_not_found" => InviteError::UserNotFound, "cant_invite_self" => InviteError::CantInviteSelf, "is_archived" => InviteError::IsArchived, "cant_invite" => InviteError::CantInvite, "ura_max_channels" => InviteError::UraMaxChannels, "not_authed" => InviteError::NotAuthed, "invalid_auth" => InviteError::InvalidAuth, "account_inactive" => InviteError::AccountInactive, "user_is_bot" => InviteError::UserIsBot, "user_is_ultra_restricted" => InviteError::UserIsUltraRestricted, "invalid_arg_name" => InviteError::InvalidArgName, "invalid_array_arg" => InviteError::InvalidArrayArg, "invalid_charset" => InviteError::InvalidCharset, "invalid_form_data" => InviteError::InvalidFormData, "invalid_post_type" => InviteError::InvalidPostType, "missing_post_type" => InviteError::MissingPostType, "team_added_to_org" => InviteError::TeamAddedToOrg, "request_timeout" => InviteError::RequestTimeout, _ => InviteError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for InviteError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for InviteError<E> { fn description(&self) -> &str { match *self { InviteError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", InviteError::UserNotFound => "user_not_found: Value passed for user was invalid.", InviteError::CantInviteSelf => "cant_invite_self: Authenticated user cannot invite themselves to a group.", InviteError::IsArchived => "is_archived: Group has been archived.", InviteError::CantInvite => "cant_invite: User cannot be invited to this group.", InviteError::UraMaxChannels => "ura_max_channels: URA is already in the maximum number of channels.", InviteError::NotAuthed => "not_authed: No authentication token provided.", InviteError::InvalidAuth => "invalid_auth: Invalid authentication token.", InviteError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", InviteError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", InviteError::UserIsUltraRestricted => "user_is_ultra_restricted: This method cannot be called by a single channel guest.", InviteError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", InviteError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", InviteError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", InviteError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", InviteError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", InviteError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", InviteError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", InviteError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", InviteError::MalformedResponse(ref e) => e.description(), InviteError::Unknown(ref s) => s, InviteError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { InviteError::MalformedResponse(ref e) => Some(e), InviteError::Client(ref inner) => Some(inner), _ => None, } } } /// Removes a user from a private channel. /// /// Wraps https://api.slack.com/methods/groups.kick pub fn kick<R>( client: &R, token: &str, request: &KickRequest<'_>, ) -> Result<KickResponse, KickError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), Some(("channel", request.channel)), Some(("user", request.user)), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.kick"); client .send(&url, &params[..]) .map_err(KickError::Client) .and_then(|result| { serde_json::from_str::<KickResponse>(&result).map_err(KickError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct KickRequest<'a> { /// Private channel to remove user from. pub channel: &'a str, /// User to remove from private channel. pub user: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct KickResponse { error: Option<String>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<KickResponse, KickError<E>>> for KickResponse { fn into(self) -> Result<KickResponse, KickError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum KickError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Value passed for user was invalid. UserNotFound, /// You can't remove yourself from a group CantKickSelf, /// User or caller were are not in the group NotInGroup, /// A team preference prevents the authenticated user from kicking. RestrictedAction, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// This method cannot be called by a restricted user or single channel guest. UserIsRestricted, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for KickError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => KickError::ChannelNotFound, "user_not_found" => KickError::UserNotFound, "cant_kick_self" => KickError::CantKickSelf, "not_in_group" => KickError::NotInGroup, "restricted_action" => KickError::RestrictedAction, "not_authed" => KickError::NotAuthed, "invalid_auth" => KickError::InvalidAuth, "account_inactive" => KickError::AccountInactive, "user_is_bot" => KickError::UserIsBot, "user_is_restricted" => KickError::UserIsRestricted, "invalid_arg_name" => KickError::InvalidArgName, "invalid_array_arg" => KickError::InvalidArrayArg, "invalid_charset" => KickError::InvalidCharset, "invalid_form_data" => KickError::InvalidFormData, "invalid_post_type" => KickError::InvalidPostType, "missing_post_type" => KickError::MissingPostType, "team_added_to_org" => KickError::TeamAddedToOrg, "request_timeout" => KickError::RequestTimeout, _ => KickError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for KickError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for KickError<E> { fn description(&self) -> &str { match *self { KickError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", KickError::UserNotFound => "user_not_found: Value passed for user was invalid.", KickError::CantKickSelf => "cant_kick_self: You can't remove yourself from a group", KickError::NotInGroup => "not_in_group: User or caller were are not in the group", KickError::RestrictedAction => "restricted_action: A team preference prevents the authenticated user from kicking.", KickError::NotAuthed => "not_authed: No authentication token provided.", KickError::InvalidAuth => "invalid_auth: Invalid authentication token.", KickError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", KickError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", KickError::UserIsRestricted => "user_is_restricted: This method cannot be called by a restricted user or single channel guest.", KickError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", KickError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", KickError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", KickError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", KickError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", KickError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", KickError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", KickError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", KickError::MalformedResponse(ref e) => e.description(), KickError::Unknown(ref s) => s, KickError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { KickError::MalformedResponse(ref e) => Some(e), KickError::Client(ref inner) => Some(inner), _ => None, } } } /// Leaves a private channel. /// /// Wraps https://api.slack.com/methods/groups.leave pub fn leave<R>( client: &R, token: &str, request: &LeaveRequest<'_>, ) -> Result<LeaveResponse, LeaveError<R::Error>> where R: SlackWebRequestSender, { let params = vec![Some(("token", token)), Some(("channel", request.channel))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.leave"); client .send(&url, &params[..]) .map_err(LeaveError::Client) .and_then(|result| { serde_json::from_str::<LeaveResponse>(&result).map_err(LeaveError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct LeaveRequest<'a> { /// Private channel to leave pub channel: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct LeaveResponse { error: Option<String>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<LeaveResponse, LeaveError<E>>> for LeaveResponse { fn into(self) -> Result<LeaveResponse, LeaveError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum LeaveError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Group has been archived. IsArchived, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// This method cannot be called by a single channel guest. UserIsUltraRestricted, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for LeaveError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => LeaveError::ChannelNotFound, "is_archived" => LeaveError::IsArchived, "not_authed" => LeaveError::NotAuthed, "invalid_auth" => LeaveError::InvalidAuth, "account_inactive" => LeaveError::AccountInactive, "user_is_bot" => LeaveError::UserIsBot, "user_is_ultra_restricted" => LeaveError::UserIsUltraRestricted, "invalid_arg_name" => LeaveError::InvalidArgName, "invalid_array_arg" => LeaveError::InvalidArrayArg, "invalid_charset" => LeaveError::InvalidCharset, "invalid_form_data" => LeaveError::InvalidFormData, "invalid_post_type" => LeaveError::InvalidPostType, "missing_post_type" => LeaveError::MissingPostType, "team_added_to_org" => LeaveError::TeamAddedToOrg, "request_timeout" => LeaveError::RequestTimeout, _ => LeaveError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for LeaveError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for LeaveError<E> { fn description(&self) -> &str { match *self { LeaveError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", LeaveError::IsArchived => "is_archived: Group has been archived.", LeaveError::NotAuthed => "not_authed: No authentication token provided.", LeaveError::InvalidAuth => "invalid_auth: Invalid authentication token.", LeaveError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", LeaveError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", LeaveError::UserIsUltraRestricted => "user_is_ultra_restricted: This method cannot be called by a single channel guest.", LeaveError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", LeaveError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", LeaveError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", LeaveError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", LeaveError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", LeaveError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", LeaveError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", LeaveError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", LeaveError::MalformedResponse(ref e) => e.description(), LeaveError::Unknown(ref s) => s, LeaveError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { LeaveError::MalformedResponse(ref e) => Some(e), LeaveError::Client(ref inner) => Some(inner), _ => None, } } } /// Lists private channels that the calling user has access to. /// /// Wraps https://api.slack.com/methods/groups.list pub fn list<R>( client: &R, token: &str, request: &ListRequest, ) -> Result<ListResponse, ListError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), request .exclude_archived .map(|exclude_archived| ("exclude_archived", if exclude_archived { "1" } else { "0" })), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.list"); client .send(&url, &params[..]) .map_err(ListError::Client) .and_then(|result| { serde_json::from_str::<ListResponse>(&result).map_err(ListError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct ListRequest { /// Don't return archived private channels. pub exclude_archived: Option<bool>, } #[derive(Clone, Debug, Deserialize)] pub struct ListResponse { error: Option<String>, pub groups: Option<Vec<crate::Group>>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<ListResponse, ListError<E>>> for ListResponse { fn into(self) -> Result<ListResponse, ListError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum ListError<E: Error> { /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for ListError<E> { fn from(s: &'a str) -> Self { match s { "not_authed" => ListError::NotAuthed, "invalid_auth" => ListError::InvalidAuth, "account_inactive" => ListError::AccountInactive, "invalid_arg_name" => ListError::InvalidArgName, "invalid_array_arg" => ListError::InvalidArrayArg, "invalid_charset" => ListError::InvalidCharset, "invalid_form_data" => ListError::InvalidFormData, "invalid_post_type" => ListError::InvalidPostType, "missing_post_type" => ListError::MissingPostType, "team_added_to_org" => ListError::TeamAddedToOrg, "request_timeout" => ListError::RequestTimeout, _ => ListError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for ListError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for ListError<E> { fn description(&self) -> &str { match *self { ListError::NotAuthed => "not_authed: No authentication token provided.", ListError::InvalidAuth => "invalid_auth: Invalid authentication token.", ListError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", ListError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", ListError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", ListError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", ListError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", ListError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", ListError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", ListError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", ListError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", ListError::MalformedResponse(ref e) => e.description(), ListError::Unknown(ref s) => s, ListError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { ListError::MalformedResponse(ref e) => Some(e), ListError::Client(ref inner) => Some(inner), _ => None, } } } /// Sets the read cursor in a private channel. /// /// Wraps https://api.slack.com/methods/groups.mark pub fn mark<R>( client: &R, token: &str, request: &MarkRequest<'_>, ) -> Result<MarkResponse, MarkError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), Some(("channel", request.channel)), Some(("ts", request.ts)), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.mark"); client .send(&url, &params[..]) .map_err(MarkError::Client) .and_then(|result| { serde_json::from_str::<MarkResponse>(&result).map_err(MarkError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct MarkRequest<'a> { /// Private channel to set reading cursor in. pub channel: &'a str, /// Timestamp of the most recently seen message. pub ts: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct MarkResponse { error: Option<String>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<MarkResponse, MarkError<E>>> for MarkResponse { fn into(self) -> Result<MarkResponse, MarkError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum MarkError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Value passed for timestamp was invalid. InvalidTimestamp, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for MarkError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => MarkError::ChannelNotFound, "invalid_timestamp" => MarkError::InvalidTimestamp, "not_authed" => MarkError::NotAuthed, "invalid_auth" => MarkError::InvalidAuth, "account_inactive" => MarkError::AccountInactive, "invalid_arg_name" => MarkError::InvalidArgName, "invalid_array_arg" => MarkError::InvalidArrayArg, "invalid_charset" => MarkError::InvalidCharset, "invalid_form_data" => MarkError::InvalidFormData, "invalid_post_type" => MarkError::InvalidPostType, "missing_post_type" => MarkError::MissingPostType, "team_added_to_org" => MarkError::TeamAddedToOrg, "request_timeout" => MarkError::RequestTimeout, _ => MarkError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for MarkError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for MarkError<E> { fn description(&self) -> &str { match *self { MarkError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", MarkError::InvalidTimestamp => "invalid_timestamp: Value passed for timestamp was invalid.", MarkError::NotAuthed => "not_authed: No authentication token provided.", MarkError::InvalidAuth => "invalid_auth: Invalid authentication token.", MarkError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", MarkError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", MarkError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", MarkError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", MarkError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", MarkError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", MarkError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", MarkError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", MarkError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", MarkError::MalformedResponse(ref e) => e.description(), MarkError::Unknown(ref s) => s, MarkError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { MarkError::MalformedResponse(ref e) => Some(e), MarkError::Client(ref inner) => Some(inner), _ => None, } } } /// Opens a private channel. /// /// Wraps https://api.slack.com/methods/groups.open pub fn open<R>( client: &R, token: &str, request: &OpenRequest<'_>, ) -> Result<OpenResponse, OpenError<R::Error>> where R: SlackWebRequestSender, { let params = vec![Some(("token", token)), Some(("channel", request.channel))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.open"); client .send(&url, &params[..]) .map_err(OpenError::Client) .and_then(|result| { serde_json::from_str::<OpenResponse>(&result).map_err(OpenError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct OpenRequest<'a> { /// Private channel to open. pub channel: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct OpenResponse { error: Option<String>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<OpenResponse, OpenError<E>>> for OpenResponse { fn into(self) -> Result<OpenResponse, OpenError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum OpenError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for OpenError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => OpenError::ChannelNotFound, "not_authed" => OpenError::NotAuthed, "invalid_auth" => OpenError::InvalidAuth, "account_inactive" => OpenError::AccountInactive, "invalid_arg_name" => OpenError::InvalidArgName, "invalid_array_arg" => OpenError::InvalidArrayArg, "invalid_charset" => OpenError::InvalidCharset, "invalid_form_data" => OpenError::InvalidFormData, "invalid_post_type" => OpenError::InvalidPostType, "missing_post_type" => OpenError::MissingPostType, "team_added_to_org" => OpenError::TeamAddedToOrg, "request_timeout" => OpenError::RequestTimeout, _ => OpenError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for OpenError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for OpenError<E> { fn description(&self) -> &str { match *self { OpenError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", OpenError::NotAuthed => "not_authed: No authentication token provided.", OpenError::InvalidAuth => "invalid_auth: Invalid authentication token.", OpenError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", OpenError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", OpenError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", OpenError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", OpenError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", OpenError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", OpenError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", OpenError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", OpenError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", OpenError::MalformedResponse(ref e) => e.description(), OpenError::Unknown(ref s) => s, OpenError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { OpenError::MalformedResponse(ref e) => Some(e), OpenError::Client(ref inner) => Some(inner), _ => None, } } } /// Renames a private channel. /// /// Wraps https://api.slack.com/methods/groups.rename pub fn rename<R>( client: &R, token: &str, request: &RenameRequest<'_>, ) -> Result<RenameResponse, RenameError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), Some(("channel", request.channel)), Some(("name", request.name)), request .validate .map(|validate| ("validate", if validate { "1" } else { "0" })), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.rename"); client .send(&url, &params[..]) .map_err(RenameError::Client) .and_then(|result| { serde_json::from_str::<RenameResponse>(&result).map_err(RenameError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct RenameRequest<'a> { /// Private channel to rename pub channel: &'a str, /// New name for private channel. pub name: &'a str, /// Whether to return errors on invalid channel name instead of modifying it to meet the specified criteria. pub validate: Option<bool>, } #[derive(Clone, Debug, Deserialize)] pub struct RenameResponse { pub channel: Option<RenameResponseChannel>, error: Option<String>, #[serde(default)] ok: bool, } #[derive(Clone, Debug, Deserialize)] pub struct RenameResponseChannel { pub created: Option<f32>, pub id: Option<String>, pub is_group: Option<bool>, pub name: Option<String>, } impl<E: Error> Into<Result<RenameResponse, RenameError<E>>> for RenameResponse { fn into(self) -> Result<RenameResponse, RenameError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum RenameError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Value passed for name was invalid. InvalidName, /// New channel name is taken NameTaken, /// Value passed for name was empty. InvalidNameRequired, /// Value passed for name contained only punctuation. InvalidNamePunctuation, /// Value passed for name exceeded max length. InvalidNameMaxlength, /// Value passed for name contained unallowed special characters or upper case characters. InvalidNameSpecials, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// This method cannot be called by a restricted user or single channel guest. UserIsRestricted, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for RenameError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => RenameError::ChannelNotFound, "invalid_name" => RenameError::InvalidName, "name_taken" => RenameError::NameTaken, "invalid_name_required" => RenameError::InvalidNameRequired, "invalid_name_punctuation" => RenameError::InvalidNamePunctuation, "invalid_name_maxlength" => RenameError::InvalidNameMaxlength, "invalid_name_specials" => RenameError::InvalidNameSpecials, "not_authed" => RenameError::NotAuthed, "invalid_auth" => RenameError::InvalidAuth, "account_inactive" => RenameError::AccountInactive, "user_is_bot" => RenameError::UserIsBot, "user_is_restricted" => RenameError::UserIsRestricted, "invalid_arg_name" => RenameError::InvalidArgName, "invalid_array_arg" => RenameError::InvalidArrayArg, "invalid_charset" => RenameError::InvalidCharset, "invalid_form_data" => RenameError::InvalidFormData, "invalid_post_type" => RenameError::InvalidPostType, "missing_post_type" => RenameError::MissingPostType, "team_added_to_org" => RenameError::TeamAddedToOrg, "request_timeout" => RenameError::RequestTimeout, _ => RenameError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for RenameError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for RenameError<E> { fn description(&self) -> &str { match *self { RenameError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", RenameError::InvalidName => "invalid_name: Value passed for name was invalid.", RenameError::NameTaken => "name_taken: New channel name is taken", RenameError::InvalidNameRequired => "invalid_name_required: Value passed for name was empty.", RenameError::InvalidNamePunctuation => "invalid_name_punctuation: Value passed for name contained only punctuation.", RenameError::InvalidNameMaxlength => "invalid_name_maxlength: Value passed for name exceeded max length.", RenameError::InvalidNameSpecials => "invalid_name_specials: Value passed for name contained unallowed special characters or upper case characters.", RenameError::NotAuthed => "not_authed: No authentication token provided.", RenameError::InvalidAuth => "invalid_auth: Invalid authentication token.", RenameError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", RenameError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", RenameError::UserIsRestricted => "user_is_restricted: This method cannot be called by a restricted user or single channel guest.", RenameError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", RenameError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", RenameError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", RenameError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", RenameError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", RenameError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", RenameError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", RenameError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", RenameError::MalformedResponse(ref e) => e.description(), RenameError::Unknown(ref s) => s, RenameError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { RenameError::MalformedResponse(ref e) => Some(e), RenameError::Client(ref inner) => Some(inner), _ => None, } } } /// Retrieve a thread of messages posted to a private channel /// /// Wraps https://api.slack.com/methods/groups.replies pub fn replies<R>( client: &R, token: &str, request: &RepliesRequest<'_>, ) -> Result<RepliesResponse, RepliesError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), Some(("channel", request.channel)), Some(("thread_ts", request.thread_ts)), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.replies"); client .send(&url, &params[..]) .map_err(RepliesError::Client) .and_then(|result| { serde_json::from_str::<RepliesResponse>(&result) .map_err(RepliesError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct RepliesRequest<'a> { /// Private channel to fetch thread from pub channel: &'a str, /// Unique identifier of a thread's parent message pub thread_ts: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct RepliesResponse { error: Option<String>, pub messages: Option<Vec<crate::Message>>, #[serde(default)] ok: bool, pub thread_info: Option<crate::ThreadInfo>, } impl<E: Error> Into<Result<RepliesResponse, RepliesError<E>>> for RepliesResponse { fn into(self) -> Result<RepliesResponse, RepliesError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum RepliesError<E: Error> { /// Value for channel was missing or invalid. ChannelNotFound, /// Value for thread_ts was missing or invalid. ThreadNotFound, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for RepliesError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => RepliesError::ChannelNotFound, "thread_not_found" => RepliesError::ThreadNotFound, "not_authed" => RepliesError::NotAuthed, "invalid_auth" => RepliesError::InvalidAuth, "account_inactive" => RepliesError::AccountInactive, "user_is_bot" => RepliesError::UserIsBot, "invalid_arg_name" => RepliesError::InvalidArgName, "invalid_array_arg" => RepliesError::InvalidArrayArg, "invalid_charset" => RepliesError::InvalidCharset, "invalid_form_data" => RepliesError::InvalidFormData, "invalid_post_type" => RepliesError::InvalidPostType, "missing_post_type" => RepliesError::MissingPostType, "team_added_to_org" => RepliesError::TeamAddedToOrg, "request_timeout" => RepliesError::RequestTimeout, _ => RepliesError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for RepliesError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for RepliesError<E> { fn description(&self) -> &str { match *self { RepliesError::ChannelNotFound => "channel_not_found: Value for channel was missing or invalid.", RepliesError::ThreadNotFound => "thread_not_found: Value for thread_ts was missing or invalid.", RepliesError::NotAuthed => "not_authed: No authentication token provided.", RepliesError::InvalidAuth => "invalid_auth: Invalid authentication token.", RepliesError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", RepliesError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", RepliesError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", RepliesError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", RepliesError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", RepliesError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", RepliesError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", RepliesError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", RepliesError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", RepliesError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", RepliesError::MalformedResponse(ref e) => e.description(), RepliesError::Unknown(ref s) => s, RepliesError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { RepliesError::MalformedResponse(ref e) => Some(e), RepliesError::Client(ref inner) => Some(inner), _ => None, } } } /// Sets the purpose for a private channel. /// /// Wraps https://api.slack.com/methods/groups.setPurpose pub fn set_purpose<R>( client: &R, token: &str, request: &SetPurposeRequest<'_>, ) -> Result<SetPurposeResponse, SetPurposeError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), Some(("channel", request.channel)), Some(("purpose", request.purpose)), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.setPurpose"); client .send(&url, &params[..]) .map_err(SetPurposeError::Client) .and_then(|result| { serde_json::from_str::<SetPurposeResponse>(&result) .map_err(SetPurposeError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct SetPurposeRequest<'a> { /// Private channel to set the purpose of pub channel: &'a str, /// The new purpose pub purpose: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct SetPurposeResponse { error: Option<String>, #[serde(default)] ok: bool, pub purpose: Option<String>, } impl<E: Error> Into<Result<SetPurposeResponse, SetPurposeError<E>>> for SetPurposeResponse { fn into(self) -> Result<SetPurposeResponse, SetPurposeError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum SetPurposeError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Private group has been archived IsArchived, /// Purpose was longer than 250 characters. TooLong, /// This method cannot be called by a restricted user or single channel guest. UserIsRestricted, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for SetPurposeError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => SetPurposeError::ChannelNotFound, "is_archived" => SetPurposeError::IsArchived, "too_long" => SetPurposeError::TooLong, "user_is_restricted" => SetPurposeError::UserIsRestricted, "not_authed" => SetPurposeError::NotAuthed, "invalid_auth" => SetPurposeError::InvalidAuth, "account_inactive" => SetPurposeError::AccountInactive, "invalid_arg_name" => SetPurposeError::InvalidArgName, "invalid_array_arg" => SetPurposeError::InvalidArrayArg, "invalid_charset" => SetPurposeError::InvalidCharset, "invalid_form_data" => SetPurposeError::InvalidFormData, "invalid_post_type" => SetPurposeError::InvalidPostType, "missing_post_type" => SetPurposeError::MissingPostType, "team_added_to_org" => SetPurposeError::TeamAddedToOrg, "request_timeout" => SetPurposeError::RequestTimeout, _ => SetPurposeError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for SetPurposeError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for SetPurposeError<E> { fn description(&self) -> &str { match *self { SetPurposeError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", SetPurposeError::IsArchived => "is_archived: Private group has been archived", SetPurposeError::TooLong => "too_long: Purpose was longer than 250 characters.", SetPurposeError::UserIsRestricted => "user_is_restricted: This method cannot be called by a restricted user or single channel guest.", SetPurposeError::NotAuthed => "not_authed: No authentication token provided.", SetPurposeError::InvalidAuth => "invalid_auth: Invalid authentication token.", SetPurposeError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", SetPurposeError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", SetPurposeError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", SetPurposeError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", SetPurposeError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", SetPurposeError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", SetPurposeError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", SetPurposeError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", SetPurposeError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", SetPurposeError::MalformedResponse(ref e) => e.description(), SetPurposeError::Unknown(ref s) => s, SetPurposeError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { SetPurposeError::MalformedResponse(ref e) => Some(e), SetPurposeError::Client(ref inner) => Some(inner), _ => None, } } } /// Sets the topic for a private channel. /// /// Wraps https://api.slack.com/methods/groups.setTopic pub fn set_topic<R>( client: &R, token: &str, request: &SetTopicRequest<'_>, ) -> Result<SetTopicResponse, SetTopicError<R::Error>> where R: SlackWebRequestSender, { let params = vec![ Some(("token", token)), Some(("channel", request.channel)), Some(("topic", request.topic)), ]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.setTopic"); client .send(&url, &params[..]) .map_err(SetTopicError::Client) .and_then(|result| { serde_json::from_str::<SetTopicResponse>(&result) .map_err(SetTopicError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct SetTopicRequest<'a> { /// Private channel to set the topic of pub channel: &'a str, /// The new topic pub topic: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct SetTopicResponse { error: Option<String>, #[serde(default)] ok: bool, pub topic: Option<String>, } impl<E: Error> Into<Result<SetTopicResponse, SetTopicError<E>>> for SetTopicResponse { fn into(self) -> Result<SetTopicResponse, SetTopicError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum SetTopicError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Private group has been archived IsArchived, /// Topic was longer than 250 characters. TooLong, /// This method cannot be called by a restricted user or single channel guest. UserIsRestricted, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for SetTopicError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => SetTopicError::ChannelNotFound, "is_archived" => SetTopicError::IsArchived, "too_long" => SetTopicError::TooLong, "user_is_restricted" => SetTopicError::UserIsRestricted, "not_authed" => SetTopicError::NotAuthed, "invalid_auth" => SetTopicError::InvalidAuth, "account_inactive" => SetTopicError::AccountInactive, "invalid_arg_name" => SetTopicError::InvalidArgName, "invalid_array_arg" => SetTopicError::InvalidArrayArg, "invalid_charset" => SetTopicError::InvalidCharset, "invalid_form_data" => SetTopicError::InvalidFormData, "invalid_post_type" => SetTopicError::InvalidPostType, "missing_post_type" => SetTopicError::MissingPostType, "team_added_to_org" => SetTopicError::TeamAddedToOrg, "request_timeout" => SetTopicError::RequestTimeout, _ => SetTopicError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for SetTopicError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for SetTopicError<E> { fn description(&self) -> &str { match *self { SetTopicError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", SetTopicError::IsArchived => "is_archived: Private group has been archived", SetTopicError::TooLong => "too_long: Topic was longer than 250 characters.", SetTopicError::UserIsRestricted => "user_is_restricted: This method cannot be called by a restricted user or single channel guest.", SetTopicError::NotAuthed => "not_authed: No authentication token provided.", SetTopicError::InvalidAuth => "invalid_auth: Invalid authentication token.", SetTopicError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", SetTopicError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", SetTopicError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", SetTopicError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", SetTopicError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", SetTopicError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", SetTopicError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", SetTopicError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", SetTopicError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", SetTopicError::MalformedResponse(ref e) => e.description(), SetTopicError::Unknown(ref s) => s, SetTopicError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { SetTopicError::MalformedResponse(ref e) => Some(e), SetTopicError::Client(ref inner) => Some(inner), _ => None, } } } /// Unarchives a private channel. /// /// Wraps https://api.slack.com/methods/groups.unarchive pub fn unarchive<R>( client: &R, token: &str, request: &UnarchiveRequest<'_>, ) -> Result<UnarchiveResponse, UnarchiveError<R::Error>> where R: SlackWebRequestSender, { let params = vec![Some(("token", token)), Some(("channel", request.channel))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("groups.unarchive"); client .send(&url, &params[..]) .map_err(UnarchiveError::Client) .and_then(|result| { serde_json::from_str::<UnarchiveResponse>(&result) .map_err(UnarchiveError::MalformedResponse) }) .and_then(|o| o.into()) } #[derive(Clone, Default, Debug)] pub struct UnarchiveRequest<'a> { /// Private channel to unarchive pub channel: &'a str, } #[derive(Clone, Debug, Deserialize)] pub struct UnarchiveResponse { error: Option<String>, #[serde(default)] ok: bool, } impl<E: Error> Into<Result<UnarchiveResponse, UnarchiveError<E>>> for UnarchiveResponse { fn into(self) -> Result<UnarchiveResponse, UnarchiveError<E>> { if self.ok { Ok(self) } else { Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into()) } } } #[derive(Debug)] pub enum UnarchiveError<E: Error> { /// Value passed for channel was invalid. ChannelNotFound, /// Group is not archived. NotArchived, /// No authentication token provided. NotAuthed, /// Invalid authentication token. InvalidAuth, /// Authentication token is for a deleted user or team. AccountInactive, /// This method cannot be called by a bot user. UserIsBot, /// This method cannot be called by a restricted user or single channel guest. UserIsRestricted, /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call. InvalidArgName, /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API. InvalidArrayArg, /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1. InvalidCharset, /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid. InvalidFormData, /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain. InvalidPostType, /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header. MissingPostType, /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. TeamAddedToOrg, /// The method was called via a POST request, but the POST data was either missing or truncated. RequestTimeout, /// The response was not parseable as the expected object MalformedResponse(serde_json::error::Error), /// The response returned an error that was unknown to the library Unknown(String), /// The client had an error sending the request to Slack Client(E), } impl<'a, E: Error> From<&'a str> for UnarchiveError<E> { fn from(s: &'a str) -> Self { match s { "channel_not_found" => UnarchiveError::ChannelNotFound, "not_archived" => UnarchiveError::NotArchived, "not_authed" => UnarchiveError::NotAuthed, "invalid_auth" => UnarchiveError::InvalidAuth, "account_inactive" => UnarchiveError::AccountInactive, "user_is_bot" => UnarchiveError::UserIsBot, "user_is_restricted" => UnarchiveError::UserIsRestricted, "invalid_arg_name" => UnarchiveError::InvalidArgName, "invalid_array_arg" => UnarchiveError::InvalidArrayArg, "invalid_charset" => UnarchiveError::InvalidCharset, "invalid_form_data" => UnarchiveError::InvalidFormData, "invalid_post_type" => UnarchiveError::InvalidPostType, "missing_post_type" => UnarchiveError::MissingPostType, "team_added_to_org" => UnarchiveError::TeamAddedToOrg, "request_timeout" => UnarchiveError::RequestTimeout, _ => UnarchiveError::Unknown(s.to_owned()), } } } impl<E: Error> fmt::Display for UnarchiveError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.description()) } } impl<E: Error> Error for UnarchiveError<E> { fn description(&self) -> &str { match *self { UnarchiveError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.", UnarchiveError::NotArchived => "not_archived: Group is not archived.", UnarchiveError::NotAuthed => "not_authed: No authentication token provided.", UnarchiveError::InvalidAuth => "invalid_auth: Invalid authentication token.", UnarchiveError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.", UnarchiveError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.", UnarchiveError::UserIsRestricted => "user_is_restricted: This method cannot be called by a restricted user or single channel guest.", UnarchiveError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.", UnarchiveError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.", UnarchiveError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.", UnarchiveError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.", UnarchiveError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.", UnarchiveError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.", UnarchiveError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.", UnarchiveError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.", UnarchiveError::MalformedResponse(ref e) => e.description(), UnarchiveError::Unknown(ref s) => s, UnarchiveError::Client(ref inner) => inner.description() } } fn cause(&self) -> Option<&dyn Error> { match *self { UnarchiveError::MalformedResponse(ref e) => Some(e), UnarchiveError::Client(ref inner) => Some(inner), _ => None, } } }
52.810923
331
0.694272
753d4ab700918fce3a5e6e7ecac0dc05aec161b2
150,112
// Copyright 2012-2013 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. use driver::session; use metadata::csearch; use metadata; use middle::const_eval; use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem}; use middle::lang_items::OpaqueStructLangItem; use middle::freevars; use middle::resolve; use middle::ty; use middle::subst::Subst; use middle::typeck; use middle; use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str}; use util::ppaux::{trait_store_to_str, ty_to_str, vstore_to_str}; use util::ppaux::{Repr, UserString}; use util::common::{indenter}; use std::cast; use std::cmp; use std::hashmap::{HashMap, HashSet}; use std::ops; use std::ptr::to_unsafe_ptr; use std::to_bytes; use std::to_str::ToStr; use std::vec; use syntax::ast::*; use syntax::ast_util::is_local; use syntax::ast_util; use syntax::attr; use syntax::codemap::Span; use syntax::codemap; use syntax::parse::token; use syntax::{ast, ast_map}; use syntax::opt_vec::OptVec; use syntax::opt_vec; use syntax::abi::AbiSet; use syntax; use extra::enum_set::{EnumSet, CLike}; pub type Disr = u64; pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0; // Data types #[deriving(Eq, IterBytes)] pub struct field { ident: ast::Ident, mt: mt } #[deriving(Clone)] pub enum MethodContainer { TraitContainer(ast::DefId), ImplContainer(ast::DefId), } #[deriving(Clone)] pub struct Method { ident: ast::Ident, generics: ty::Generics, transformed_self_ty: Option<ty::t>, fty: BareFnTy, explicit_self: ast::explicit_self_, vis: ast::visibility, def_id: ast::DefId, container: MethodContainer, // If this method is provided, we need to know where it came from provided_source: Option<ast::DefId> } impl Method { pub fn new(ident: ast::Ident, generics: ty::Generics, transformed_self_ty: Option<ty::t>, fty: BareFnTy, explicit_self: ast::explicit_self_, vis: ast::visibility, def_id: ast::DefId, container: MethodContainer, provided_source: Option<ast::DefId>) -> Method { // Check the invariants. if explicit_self == ast::sty_static { assert!(transformed_self_ty.is_none()); } else { assert!(transformed_self_ty.is_some()); } Method { ident: ident, generics: generics, transformed_self_ty: transformed_self_ty, fty: fty, explicit_self: explicit_self, vis: vis, def_id: def_id, container: container, provided_source: provided_source } } pub fn container_id(&self) -> ast::DefId { match self.container { TraitContainer(id) => id, ImplContainer(id) => id, } } } pub struct Impl { did: DefId, ident: Ident, methods: ~[@Method] } #[deriving(Clone, Eq, IterBytes)] pub struct mt { ty: t, mutbl: ast::Mutability, } #[deriving(Clone, Eq, Encodable, Decodable, IterBytes, ToStr)] pub enum vstore { vstore_fixed(uint), vstore_uniq, vstore_box, vstore_slice(Region) } #[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)] pub enum TraitStore { BoxTraitStore, // @Trait UniqTraitStore, // ~Trait RegionTraitStore(Region), // &Trait } // XXX: This should probably go away at some point. Maybe after destructors // do? #[deriving(Clone, Eq, Encodable, Decodable)] pub enum SelfMode { ByCopy, ByRef, } pub struct field_ty { name: Name, id: DefId, vis: ast::visibility, } // Contains information needed to resolve types and (in the future) look up // the types of AST nodes. #[deriving(Eq,IterBytes)] pub struct creader_cache_key { cnum: int, pos: uint, len: uint } type creader_cache = @mut HashMap<creader_cache_key, t>; struct intern_key { sty: *sty, } // NB: Do not replace this with #[deriving(Eq)]. The automatically-derived // implementation will not recurse through sty and you will get stack // exhaustion. impl cmp::Eq for intern_key { fn eq(&self, other: &intern_key) -> bool { unsafe { *self.sty == *other.sty } } fn ne(&self, other: &intern_key) -> bool { !self.eq(other) } } // NB: Do not replace this with #[deriving(IterBytes)], as above. (Figured // this out the hard way.) impl to_bytes::IterBytes for intern_key { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { unsafe { (*self.sty).iter_bytes(lsb0, f) } } } pub enum ast_ty_to_ty_cache_entry { atttce_unresolved, /* not resolved yet */ atttce_resolved(t) /* resolved to a type, irrespective of region */ } pub type opt_region_variance = Option<region_variance>; #[deriving(Clone, Eq, Decodable, Encodable)] pub enum region_variance { rv_covariant, rv_invariant, rv_contravariant, } #[deriving(Decodable, Encodable)] pub enum AutoAdjustment { AutoAddEnv(ty::Region, ast::Sigil), AutoDerefRef(AutoDerefRef) } #[deriving(Decodable, Encodable)] pub struct AutoDerefRef { autoderefs: uint, autoref: Option<AutoRef> } #[deriving(Decodable, Encodable)] pub enum AutoRef { /// Convert from T to &T AutoPtr(Region, ast::Mutability), /// Convert from @[]/~[]/&[] to &[] (or str) AutoBorrowVec(Region, ast::Mutability), /// Convert from @[]/~[]/&[] to &&[] (or str) AutoBorrowVecRef(Region, ast::Mutability), /// Convert from @fn()/~fn()/&fn() to &fn() AutoBorrowFn(Region), /// Convert from T to *T AutoUnsafe(ast::Mutability), /// Convert from @Trait/~Trait/&Trait to &Trait AutoBorrowObj(Region, ast::Mutability), } pub type ctxt = @ctxt_; struct ctxt_ { diag: @mut syntax::diagnostic::span_handler, interner: @mut HashMap<intern_key, ~t_box_>, next_id: @mut uint, cstore: @mut metadata::cstore::CStore, sess: session::Session, def_map: resolve::DefMap, region_maps: @mut middle::region::RegionMaps, region_paramd_items: middle::region::region_paramd_items, // Stores the types for various nodes in the AST. Note that this table // is not guaranteed to be populated until after typeck. See // typeck::check::fn_ctxt for details. node_types: node_type_table, // Stores the type parameters which were substituted to obtain the type // of this node. This only applies to nodes that refer to entities // parameterized by type parameters, such as generic fns, types, or // other items. node_type_substs: @mut HashMap<NodeId, ~[t]>, // Maps from a method to the method "descriptor" methods: @mut HashMap<DefId, @Method>, // Maps from a trait def-id to a list of the def-ids of its methods trait_method_def_ids: @mut HashMap<DefId, @~[DefId]>, // A cache for the trait_methods() routine trait_methods_cache: @mut HashMap<DefId, @~[@Method]>, impl_trait_cache: @mut HashMap<ast::DefId, Option<@ty::TraitRef>>, trait_refs: @mut HashMap<NodeId, @TraitRef>, trait_defs: @mut HashMap<DefId, @TraitDef>, items: ast_map::map, intrinsic_defs: @mut HashMap<ast::DefId, t>, freevars: freevars::freevar_map, tcache: type_cache, rcache: creader_cache, short_names_cache: @mut HashMap<t, @str>, needs_unwind_cleanup_cache: @mut HashMap<t, bool>, tc_cache: @mut HashMap<uint, TypeContents>, ast_ty_to_ty_cache: @mut HashMap<NodeId, ast_ty_to_ty_cache_entry>, enum_var_cache: @mut HashMap<DefId, @~[@VariantInfo]>, ty_param_defs: @mut HashMap<ast::NodeId, TypeParameterDef>, adjustments: @mut HashMap<ast::NodeId, @AutoAdjustment>, normalized_cache: @mut HashMap<t, t>, lang_items: middle::lang_items::LanguageItems, // A mapping of fake provided method def_ids to the default implementation provided_method_sources: @mut HashMap<ast::DefId, ast::DefId>, supertraits: @mut HashMap<ast::DefId, @~[@TraitRef]>, // A mapping from the def ID of an enum or struct type to the def ID // of the method that implements its destructor. If the type is not // present in this map, it does not have a destructor. This map is // populated during the coherence phase of typechecking. destructor_for_type: @mut HashMap<ast::DefId, ast::DefId>, // A method will be in this list if and only if it is a destructor. destructors: @mut HashSet<ast::DefId>, // Maps a trait onto a list of impls of that trait. trait_impls: @mut HashMap<ast::DefId, @mut ~[@Impl]>, // Maps a def_id of a type to a list of its inherent impls. // Contains implementations of methods that are inherent to a type. // Methods in these implementations don't need to be exported. inherent_impls: @mut HashMap<ast::DefId, @mut ~[@Impl]>, // Maps a def_id of an impl to an Impl structure. // Note that this contains all of the impls that we know about, // including ones in other crates. It's not clear that this is the best // way to do it. impls: @mut HashMap<ast::DefId, @Impl>, // Set of used unsafe nodes (functions or blocks). Unsafe nodes not // present in this set can be warned about. used_unsafe: @mut HashSet<ast::NodeId>, // Set of nodes which mark locals as mutable which end up getting used at // some point. Local variable definitions not in this set can be warned // about. used_mut_nodes: @mut HashSet<ast::NodeId>, // vtable resolution information for impl declarations impl_vtables: typeck::impl_vtable_map, // The set of external nominal types whose implementations have been read. // This is used for lazy resolution of methods. populated_external_types: @mut HashSet<ast::DefId>, // The set of external traits whose implementations have been read. This // is used for lazy resolution of traits. populated_external_traits: @mut HashSet<ast::DefId>, // These two caches are used by const_eval when decoding external statics // and variants that are found. extern_const_statics: @mut HashMap<ast::DefId, Option<@ast::Expr>>, extern_const_variants: @mut HashMap<ast::DefId, Option<@ast::Expr>>, } pub enum tbox_flag { has_params = 1, has_self = 2, needs_infer = 4, has_regions = 8, has_ty_err = 16, has_ty_bot = 32, // a meta-flag: subst may be required if the type has parameters, a self // type, or references bound regions needs_subst = 1 | 2 | 8 } pub type t_box = &'static t_box_; pub struct t_box_ { sty: sty, id: uint, flags: uint, } // To reduce refcounting cost, we're representing types as unsafe pointers // throughout the compiler. These are simply casted t_box values. Use ty::get // to cast them back to a box. (Without the cast, compiler performance suffers // ~15%.) This does mean that a t value relies on the ctxt to keep its box // alive, and using ty::get is unsafe when the ctxt is no longer alive. enum t_opaque {} pub type t = *t_opaque; impl ToStr for t { fn to_str(&self) -> ~str { ~"*t_opaque" } } pub fn get(t: t) -> t_box { unsafe { let t2: t_box = cast::transmute(t); t2 } } pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool { (tb.flags & (flag as uint)) != 0u } pub fn type_has_params(t: t) -> bool { tbox_has_flag(get(t), has_params) } pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) } pub fn type_needs_infer(t: t) -> bool { tbox_has_flag(get(t), needs_infer) } pub fn type_has_regions(t: t) -> bool { tbox_has_flag(get(t), has_regions) } pub fn type_id(t: t) -> uint { get(t).id } #[deriving(Clone, Eq, IterBytes)] pub struct BareFnTy { purity: ast::purity, abis: AbiSet, sig: FnSig } #[deriving(Clone, Eq, IterBytes)] pub struct ClosureTy { purity: ast::purity, sigil: ast::Sigil, onceness: ast::Onceness, region: Region, bounds: BuiltinBounds, sig: FnSig, } /** * Signature of a function type, which I have arbitrarily * decided to use to refer to the input/output types. * * - `lifetimes` is the list of region names bound in this fn. * - `inputs` is the list of arguments and their modes. * - `output` is the return type. */ #[deriving(Clone, Eq, IterBytes)] pub struct FnSig { bound_lifetime_names: OptVec<ast::Ident>, inputs: ~[t], output: t } #[deriving(Clone, Eq, IterBytes)] pub struct param_ty { idx: uint, def_id: DefId } /// Representation of regions: #[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)] pub enum Region { /// Bound regions are found (primarily) in function types. They indicate /// region parameters that have yet to be replaced with actual regions /// (analogous to type parameters, except that due to the monomorphic /// nature of our type system, bound type parameters are always replaced /// with fresh type variables whenever an item is referenced, so type /// parameters only appear "free" in types. Regions in contrast can /// appear free or bound.). When a function is called, all bound regions /// tied to that function's node-id are replaced with fresh region /// variables whose value is then inferred. re_bound(bound_region), /// When checking a function body, the types of all arguments and so forth /// that refer to bound region parameters are modified to refer to free /// region parameters. re_free(FreeRegion), /// A concrete region naming some expression within the current function. re_scope(NodeId), /// Static data that has an "infinite" lifetime. Top in the region lattice. re_static, /// A region variable. Should not exist after typeck. re_infer(InferRegion), /// Empty lifetime is for data that is never accessed. /// Bottom in the region lattice. We treat re_empty somewhat /// specially; at least right now, we do not generate instances of /// it during the GLB computations, but rather /// generate an error instead. This is to improve error messages. /// The only way to get an instance of re_empty is to have a region /// variable with no constraints. re_empty, } impl Region { pub fn is_bound(&self) -> bool { match self { &re_bound(*) => true, _ => false } } } #[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)] pub struct FreeRegion { scope_id: NodeId, bound_region: bound_region } #[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)] pub enum bound_region { /// The self region for structs, impls (&T in a type defn or &'self T) br_self, /// An anonymous region parameter for a given fn (&T) br_anon(uint), /// Named region parameters for functions (a in &'a T) br_named(ast::Ident), /// Fresh bound identifiers created during GLB computations. br_fresh(uint), /** * Handles capture-avoiding substitution in a rather subtle case. If you * have a closure whose argument types are being inferred based on the * expected type, and the expected type includes bound regions, then we * will wrap those bound regions in a br_cap_avoid() with the id of the * fn expression. This ensures that the names are not "captured" by the * enclosing scope, which may define the same names. For an example of * where this comes up, see src/test/compile-fail/regions-ret-borrowed.rs * and regions-ret-borrowed-1.rs. */ br_cap_avoid(ast::NodeId, @bound_region), } /** * Represents the values to use when substituting lifetime parameters. * If the value is `ErasedRegions`, then this subst is occurring during * trans, and all region parameters will be replaced with `ty::re_static`. */ #[deriving(Clone, Eq, IterBytes)] pub enum RegionSubsts { ErasedRegions, NonerasedRegions(OptVec<ty::Region>) } /** * The type substs represents the kinds of things that can be substituted to * convert a polytype into a monotype. Note however that substituting bound * regions other than `self` is done through a different mechanism: * * - `tps` represents the type parameters in scope. They are indexed * according to the order in which they were declared. * * - `self_r` indicates the region parameter `self` that is present on nominal * types (enums, structs) declared as having a region parameter. `self_r` * should always be none for types that are not region-parameterized and * Some(_) for types that are. The only bound region parameter that should * appear within a region-parameterized type is `self`. * * - `self_ty` is the type to which `self` should be remapped, if any. The * `self` type is rather funny in that it can only appear on traits and is * always substituted away to the implementing type for a trait. */ #[deriving(Clone, Eq, IterBytes)] pub struct substs { self_ty: Option<ty::t>, tps: ~[t], regions: RegionSubsts, } mod primitives { use super::t_box_; use syntax::ast; macro_rules! def_prim_ty( ($name:ident, $sty:expr, $id:expr) => ( pub static $name: t_box_ = t_box_ { sty: $sty, id: $id, flags: 0, }; ) ) def_prim_ty!(TY_NIL, super::ty_nil, 0) def_prim_ty!(TY_BOOL, super::ty_bool, 1) def_prim_ty!(TY_CHAR, super::ty_char, 2) def_prim_ty!(TY_INT, super::ty_int(ast::ty_i), 3) def_prim_ty!(TY_I8, super::ty_int(ast::ty_i8), 4) def_prim_ty!(TY_I16, super::ty_int(ast::ty_i16), 5) def_prim_ty!(TY_I32, super::ty_int(ast::ty_i32), 6) def_prim_ty!(TY_I64, super::ty_int(ast::ty_i64), 7) def_prim_ty!(TY_UINT, super::ty_uint(ast::ty_u), 8) def_prim_ty!(TY_U8, super::ty_uint(ast::ty_u8), 9) def_prim_ty!(TY_U16, super::ty_uint(ast::ty_u16), 10) def_prim_ty!(TY_U32, super::ty_uint(ast::ty_u32), 11) def_prim_ty!(TY_U64, super::ty_uint(ast::ty_u64), 12) def_prim_ty!(TY_F32, super::ty_float(ast::ty_f32), 14) def_prim_ty!(TY_F64, super::ty_float(ast::ty_f64), 15) pub static TY_BOT: t_box_ = t_box_ { sty: super::ty_bot, id: 16, flags: super::has_ty_bot as uint, }; pub static TY_ERR: t_box_ = t_box_ { sty: super::ty_err, id: 17, flags: super::has_ty_err as uint, }; pub static LAST_PRIMITIVE_ID: uint = 18; } // NB: If you change this, you'll probably want to change the corresponding // AST structure in libsyntax/ast.rs as well. #[deriving(Clone, Eq, IterBytes)] pub enum sty { ty_nil, ty_bot, ty_bool, ty_char, ty_int(ast::int_ty), ty_uint(ast::uint_ty), ty_float(ast::float_ty), ty_estr(vstore), ty_enum(DefId, substs), ty_box(mt), ty_uniq(mt), ty_evec(mt, vstore), ty_ptr(mt), ty_rptr(Region, mt), ty_bare_fn(BareFnTy), ty_closure(ClosureTy), ty_trait(DefId, substs, TraitStore, ast::Mutability, BuiltinBounds), ty_struct(DefId, substs), ty_tup(~[t]), ty_param(param_ty), // type parameter ty_self(DefId), /* special, implicit `self` type parameter; * def_id is the id of the trait */ ty_infer(InferTy), // something used only during inference/typeck ty_err, // Also only used during inference/typeck, to represent // the type of an erroneous expression (helps cut down // on non-useful type error messages) // "Fake" types, used for trans purposes ty_type, // type_desc* ty_opaque_box, // used by monomorphizer to represent any @ box ty_opaque_closure_ptr(Sigil), // ptr to env for &fn, @fn, ~fn ty_unboxed_vec(mt), } #[deriving(Eq, IterBytes)] pub struct TraitRef { def_id: DefId, substs: substs } #[deriving(Clone, Eq)] pub enum IntVarValue { IntType(ast::int_ty), UintType(ast::uint_ty), } #[deriving(Clone, ToStr)] pub enum terr_vstore_kind { terr_vec, terr_str, terr_fn, terr_trait } #[deriving(Clone, ToStr)] pub struct expected_found<T> { expected: T, found: T } // Data structures used in type unification #[deriving(Clone, ToStr)] pub enum type_err { terr_mismatch, terr_purity_mismatch(expected_found<purity>), terr_onceness_mismatch(expected_found<Onceness>), terr_abi_mismatch(expected_found<AbiSet>), terr_mutability, terr_sigil_mismatch(expected_found<ast::Sigil>), terr_box_mutability, terr_ptr_mutability, terr_ref_mutability, terr_vec_mutability, terr_tuple_size(expected_found<uint>), terr_ty_param_size(expected_found<uint>), terr_record_size(expected_found<uint>), terr_record_mutability, terr_record_fields(expected_found<Ident>), terr_arg_count, terr_regions_does_not_outlive(Region, Region), terr_regions_not_same(Region, Region), terr_regions_no_overlap(Region, Region), terr_regions_insufficiently_polymorphic(bound_region, Region), terr_regions_overly_polymorphic(bound_region, Region), terr_vstores_differ(terr_vstore_kind, expected_found<vstore>), terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>), terr_in_field(@type_err, ast::Ident), terr_sorts(expected_found<t>), terr_integer_as_char, terr_int_mismatch(expected_found<IntVarValue>), terr_float_mismatch(expected_found<ast::float_ty>), terr_traits(expected_found<ast::DefId>), terr_builtin_bounds(expected_found<BuiltinBounds>), } #[deriving(Eq, IterBytes)] pub struct ParamBounds { builtin_bounds: BuiltinBounds, trait_bounds: ~[@TraitRef] } pub type BuiltinBounds = EnumSet<BuiltinBound>; #[deriving(Clone, Eq, IterBytes, ToStr)] pub enum BuiltinBound { BoundStatic, BoundSend, BoundFreeze, BoundSized, } pub fn EmptyBuiltinBounds() -> BuiltinBounds { EnumSet::empty() } pub fn AllBuiltinBounds() -> BuiltinBounds { let mut set = EnumSet::empty(); set.add(BoundStatic); set.add(BoundSend); set.add(BoundFreeze); set.add(BoundSized); set } impl CLike for BuiltinBound { fn to_uint(&self) -> uint { *self as uint } fn from_uint(v: uint) -> BuiltinBound { unsafe { cast::transmute(v) } } } #[deriving(Clone, Eq, IterBytes)] pub struct TyVid(uint); #[deriving(Clone, Eq, IterBytes)] pub struct IntVid(uint); #[deriving(Clone, Eq, IterBytes)] pub struct FloatVid(uint); #[deriving(Clone, Eq, Encodable, Decodable, IterBytes)] pub struct RegionVid { id: uint } #[deriving(Clone, Eq, IterBytes)] pub enum InferTy { TyVar(TyVid), IntVar(IntVid), FloatVar(FloatVid) } #[deriving(Clone, Encodable, Decodable, IterBytes, ToStr)] pub enum InferRegion { ReVar(RegionVid), ReSkolemized(uint, bound_region) } impl cmp::Eq for InferRegion { fn eq(&self, other: &InferRegion) -> bool { match ((*self), *other) { (ReVar(rva), ReVar(rvb)) => { rva == rvb } (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => { rva == rvb } _ => false } } fn ne(&self, other: &InferRegion) -> bool { !((*self) == (*other)) } } pub trait Vid { fn to_uint(&self) -> uint; } impl Vid for TyVid { fn to_uint(&self) -> uint { **self } } impl ToStr for TyVid { fn to_str(&self) -> ~str { format!("<V{}>", self.to_uint()) } } impl Vid for IntVid { fn to_uint(&self) -> uint { **self } } impl ToStr for IntVid { fn to_str(&self) -> ~str { format!("<VI{}>", self.to_uint()) } } impl Vid for FloatVid { fn to_uint(&self) -> uint { **self } } impl ToStr for FloatVid { fn to_str(&self) -> ~str { format!("<VF{}>", self.to_uint()) } } impl Vid for RegionVid { fn to_uint(&self) -> uint { self.id } } impl ToStr for RegionVid { fn to_str(&self) -> ~str { format!("{:?}", self.id) } } impl ToStr for FnSig { fn to_str(&self) -> ~str { // grr, without tcx not much we can do. return ~"(...)"; } } impl ToStr for InferTy { fn to_str(&self) -> ~str { match *self { TyVar(ref v) => v.to_str(), IntVar(ref v) => v.to_str(), FloatVar(ref v) => v.to_str() } } } impl ToStr for IntVarValue { fn to_str(&self) -> ~str { match *self { IntType(ref v) => v.to_str(), UintType(ref v) => v.to_str(), } } } #[deriving(Clone)] pub struct TypeParameterDef { ident: ast::Ident, def_id: ast::DefId, bounds: @ParamBounds } /// Information about the type/lifetime parametesr associated with an item. /// Analogous to ast::Generics. #[deriving(Clone)] pub struct Generics { type_param_defs: @~[TypeParameterDef], region_param: Option<region_variance>, } impl Generics { pub fn has_type_params(&self) -> bool { !self.type_param_defs.is_empty() } } /// A polytype. /// /// - `bounds`: The list of bounds for each type parameter. The length of the /// list also tells you how many type parameters there are. /// /// - `rp`: true if the type is region-parameterized. Types can have at /// most one region parameter, always called `&self`. /// /// - `ty`: the base type. May have reference to the (unsubstituted) bound /// region `&self` or to (unsubstituted) ty_param types #[deriving(Clone)] pub struct ty_param_bounds_and_ty { generics: Generics, ty: t } /// As `ty_param_bounds_and_ty` but for a trait ref. pub struct TraitDef { generics: Generics, bounds: BuiltinBounds, trait_ref: @ty::TraitRef, } pub struct ty_param_substs_and_ty { substs: ty::substs, ty: ty::t } type type_cache = @mut HashMap<ast::DefId, ty_param_bounds_and_ty>; pub type node_type_table = @mut HashMap<uint,t>; fn mk_rcache() -> creader_cache { return @mut HashMap::new(); } pub fn new_ty_hash<V:'static>() -> @mut HashMap<t, V> { @mut HashMap::new() } pub fn mk_ctxt(s: session::Session, dm: resolve::DefMap, amap: ast_map::map, freevars: freevars::freevar_map, region_maps: @mut middle::region::RegionMaps, region_paramd_items: middle::region::region_paramd_items, lang_items: middle::lang_items::LanguageItems) -> ctxt { @ctxt_ { diag: s.diagnostic(), interner: @mut HashMap::new(), next_id: @mut primitives::LAST_PRIMITIVE_ID, cstore: s.cstore, sess: s, def_map: dm, region_maps: region_maps, region_paramd_items: region_paramd_items, node_types: @mut HashMap::new(), node_type_substs: @mut HashMap::new(), trait_refs: @mut HashMap::new(), trait_defs: @mut HashMap::new(), items: amap, intrinsic_defs: @mut HashMap::new(), freevars: freevars, tcache: @mut HashMap::new(), rcache: mk_rcache(), short_names_cache: new_ty_hash(), needs_unwind_cleanup_cache: new_ty_hash(), tc_cache: @mut HashMap::new(), ast_ty_to_ty_cache: @mut HashMap::new(), enum_var_cache: @mut HashMap::new(), methods: @mut HashMap::new(), trait_method_def_ids: @mut HashMap::new(), trait_methods_cache: @mut HashMap::new(), impl_trait_cache: @mut HashMap::new(), ty_param_defs: @mut HashMap::new(), adjustments: @mut HashMap::new(), normalized_cache: new_ty_hash(), lang_items: lang_items, provided_method_sources: @mut HashMap::new(), supertraits: @mut HashMap::new(), destructor_for_type: @mut HashMap::new(), destructors: @mut HashSet::new(), trait_impls: @mut HashMap::new(), inherent_impls: @mut HashMap::new(), impls: @mut HashMap::new(), used_unsafe: @mut HashSet::new(), used_mut_nodes: @mut HashSet::new(), impl_vtables: @mut HashMap::new(), populated_external_types: @mut HashSet::new(), populated_external_traits: @mut HashSet::new(), extern_const_statics: @mut HashMap::new(), extern_const_variants: @mut HashMap::new(), } } // Type constructors // Interns a type/name combination, stores the resulting box in cx.interner, // and returns the box as cast to an unsafe ptr (see comments for t above). fn mk_t(cx: ctxt, st: sty) -> t { // Check for primitive types. match st { ty_nil => return mk_nil(), ty_err => return mk_err(), ty_bool => return mk_bool(), ty_int(i) => return mk_mach_int(i), ty_uint(u) => return mk_mach_uint(u), ty_float(f) => return mk_mach_float(f), _ => {} }; let key = intern_key { sty: to_unsafe_ptr(&st) }; match cx.interner.find(&key) { Some(t) => unsafe { return cast::transmute(&t.sty); }, _ => () } let mut flags = 0u; fn rflags(r: Region) -> uint { (has_regions as uint) | { match r { ty::re_infer(_) => needs_infer as uint, _ => 0u } } } fn sflags(substs: &substs) -> uint { let mut f = 0u; for tt in substs.tps.iter() { f |= get(*tt).flags; } match substs.regions { ErasedRegions => {} NonerasedRegions(ref regions) => { for r in regions.iter() { f |= rflags(*r) } } } return f; } match &st { &ty_estr(vstore_slice(r)) => { flags |= rflags(r); } &ty_evec(ref mt, vstore_slice(r)) => { flags |= rflags(r); flags |= get(mt.ty).flags; } &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) | &ty_estr(_) | &ty_type | &ty_opaque_closure_ptr(_) | &ty_opaque_box => (), // You might think that we could just return ty_err for // any type containing ty_err as a component, and get // rid of the has_ty_err flag -- likewise for ty_bot (with // the exception of function types that return bot). // But doing so caused sporadic memory corruption, and // neither I (tjc) nor nmatsakis could figure out why, // so we're doing it this way. &ty_bot => flags |= has_ty_bot as uint, &ty_err => flags |= has_ty_err as uint, &ty_param(_) => flags |= has_params as uint, &ty_infer(_) => flags |= needs_infer as uint, &ty_self(_) => flags |= has_self as uint, &ty_enum(_, ref substs) | &ty_struct(_, ref substs) | &ty_trait(_, ref substs, _, _, _) => { flags |= sflags(substs); match st { ty_trait(_, _, RegionTraitStore(r), _, _) => { flags |= rflags(r); } _ => {} } } &ty_box(ref m) | &ty_uniq(ref m) | &ty_evec(ref m, _) | &ty_ptr(ref m) | &ty_unboxed_vec(ref m) => { flags |= get(m.ty).flags; } &ty_rptr(r, ref m) => { flags |= rflags(r); flags |= get(m.ty).flags; } &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; }, &ty_bare_fn(ref f) => { for a in f.sig.inputs.iter() { flags |= get(*a).flags; } flags |= get(f.sig.output).flags; // T -> _|_ is *not* _|_ ! flags &= !(has_ty_bot as uint); } &ty_closure(ref f) => { flags |= rflags(f.region); for a in f.sig.inputs.iter() { flags |= get(*a).flags; } flags |= get(f.sig.output).flags; // T -> _|_ is *not* _|_ ! flags &= !(has_ty_bot as uint); } } let t = ~t_box_ { sty: st, id: *cx.next_id, flags: flags, }; let sty_ptr = to_unsafe_ptr(&t.sty); let key = intern_key { sty: sty_ptr, }; cx.interner.insert(key, t); *cx.next_id += 1; unsafe { cast::transmute::<*sty, t>(sty_ptr) } } #[inline] pub fn mk_prim_t(primitive: &'static t_box_) -> t { unsafe { cast::transmute::<&'static t_box_, t>(primitive) } } #[inline] pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) } #[inline] pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) } #[inline] pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) } #[inline] pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) } #[inline] pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) } #[inline] pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) } #[inline] pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) } #[inline] pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) } #[inline] pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) } #[inline] pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) } #[inline] pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) } #[inline] pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) } #[inline] pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) } #[inline] pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) } #[inline] pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) } #[inline] pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) } pub fn mk_mach_int(tm: ast::int_ty) -> t { match tm { ast::ty_i => mk_int(), ast::ty_i8 => mk_i8(), ast::ty_i16 => mk_i16(), ast::ty_i32 => mk_i32(), ast::ty_i64 => mk_i64(), } } pub fn mk_mach_uint(tm: ast::uint_ty) -> t { match tm { ast::ty_u => mk_uint(), ast::ty_u8 => mk_u8(), ast::ty_u16 => mk_u16(), ast::ty_u32 => mk_u32(), ast::ty_u64 => mk_u64(), } } pub fn mk_mach_float(tm: ast::float_ty) -> t { match tm { ast::ty_f32 => mk_f32(), ast::ty_f64 => mk_f64(), } } #[inline] pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) } pub fn mk_estr(cx: ctxt, t: vstore) -> t { mk_t(cx, ty_estr(t)) } pub fn mk_enum(cx: ctxt, did: ast::DefId, substs: substs) -> t { // take a copy of substs so that we own the vectors inside mk_t(cx, ty_enum(did, substs)) } pub fn mk_box(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_box(tm)) } pub fn mk_imm_box(cx: ctxt, ty: t) -> t { mk_box(cx, mt {ty: ty, mutbl: ast::MutImmutable}) } pub fn mk_uniq(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_uniq(tm)) } pub fn mk_imm_uniq(cx: ctxt, ty: t) -> t { mk_uniq(cx, mt {ty: ty, mutbl: ast::MutImmutable}) } pub fn mk_ptr(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) } pub fn mk_rptr(cx: ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) } pub fn mk_mut_rptr(cx: ctxt, r: Region, ty: t) -> t { mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable}) } pub fn mk_imm_rptr(cx: ctxt, r: Region, ty: t) -> t { mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable}) } pub fn mk_mut_ptr(cx: ctxt, ty: t) -> t { mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable}) } pub fn mk_imm_ptr(cx: ctxt, ty: t) -> t { mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable}) } pub fn mk_nil_ptr(cx: ctxt) -> t { mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable}) } pub fn mk_evec(cx: ctxt, tm: mt, t: vstore) -> t { mk_t(cx, ty_evec(tm, t)) } pub fn mk_unboxed_vec(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_unboxed_vec(tm)) } pub fn mk_mut_unboxed_vec(cx: ctxt, ty: t) -> t { mk_t(cx, ty_unboxed_vec(mt {ty: ty, mutbl: ast::MutImmutable})) } pub fn mk_tup(cx: ctxt, ts: ~[t]) -> t { mk_t(cx, ty_tup(ts)) } pub fn mk_closure(cx: ctxt, fty: ClosureTy) -> t { mk_t(cx, ty_closure(fty)) } pub fn mk_bare_fn(cx: ctxt, fty: BareFnTy) -> t { mk_t(cx, ty_bare_fn(fty)) } pub fn mk_ctor_fn(cx: ctxt, input_tys: &[ty::t], output: ty::t) -> t { let input_args = input_tys.map(|t| *t); mk_bare_fn(cx, BareFnTy { purity: ast::impure_fn, abis: AbiSet::Rust(), sig: FnSig { bound_lifetime_names: opt_vec::Empty, inputs: input_args, output: output } }) } pub fn mk_trait(cx: ctxt, did: ast::DefId, substs: substs, store: TraitStore, mutability: ast::Mutability, bounds: BuiltinBounds) -> t { // take a copy of substs so that we own the vectors inside mk_t(cx, ty_trait(did, substs, store, mutability, bounds)) } pub fn mk_struct(cx: ctxt, struct_id: ast::DefId, substs: substs) -> t { // take a copy of substs so that we own the vectors inside mk_t(cx, ty_struct(struct_id, substs)) } pub fn mk_var(cx: ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) } pub fn mk_int_var(cx: ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) } pub fn mk_float_var(cx: ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) } pub fn mk_infer(cx: ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) } pub fn mk_self(cx: ctxt, did: ast::DefId) -> t { mk_t(cx, ty_self(did)) } pub fn mk_param(cx: ctxt, n: uint, k: DefId) -> t { mk_t(cx, ty_param(param_ty { idx: n, def_id: k })) } pub fn mk_type(cx: ctxt) -> t { mk_t(cx, ty_type) } pub fn mk_opaque_closure_ptr(cx: ctxt, sigil: ast::Sigil) -> t { mk_t(cx, ty_opaque_closure_ptr(sigil)) } pub fn mk_opaque_box(cx: ctxt) -> t { mk_t(cx, ty_opaque_box) } pub fn walk_ty(ty: t, f: &fn(t)) { maybe_walk_ty(ty, |t| { f(t); true }); } pub fn maybe_walk_ty(ty: t, f: &fn(t) -> bool) { if !f(ty) { return; } match get(ty).sty { ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) | ty_estr(_) | ty_type | ty_opaque_box | ty_self(_) | ty_opaque_closure_ptr(_) | ty_infer(_) | ty_param(_) | ty_err => { } ty_box(ref tm) | ty_evec(ref tm, _) | ty_unboxed_vec(ref tm) | ty_ptr(ref tm) | ty_rptr(_, ref tm) | ty_uniq(ref tm) => { maybe_walk_ty(tm.ty, f); } ty_enum(_, ref substs) | ty_struct(_, ref substs) | ty_trait(_, ref substs, _, _, _) => { for subty in (*substs).tps.iter() { maybe_walk_ty(*subty, |x| f(x)); } } ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } } ty_bare_fn(ref ft) => { for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); } maybe_walk_ty(ft.sig.output, f); } ty_closure(ref ft) => { for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); } maybe_walk_ty(ft.sig.output, f); } } } pub fn fold_sty_to_ty(tcx: ty::ctxt, sty: &sty, foldop: &fn(t) -> t) -> t { mk_t(tcx, fold_sty(sty, foldop)) } pub fn fold_sig(sig: &FnSig, fldop: &fn(t) -> t) -> FnSig { let args = sig.inputs.map(|arg| fldop(*arg)); FnSig { bound_lifetime_names: sig.bound_lifetime_names.clone(), inputs: args, output: fldop(sig.output) } } pub fn fold_bare_fn_ty(fty: &BareFnTy, fldop: &fn(t) -> t) -> BareFnTy { BareFnTy {sig: fold_sig(&fty.sig, fldop), abis: fty.abis, purity: fty.purity} } fn fold_sty(sty: &sty, fldop: &fn(t) -> t) -> sty { fn fold_substs(substs: &substs, fldop: &fn(t) -> t) -> substs { substs {regions: substs.regions.clone(), self_ty: substs.self_ty.map(|t| fldop(t)), tps: substs.tps.map(|t| fldop(*t))} } match *sty { ty_box(ref tm) => { ty_box(mt {ty: fldop(tm.ty), mutbl: tm.mutbl}) } ty_uniq(ref tm) => { ty_uniq(mt {ty: fldop(tm.ty), mutbl: tm.mutbl}) } ty_ptr(ref tm) => { ty_ptr(mt {ty: fldop(tm.ty), mutbl: tm.mutbl}) } ty_unboxed_vec(ref tm) => { ty_unboxed_vec(mt {ty: fldop(tm.ty), mutbl: tm.mutbl}) } ty_evec(ref tm, vst) => { ty_evec(mt {ty: fldop(tm.ty), mutbl: tm.mutbl}, vst) } ty_enum(tid, ref substs) => { ty_enum(tid, fold_substs(substs, fldop)) } ty_trait(did, ref substs, st, mutbl, bounds) => { ty_trait(did, fold_substs(substs, fldop), st, mutbl, bounds) } ty_tup(ref ts) => { let new_ts = ts.map(|tt| fldop(*tt)); ty_tup(new_ts) } ty_bare_fn(ref f) => { ty_bare_fn(fold_bare_fn_ty(f, fldop)) } ty_closure(ref f) => { let sig = fold_sig(&f.sig, fldop); ty_closure(ClosureTy { sig: sig, purity: f.purity, sigil: f.sigil, onceness: f.onceness, region: f.region, bounds: f.bounds, }) } ty_rptr(r, ref tm) => { ty_rptr(r, mt {ty: fldop(tm.ty), mutbl: tm.mutbl}) } ty_struct(did, ref substs) => { ty_struct(did, fold_substs(substs, fldop)) } ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) | ty_estr(_) | ty_type | ty_opaque_closure_ptr(_) | ty_err | ty_opaque_box | ty_infer(_) | ty_param(*) | ty_self(_) => { (*sty).clone() } } } // Folds types from the bottom up. pub fn fold_ty(cx: ctxt, t0: t, fldop: &fn(t) -> t) -> t { let sty = fold_sty(&get(t0).sty, |t| fold_ty(cx, fldop(t), |t| fldop(t))); fldop(mk_t(cx, sty)) } pub fn walk_regions_and_ty( cx: ctxt, ty: t, walkr: &fn(r: Region), walkt: &fn(t: t) -> bool) { if (walkt(ty)) { fold_regions_and_ty( cx, ty, |r| { walkr(r); r }, |t| { walk_regions_and_ty(cx, t, |r| walkr(r), |t| walkt(t)); t }, |t| { walk_regions_and_ty(cx, t, |r| walkr(r), |t| walkt(t)); t }); } } pub fn fold_regions_and_ty( cx: ctxt, ty: t, fldr: &fn(r: Region) -> Region, fldfnt: &fn(t: t) -> t, fldt: &fn(t: t) -> t) -> t { fn fold_substs( substs: &substs, fldr: &fn(r: Region) -> Region, fldt: &fn(t: t) -> t) -> substs { let regions = match substs.regions { ErasedRegions => ErasedRegions, NonerasedRegions(ref regions) => { NonerasedRegions(regions.map(|r| fldr(*r))) } }; substs { regions: regions, self_ty: substs.self_ty.map(|t| fldt(t)), tps: substs.tps.map(|t| fldt(*t)) } } let tb = ty::get(ty); match tb.sty { ty::ty_rptr(r, mt) => { let m_r = fldr(r); let m_t = fldt(mt.ty); ty::mk_rptr(cx, m_r, mt {ty: m_t, mutbl: mt.mutbl}) } ty_estr(vstore_slice(r)) => { let m_r = fldr(r); ty::mk_estr(cx, vstore_slice(m_r)) } ty_evec(mt, vstore_slice(r)) => { let m_r = fldr(r); let m_t = fldt(mt.ty); ty::mk_evec(cx, mt {ty: m_t, mutbl: mt.mutbl}, vstore_slice(m_r)) } ty_enum(def_id, ref substs) => { ty::mk_enum(cx, def_id, fold_substs(substs, fldr, fldt)) } ty_struct(def_id, ref substs) => { ty::mk_struct(cx, def_id, fold_substs(substs, fldr, fldt)) } ty_trait(def_id, ref substs, st, mutbl, bounds) => { let st = match st { RegionTraitStore(region) => RegionTraitStore(fldr(region)), st => st, }; ty::mk_trait(cx, def_id, fold_substs(substs, fldr, fldt), st, mutbl, bounds) } ty_bare_fn(ref f) => { ty::mk_bare_fn(cx, BareFnTy { sig: fold_sig(&f.sig, fldfnt), purity: f.purity, abis: f.abis.clone(), }) } ty_closure(ref f) => { ty::mk_closure(cx, ClosureTy { region: fldr(f.region), sig: fold_sig(&f.sig, fldfnt), purity: f.purity, sigil: f.sigil, onceness: f.onceness, bounds: f.bounds, }) } ref sty => { fold_sty_to_ty(cx, sty, |t| fldt(t)) } } } // n.b. this function is intended to eventually replace fold_region() below, // that is why its name is so similar. pub fn fold_regions( cx: ctxt, ty: t, fldr: &fn(r: Region, in_fn: bool) -> Region) -> t { fn do_fold(cx: ctxt, ty: t, in_fn: bool, fldr: &fn(Region, bool) -> Region) -> t { debug2!("do_fold(ty={}, in_fn={})", ty_to_str(cx, ty), in_fn); if !type_has_regions(ty) { return ty; } fold_regions_and_ty( cx, ty, |r| fldr(r, in_fn), |t| do_fold(cx, t, true, |r,b| fldr(r,b)), |t| do_fold(cx, t, in_fn, |r,b| fldr(r,b))) } do_fold(cx, ty, false, fldr) } // Substitute *only* type parameters. Used in trans where regions are erased. pub fn subst_tps(cx: ctxt, tps: &[t], self_ty_opt: Option<t>, typ: t) -> t { if tps.len() == 0u && self_ty_opt.is_none() { return typ; } let tb = ty::get(typ); if self_ty_opt.is_none() && !tbox_has_flag(tb, has_params) { return typ; } match tb.sty { ty_param(p) => tps[p.idx], ty_self(_) => { match self_ty_opt { None => cx.sess.bug("ty_self unexpected here"), Some(self_ty) => { subst_tps(cx, tps, self_ty_opt, self_ty) } } } ref sty => { fold_sty_to_ty(cx, sty, |t| subst_tps(cx, tps, self_ty_opt, t)) } } } pub fn substs_is_noop(substs: &substs) -> bool { let regions_is_noop = match substs.regions { ErasedRegions => false, // may be used to canonicalize NonerasedRegions(ref regions) => regions.is_empty() }; substs.tps.len() == 0u && regions_is_noop && substs.self_ty.is_none() } pub fn substs_to_str(cx: ctxt, substs: &substs) -> ~str { substs.repr(cx) } pub fn subst(cx: ctxt, substs: &substs, typ: t) -> t { typ.subst(cx, substs) } // Type utilities pub fn type_is_voidish(tcx: ctxt, ty: t) -> bool { //! "nil" and "bot" are void types in that they represent 0 bits of information type_is_nil(ty) || type_is_bot(ty) || type_is_empty(tcx, ty) } pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil } pub fn type_is_bot(ty: t) -> bool { (get(ty).flags & (has_ty_bot as uint)) != 0 } pub fn type_is_error(ty: t) -> bool { (get(ty).flags & (has_ty_err as uint)) != 0 } pub fn type_needs_subst(ty: t) -> bool { tbox_has_flag(get(ty), needs_subst) } pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool { tref.substs.self_ty.iter().any(|&t| type_is_error(t)) || tref.substs.tps.iter().any(|&t| type_is_error(t)) } pub fn type_is_ty_var(ty: t) -> bool { match get(ty).sty { ty_infer(TyVar(_)) => true, _ => false } } pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool } pub fn type_is_self(ty: t) -> bool { match get(ty).sty { ty_self(*) => true, _ => false } } pub fn type_is_structural(ty: t) -> bool { match get(ty).sty { ty_struct(*) | ty_tup(_) | ty_enum(*) | ty_closure(_) | ty_trait(*) | ty_evec(_, vstore_fixed(_)) | ty_estr(vstore_fixed(_)) | ty_evec(_, vstore_slice(_)) | ty_estr(vstore_slice(_)) => true, _ => false } } pub fn type_is_sequence(ty: t) -> bool { match get(ty).sty { ty_estr(_) | ty_evec(_, _) => true, _ => false } } pub fn type_is_simd(cx: ctxt, ty: t) -> bool { match get(ty).sty { ty_struct(did, _) => lookup_simd(cx, did), _ => false } } pub fn type_is_str(ty: t) -> bool { match get(ty).sty { ty_estr(_) => true, _ => false } } pub fn sequence_element_type(cx: ctxt, ty: t) -> t { match get(ty).sty { ty_estr(_) => return mk_mach_uint(ast::ty_u8), ty_evec(mt, _) | ty_unboxed_vec(mt) => return mt.ty, _ => cx.sess.bug("sequence_element_type called on non-sequence value"), } } pub fn simd_type(cx: ctxt, ty: t) -> t { match get(ty).sty { ty_struct(did, ref substs) => { let fields = lookup_struct_fields(cx, did); lookup_field_type(cx, did, fields[0].id, substs) } _ => fail2!("simd_type called on invalid type") } } pub fn simd_size(cx: ctxt, ty: t) -> uint { match get(ty).sty { ty_struct(did, _) => { let fields = lookup_struct_fields(cx, did); fields.len() } _ => fail2!("simd_size called on invalid type") } } pub fn get_element_type(ty: t, i: uint) -> t { match get(ty).sty { ty_tup(ref ts) => return ts[i], _ => fail2!("get_element_type called on invalid type") } } pub fn type_is_box(ty: t) -> bool { match get(ty).sty { ty_box(_) => return true, _ => return false } } pub fn type_is_boxed(ty: t) -> bool { match get(ty).sty { ty_box(_) | ty_opaque_box | ty_evec(_, vstore_box) | ty_estr(vstore_box) => true, _ => false } } pub fn type_is_region_ptr(ty: t) -> bool { match get(ty).sty { ty_rptr(_, _) => true, _ => false } } pub fn type_is_slice(ty: t) -> bool { match get(ty).sty { ty_evec(_, vstore_slice(_)) | ty_estr(vstore_slice(_)) => true, _ => return false } } pub fn type_is_unique_box(ty: t) -> bool { match get(ty).sty { ty_uniq(_) => return true, _ => return false } } pub fn type_is_unsafe_ptr(ty: t) -> bool { match get(ty).sty { ty_ptr(_) => return true, _ => return false } } pub fn type_is_vec(ty: t) -> bool { return match get(ty).sty { ty_evec(_, _) | ty_unboxed_vec(_) => true, ty_estr(_) => true, _ => false }; } pub fn type_is_unique(ty: t) -> bool { match get(ty).sty { ty_uniq(_) | ty_evec(_, vstore_uniq) | ty_estr(vstore_uniq) | ty_opaque_closure_ptr(ast::OwnedSigil) => true, _ => return false } } /* A scalar type is one that denotes an atomic datum, with no sub-components. (A ty_ptr is scalar because it represents a non-managed pointer, so its contents are abstract to rustc.) */ pub fn type_is_scalar(ty: t) -> bool { match get(ty).sty { ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) | ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) | ty_type | ty_bare_fn(*) | ty_ptr(_) => true, _ => false } } pub fn type_needs_drop(cx: ctxt, ty: t) -> bool { type_contents(cx, ty).needs_drop(cx) } // Some things don't need cleanups during unwinding because the // task can free them all at once later. Currently only things // that only contain scalars and shared boxes can avoid unwind // cleanups. pub fn type_needs_unwind_cleanup(cx: ctxt, ty: t) -> bool { match cx.needs_unwind_cleanup_cache.find(&ty) { Some(&result) => return result, None => () } let mut tycache = HashSet::new(); let needs_unwind_cleanup = type_needs_unwind_cleanup_(cx, ty, &mut tycache, false); cx.needs_unwind_cleanup_cache.insert(ty, needs_unwind_cleanup); return needs_unwind_cleanup; } fn type_needs_unwind_cleanup_(cx: ctxt, ty: t, tycache: &mut HashSet<t>, encountered_box: bool) -> bool { // Prevent infinite recursion if !tycache.insert(ty) { return false; } let mut encountered_box = encountered_box; let mut needs_unwind_cleanup = false; do maybe_walk_ty(ty) |ty| { let old_encountered_box = encountered_box; let result = match get(ty).sty { ty_box(_) | ty_opaque_box => { encountered_box = true; true } ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) | ty_tup(_) | ty_ptr(_) => { true } ty_enum(did, ref substs) => { for v in (*enum_variants(cx, did)).iter() { for aty in v.args.iter() { let t = subst(cx, substs, *aty); needs_unwind_cleanup |= type_needs_unwind_cleanup_(cx, t, tycache, encountered_box); } } !needs_unwind_cleanup } ty_uniq(_) | ty_estr(vstore_uniq) | ty_estr(vstore_box) | ty_evec(_, vstore_uniq) | ty_evec(_, vstore_box) => { // Once we're inside a box, the annihilator will find // it and destroy it. if !encountered_box { needs_unwind_cleanup = true; false } else { true } } _ => { needs_unwind_cleanup = true; false } }; encountered_box = old_encountered_box; result } return needs_unwind_cleanup; } /** * Type contents is how the type checker reasons about kinds. * They track what kinds of things are found within a type. You can * think of them as kind of an "anti-kind". They track the kinds of values * and thinks that are contained in types. Having a larger contents for * a type tends to rule that type *out* from various kinds. For example, * a type that contains a borrowed pointer is not sendable. * * The reason we compute type contents and not kinds is that it is * easier for me (nmatsakis) to think about what is contained within * a type than to think about what is *not* contained within a type. */ pub struct TypeContents { bits: u32 } impl TypeContents { pub fn meets_bounds(&self, cx: ctxt, bbs: BuiltinBounds) -> bool { bbs.iter().all(|bb| self.meets_bound(cx, bb)) } pub fn meets_bound(&self, cx: ctxt, bb: BuiltinBound) -> bool { match bb { BoundStatic => self.is_static(cx), BoundFreeze => self.is_freezable(cx), BoundSend => self.is_sendable(cx), BoundSized => self.is_sized(cx), } } pub fn intersects(&self, tc: TypeContents) -> bool { (self.bits & tc.bits) != 0 } pub fn noncopyable(_cx: ctxt) -> TypeContents { TC_DTOR + TC_BORROWED_MUT + TC_ONCE_CLOSURE + TC_NONCOPY_TRAIT + TC_EMPTY_ENUM } pub fn is_static(&self, cx: ctxt) -> bool { !self.intersects(TypeContents::nonstatic(cx)) } pub fn nonstatic(_cx: ctxt) -> TypeContents { TC_BORROWED_POINTER } pub fn is_sendable(&self, cx: ctxt) -> bool { !self.intersects(TypeContents::nonsendable(cx)) } pub fn nonsendable(_cx: ctxt) -> TypeContents { TC_MANAGED + TC_BORROWED_POINTER + TC_NON_SENDABLE } pub fn contains_managed(&self) -> bool { self.intersects(TC_MANAGED) } pub fn is_freezable(&self, cx: ctxt) -> bool { !self.intersects(TypeContents::nonfreezable(cx)) } pub fn nonfreezable(_cx: ctxt) -> TypeContents { TC_MUTABLE } pub fn is_sized(&self, cx: ctxt) -> bool { !self.intersects(TypeContents::dynamically_sized(cx)) } pub fn dynamically_sized(_cx: ctxt) -> TypeContents { TC_DYNAMIC_SIZE } pub fn moves_by_default(&self, cx: ctxt) -> bool { self.intersects(TypeContents::nonimplicitly_copyable(cx)) } pub fn nonimplicitly_copyable(cx: ctxt) -> TypeContents { TypeContents::noncopyable(cx) + TC_OWNED_POINTER + TC_OWNED_VEC } pub fn needs_drop(&self, cx: ctxt) -> bool { if self.intersects(TC_NONCOPY_TRAIT) { // Currently all noncopyable existentials are 2nd-class types // behind owned pointers. With dynamically-sized types, remove // this assertion. assert!(self.intersects(TC_OWNED_POINTER) || // (...or stack closures without a copy bound.) self.intersects(TC_BORROWED_POINTER)); } let tc = TC_MANAGED + TC_DTOR + TypeContents::sendable(cx); self.intersects(tc) } pub fn sendable(_cx: ctxt) -> TypeContents { //! Any kind of sendable contents. TC_OWNED_POINTER + TC_OWNED_VEC } } impl ops::Add<TypeContents,TypeContents> for TypeContents { fn add(&self, other: &TypeContents) -> TypeContents { TypeContents {bits: self.bits | other.bits} } } impl ops::Sub<TypeContents,TypeContents> for TypeContents { fn sub(&self, other: &TypeContents) -> TypeContents { TypeContents {bits: self.bits & !other.bits} } } impl ToStr for TypeContents { fn to_str(&self) -> ~str { format!("TypeContents({})", self.bits.to_str_radix(2)) } } /// Constant for a type containing nothing of interest. static TC_NONE: TypeContents = TypeContents{bits: 0b0000_0000_0000}; /// Contains a borrowed value with a lifetime other than static static TC_BORROWED_POINTER: TypeContents = TypeContents{bits: 0b0000_0000_0001}; /// Contains an owned pointer (~T) but not slice of some kind static TC_OWNED_POINTER: TypeContents = TypeContents{bits: 0b0000_0000_0010}; /// Contains an owned vector ~[] or owned string ~str static TC_OWNED_VEC: TypeContents = TypeContents{bits: 0b0000_0000_0100}; /// Contains a non-copyable ~fn() or a ~Trait (NOT a ~fn:Copy() or ~Trait:Copy). static TC_NONCOPY_TRAIT: TypeContents = TypeContents{bits: 0b0000_0000_1000}; /// Type with a destructor static TC_DTOR: TypeContents = TypeContents{bits: 0b0000_0001_0000}; /// Contains a managed value static TC_MANAGED: TypeContents = TypeContents{bits: 0b0000_0010_0000}; /// &mut with any region static TC_BORROWED_MUT: TypeContents = TypeContents{bits: 0b0000_0100_0000}; /// Mutable content, whether owned or by ref static TC_MUTABLE: TypeContents = TypeContents{bits: 0b0000_1000_0000}; /// One-shot closure static TC_ONCE_CLOSURE: TypeContents = TypeContents{bits: 0b0001_0000_0000}; /// An enum with no variants. static TC_EMPTY_ENUM: TypeContents = TypeContents{bits: 0b0010_0000_0000}; /// Contains a type marked with `#[no_send]` static TC_NON_SENDABLE: TypeContents = TypeContents{bits: 0b0100_0000_0000}; /// Is a bare vector, str, function, trait, etc (only relevant at top level). static TC_DYNAMIC_SIZE: TypeContents = TypeContents{bits: 0b1000_0000_0000}; /// All possible contents. static TC_ALL: TypeContents = TypeContents{bits: 0b1111_1111_1111}; pub fn type_is_static(cx: ctxt, t: ty::t) -> bool { type_contents(cx, t).is_static(cx) } pub fn type_is_sendable(cx: ctxt, t: ty::t) -> bool { type_contents(cx, t).is_sendable(cx) } pub fn type_is_freezable(cx: ctxt, t: ty::t) -> bool { type_contents(cx, t).is_freezable(cx) } pub fn type_contents(cx: ctxt, ty: t) -> TypeContents { let ty_id = type_id(ty); match cx.tc_cache.find(&ty_id) { Some(tc) => { return *tc; } None => {} } let mut cache = HashMap::new(); let result = tc_ty(cx, ty, &mut cache); cx.tc_cache.insert(ty_id, result); return result; fn tc_ty(cx: ctxt, ty: t, cache: &mut HashMap<uint, TypeContents>) -> TypeContents { // Subtle: Note that we are *not* using cx.tc_cache here but rather a // private cache for this walk. This is needed in the case of cyclic // types like: // // struct List { next: ~Option<List>, ... } // // When computing the type contents of such a type, we wind up deeply // recursing as we go. So when we encounter the recursive reference // to List, we temporarily use TC_NONE as its contents. Later we'll // patch up the cache with the correct value, once we've computed it // (this is basically a co-inductive process, if that helps). So in // the end we'll compute TC_OWNED_POINTER, in this case. // // The problem is, as we are doing the computation, we will also // compute an *intermediate* contents for, e.g., Option<List> of // TC_NONE. This is ok during the computation of List itself, but if // we stored this intermediate value into cx.tc_cache, then later // requests for the contents of Option<List> would also yield TC_NONE // which is incorrect. This value was computed based on the crutch // value for the type contents of list. The correct value is // TC_OWNED_POINTER. This manifested as issue #4821. let ty_id = type_id(ty); match cache.find(&ty_id) { Some(tc) => { return *tc; } None => {} } match cx.tc_cache.find(&ty_id) { // Must check both caches! Some(tc) => { return *tc; } None => {} } cache.insert(ty_id, TC_NONE); let _i = indenter(); let result = match get(ty).sty { // Scalar and unique types are sendable, freezable, and durable ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) | ty_bare_fn(_) | ty_ptr(_) => { TC_NONE } ty_estr(vstore_uniq) => { TC_OWNED_VEC } ty_closure(ref c) => { closure_contents(c) } ty_box(mt) => { TC_MANAGED + statically_sized(nonsendable(tc_mt(cx, mt, cache))) } ty_trait(_, _, store, mutbl, bounds) => { trait_contents(store, mutbl, bounds) } ty_rptr(r, mt) => { borrowed_contents(r, mt.mutbl) + statically_sized(nonsendable(tc_mt(cx, mt, cache))) } ty_uniq(mt) => { TC_OWNED_POINTER + statically_sized(tc_mt(cx, mt, cache)) } ty_evec(mt, vstore_uniq) => { TC_OWNED_VEC + statically_sized(tc_mt(cx, mt, cache)) } ty_evec(mt, vstore_box) => { TC_MANAGED + statically_sized(nonsendable(tc_mt(cx, mt, cache))) } ty_evec(mt, vstore_slice(r)) => { borrowed_contents(r, mt.mutbl) + statically_sized(nonsendable(tc_mt(cx, mt, cache))) } ty_evec(mt, vstore_fixed(_)) => { let contents = tc_mt(cx, mt, cache); // FIXME(#6308) Uncomment this when construction of such // vectors is prevented earlier in compilation. // if !contents.is_sized(cx) { // cx.sess.bug("Fixed-length vector of unsized type \ // should be impossible"); // } contents } ty_estr(vstore_box) => { TC_MANAGED } ty_estr(vstore_slice(r)) => { borrowed_contents(r, MutImmutable) } ty_estr(vstore_fixed(_)) => { TC_NONE } ty_struct(did, ref substs) => { let flds = struct_fields(cx, did, substs); let mut res = flds.iter().fold( TC_NONE, |tc, f| tc + tc_mt(cx, f.mt, cache)); if ty::has_dtor(cx, did) { res = res + TC_DTOR; } apply_tc_attr(cx, did, res) } ty_tup(ref tys) => { tys.iter().fold(TC_NONE, |tc, ty| tc + tc_ty(cx, *ty, cache)) } ty_enum(did, ref substs) => { let variants = substd_enum_variants(cx, did, substs); let res = if variants.is_empty() { // we somewhat arbitrary declare that empty enums // are non-copyable TC_EMPTY_ENUM } else { variants.iter().fold(TC_NONE, |tc, variant| { variant.args.iter().fold(tc, |tc, arg_ty| tc + tc_ty(cx, *arg_ty, cache)) }) }; apply_tc_attr(cx, did, res) } ty_param(p) => { // We only ever ask for the kind of types that are defined in // the current crate; therefore, the only type parameters that // could be in scope are those defined in the current crate. // If this assertion failures, it is likely because of a // failure in the cross-crate inlining code to translate a // def-id. assert_eq!(p.def_id.crate, ast::LOCAL_CRATE); let tp_def = cx.ty_param_defs.get(&p.def_id.node); kind_bounds_to_contents(cx, &tp_def.bounds.builtin_bounds, tp_def.bounds.trait_bounds) } ty_self(def_id) => { // FIXME(#4678)---self should just be a ty param // Self may be bounded if the associated trait has builtin kinds // for supertraits. If so we can use those bounds. let trait_def = lookup_trait_def(cx, def_id); let traits = [trait_def.trait_ref]; kind_bounds_to_contents(cx, &trait_def.bounds, traits) } ty_infer(_) => { // This occurs during coherence, but shouldn't occur at other // times. TC_ALL } ty_opaque_box => TC_MANAGED, ty_unboxed_vec(mt) => TC_DYNAMIC_SIZE + tc_mt(cx, mt, cache), ty_opaque_closure_ptr(sigil) => { match sigil { ast::BorrowedSigil => TC_BORROWED_POINTER, ast::ManagedSigil => TC_MANAGED, // FIXME(#3569): Looks like noncopyability should depend // on the bounds, but I don't think this case ever comes up. ast::OwnedSigil => TC_NONCOPY_TRAIT + TC_OWNED_POINTER, } } ty_type => TC_NONE, ty_err => { cx.sess.bug("Asked to compute contents of fictitious type"); } }; cache.insert(ty_id, result); return result; } fn tc_mt(cx: ctxt, mt: mt, cache: &mut HashMap<uint, TypeContents>) -> TypeContents { let mc = if mt.mutbl == MutMutable {TC_MUTABLE} else {TC_NONE}; mc + tc_ty(cx, mt.ty, cache) } fn apply_tc_attr(cx: ctxt, did: DefId, mut tc: TypeContents) -> TypeContents { if has_attr(cx, did, "no_freeze") { tc = tc + TC_MUTABLE; } if has_attr(cx, did, "no_send") { tc = tc + TC_NON_SENDABLE; } tc } fn borrowed_contents(region: ty::Region, mutbl: ast::Mutability) -> TypeContents { let mc = if mutbl == MutMutable { TC_MUTABLE + TC_BORROWED_MUT } else { TC_NONE }; let rc = if region != ty::re_static { TC_BORROWED_POINTER } else { TC_NONE }; mc + rc } fn nonsendable(pointee: TypeContents) -> TypeContents { /*! * * Given a non-owning pointer to some type `T` with * contents `pointee` (like `@T` or * `&T`), returns the relevant bits that * apply to the owner of the pointer. */ let mask = TC_MUTABLE.bits | TC_BORROWED_POINTER.bits; TypeContents {bits: pointee.bits & mask} } fn statically_sized(pointee: TypeContents) -> TypeContents { /*! * If a dynamically-sized type is found behind a pointer, we should * restore the 'Sized' kind to the pointer and things that contain it. */ TypeContents {bits: pointee.bits & !TC_DYNAMIC_SIZE.bits} } fn closure_contents(cty: &ClosureTy) -> TypeContents { // Closure contents are just like trait contents, but with potentially // even more stuff. let st = match cty.sigil { ast::BorrowedSigil => trait_contents(RegionTraitStore(cty.region), MutImmutable, cty.bounds) + TC_BORROWED_POINTER, // might be an env packet even if static ast::ManagedSigil => trait_contents(BoxTraitStore, MutImmutable, cty.bounds), ast::OwnedSigil => trait_contents(UniqTraitStore, MutImmutable, cty.bounds), }; // FIXME(#3569): This borrowed_contents call should be taken care of in // trait_contents, after ~Traits and @Traits can have region bounds too. // This one here is redundant for &fns but important for ~fns and @fns. let rt = borrowed_contents(cty.region, MutImmutable); // This also prohibits "@once fn" from being copied, which allows it to // be called. Neither way really makes much sense. let ot = match cty.onceness { ast::Once => TC_ONCE_CLOSURE, ast::Many => TC_NONE }; // Prevent noncopyable types captured in the environment from being copied. st + rt + ot + TC_NONCOPY_TRAIT } fn trait_contents(store: TraitStore, mutbl: ast::Mutability, bounds: BuiltinBounds) -> TypeContents { let st = match store { UniqTraitStore => TC_OWNED_POINTER, BoxTraitStore => TC_MANAGED, RegionTraitStore(r) => borrowed_contents(r, mutbl), }; let mt = match mutbl { ast::MutMutable => TC_MUTABLE, _ => TC_NONE }; // We get additional "special type contents" for each bound that *isn't* // on the trait. So iterate over the inverse of the bounds that are set. // This is like with typarams below, but less "pessimistic" and also // dependent on the trait store. let mut bt = TC_NONE; for bound in (AllBuiltinBounds() - bounds).iter() { bt = bt + match bound { BoundStatic if bounds.contains_elem(BoundSend) => TC_NONE, // Send bound implies static bound. BoundStatic => TC_BORROWED_POINTER, // Useful for "@Trait:'static" BoundSend => TC_NON_SENDABLE, BoundFreeze => TC_MUTABLE, BoundSized => TC_NONE, // don't care if interior is sized }; } st + mt + bt } fn kind_bounds_to_contents(cx: ctxt, bounds: &BuiltinBounds, traits: &[@TraitRef]) -> TypeContents { let _i = indenter(); let mut tc = TC_ALL; do each_inherited_builtin_bound(cx, bounds, traits) |bound| { debug2!("tc = {}, bound = {:?}", tc.to_str(), bound); tc = tc - match bound { BoundStatic => TypeContents::nonstatic(cx), BoundSend => TypeContents::nonsendable(cx), BoundFreeze => TypeContents::nonfreezable(cx), // The dynamic-size bit can be removed at pointer-level, etc. BoundSized => TypeContents::dynamically_sized(cx), }; } debug2!("result = {}", tc.to_str()); return tc; // Iterates over all builtin bounds on the type parameter def, including // those inherited from traits with builtin-kind-supertraits. fn each_inherited_builtin_bound(cx: ctxt, bounds: &BuiltinBounds, traits: &[@TraitRef], f: &fn(BuiltinBound)) { for bound in bounds.iter() { f(bound); } do each_bound_trait_and_supertraits(cx, traits) |trait_ref| { let trait_def = lookup_trait_def(cx, trait_ref.def_id); for bound in trait_def.bounds.iter() { f(bound); } true }; } } } pub fn type_moves_by_default(cx: ctxt, ty: t) -> bool { type_contents(cx, ty).moves_by_default(cx) } // True if instantiating an instance of `r_ty` requires an instance of `r_ty`. pub fn is_instantiable(cx: ctxt, r_ty: t) -> bool { fn type_requires(cx: ctxt, seen: &mut ~[DefId], r_ty: t, ty: t) -> bool { debug2!("type_requires({}, {})?", ::util::ppaux::ty_to_str(cx, r_ty), ::util::ppaux::ty_to_str(cx, ty)); let r = { get(r_ty).sty == get(ty).sty || subtypes_require(cx, seen, r_ty, ty) }; debug2!("type_requires({}, {})? {}", ::util::ppaux::ty_to_str(cx, r_ty), ::util::ppaux::ty_to_str(cx, ty), r); return r; } fn subtypes_require(cx: ctxt, seen: &mut ~[DefId], r_ty: t, ty: t) -> bool { debug2!("subtypes_require({}, {})?", ::util::ppaux::ty_to_str(cx, r_ty), ::util::ppaux::ty_to_str(cx, ty)); let r = match get(ty).sty { ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) | ty_estr(_) | ty_bare_fn(_) | ty_closure(_) | ty_infer(_) | ty_err | ty_param(_) | ty_self(_) | ty_type | ty_opaque_box | ty_opaque_closure_ptr(_) | ty_evec(_, _) | ty_unboxed_vec(_) => { false } ty_box(ref mt) | ty_uniq(ref mt) | ty_rptr(_, ref mt) => { type_requires(cx, seen, r_ty, mt.ty) } ty_ptr(*) => { false // unsafe ptrs can always be NULL } ty_trait(_, _, _, _, _) => { false } ty_struct(ref did, _) if seen.contains(did) => { false } ty_struct(did, ref substs) => { seen.push(did); let fields = struct_fields(cx, did, substs); let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty)); seen.pop(); r } ty_tup(ref ts) => { ts.iter().any(|t| type_requires(cx, seen, r_ty, *t)) } ty_enum(ref did, _) if seen.contains(did) => { false } ty_enum(did, ref substs) => { seen.push(did); let vs = enum_variants(cx, did); let r = !vs.is_empty() && do vs.iter().all |variant| { do variant.args.iter().any |aty| { let sty = subst(cx, substs, *aty); type_requires(cx, seen, r_ty, sty) } }; seen.pop(); r } }; debug2!("subtypes_require({}, {})? {}", ::util::ppaux::ty_to_str(cx, r_ty), ::util::ppaux::ty_to_str(cx, ty), r); return r; } let mut seen = ~[]; !subtypes_require(cx, &mut seen, r_ty, r_ty) } pub fn type_structurally_contains(cx: ctxt, ty: t, test: &fn(x: &sty) -> bool) -> bool { let sty = &get(ty).sty; debug2!("type_structurally_contains: {}", ::util::ppaux::ty_to_str(cx, ty)); if test(sty) { return true; } match *sty { ty_enum(did, ref substs) => { for variant in (*enum_variants(cx, did)).iter() { for aty in variant.args.iter() { let sty = subst(cx, substs, *aty); if type_structurally_contains(cx, sty, |x| test(x)) { return true; } } } return false; } ty_struct(did, ref substs) => { let r = lookup_struct_fields(cx, did); for field in r.iter() { let ft = lookup_field_type(cx, did, field.id, substs); if type_structurally_contains(cx, ft, |x| test(x)) { return true; } } return false; } ty_tup(ref ts) => { for tt in ts.iter() { if type_structurally_contains(cx, *tt, |x| test(x)) { return true; } } return false; } ty_evec(ref mt, vstore_fixed(_)) => { return type_structurally_contains(cx, mt.ty, test); } _ => return false } } pub fn type_structurally_contains_uniques(cx: ctxt, ty: t) -> bool { return type_structurally_contains(cx, ty, |sty| { match *sty { ty_uniq(_) | ty_evec(_, vstore_uniq) | ty_estr(vstore_uniq) => true, _ => false, } }); } pub fn type_is_trait(ty: t) -> bool { match get(ty).sty { ty_trait(*) => true, _ => false } } pub fn type_is_integral(ty: t) -> bool { match get(ty).sty { ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true, _ => false } } pub fn type_is_char(ty: t) -> bool { match get(ty).sty { ty_char => true, _ => false } } pub fn type_is_fp(ty: t) -> bool { match get(ty).sty { ty_infer(FloatVar(_)) | ty_float(_) => true, _ => false } } pub fn type_is_numeric(ty: t) -> bool { return type_is_integral(ty) || type_is_fp(ty); } pub fn type_is_signed(ty: t) -> bool { match get(ty).sty { ty_int(_) => true, _ => false } } pub fn type_is_machine(ty: t) -> bool { match get(ty).sty { ty_int(ast::ty_i) | ty_uint(ast::ty_u) => false, ty_int(*) | ty_uint(*) | ty_float(*) => true, _ => false } } // Whether a type is Plain Old Data -- meaning it does not contain pointers // that the cycle collector might care about. pub fn type_is_pod(cx: ctxt, ty: t) -> bool { let mut result = true; match get(ty).sty { // Scalar types ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) | ty_type | ty_ptr(_) | ty_bare_fn(_) => result = true, // Boxed types ty_box(_) | ty_uniq(_) | ty_closure(_) | ty_estr(vstore_uniq) | ty_estr(vstore_box) | ty_evec(_, vstore_uniq) | ty_evec(_, vstore_box) | ty_trait(_, _, _, _, _) | ty_rptr(_,_) | ty_opaque_box => result = false, // Structural types ty_enum(did, ref substs) => { let variants = enum_variants(cx, did); for variant in (*variants).iter() { // XXX(pcwalton): This is an inefficient way to do this. Don't // synthesize a tuple! // // Perform any type parameter substitutions. let tup_ty = mk_tup(cx, variant.args.clone()); let tup_ty = subst(cx, substs, tup_ty); if !type_is_pod(cx, tup_ty) { result = false; } } } ty_tup(ref elts) => { for elt in elts.iter() { if !type_is_pod(cx, *elt) { result = false; } } } ty_estr(vstore_fixed(_)) => result = true, ty_evec(ref mt, vstore_fixed(_)) | ty_unboxed_vec(ref mt) => { result = type_is_pod(cx, mt.ty); } ty_param(_) => result = false, ty_opaque_closure_ptr(_) => result = true, ty_struct(did, ref substs) => { let fields = lookup_struct_fields(cx, did); result = do fields.iter().all |f| { let fty = ty::lookup_item_type(cx, f.id); let sty = subst(cx, substs, fty.ty); type_is_pod(cx, sty) }; } ty_estr(vstore_slice(*)) | ty_evec(_, vstore_slice(*)) => { result = false; } ty_infer(*) | ty_self(*) | ty_err => { cx.sess.bug("non concrete type in type_is_pod"); } } return result; } pub fn type_is_enum(ty: t) -> bool { match get(ty).sty { ty_enum(_, _) => return true, _ => return false } } // Is the type's representation size known at compile time? pub fn type_is_sized(cx: ctxt, ty: ty::t) -> bool { match get(ty).sty { // FIXME(#6308) add trait, vec, str, etc here. ty_param(p) => { let param_def = cx.ty_param_defs.get(&p.def_id.node); if param_def.bounds.builtin_bounds.contains_elem(BoundSized) { return true; } return false; }, _ => return true, } } // Whether a type is enum like, that is a enum type with only nullary // constructors pub fn type_is_c_like_enum(cx: ctxt, ty: t) -> bool { match get(ty).sty { ty_enum(did, _) => { let variants = enum_variants(cx, did); if variants.len() == 0 { false } else { variants.iter().all(|v| v.args.len() == 0) } } _ => false } } pub fn type_param(ty: t) -> Option<uint> { match get(ty).sty { ty_param(p) => return Some(p.idx), _ => {/* fall through */ } } return None; } // Returns the type and mutability of *t. // // The parameter `explicit` indicates if this is an *explicit* dereference. // Some types---notably unsafe ptrs---can only be dereferenced explicitly. pub fn deref(cx: ctxt, t: t, explicit: bool) -> Option<mt> { deref_sty(cx, &get(t).sty, explicit) } pub fn deref_sty(cx: ctxt, sty: &sty, explicit: bool) -> Option<mt> { match *sty { ty_rptr(_, mt) | ty_box(mt) | ty_uniq(mt) => { Some(mt) } ty_ptr(mt) if explicit => { Some(mt) } ty_enum(did, ref substs) => { let variants = enum_variants(cx, did); if (*variants).len() == 1u && variants[0].args.len() == 1u { let v_t = subst(cx, substs, variants[0].args[0]); Some(mt {ty: v_t, mutbl: ast::MutImmutable}) } else { None } } ty_struct(did, ref substs) => { let fields = struct_fields(cx, did, substs); if fields.len() == 1 && fields[0].ident == syntax::parse::token::special_idents::unnamed_field { Some(mt {ty: fields[0].mt.ty, mutbl: ast::MutImmutable}) } else { None } } _ => None } } pub fn type_autoderef(cx: ctxt, t: t) -> t { let mut t = t; loop { match deref(cx, t, false) { None => return t, Some(mt) => t = mt.ty } } } // Returns the type and mutability of t[i] pub fn index(t: t) -> Option<mt> { index_sty(&get(t).sty) } pub fn index_sty(sty: &sty) -> Option<mt> { match *sty { ty_evec(mt, _) => Some(mt), ty_estr(_) => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}), _ => None } } /** * Enforces an arbitrary but consistent total ordering over * free regions. This is needed for establishing a consistent * LUB in region_inference. */ impl cmp::TotalOrd for FreeRegion { fn cmp(&self, other: &FreeRegion) -> Ordering { cmp::cmp2(&self.scope_id, &self.bound_region, &other.scope_id, &other.bound_region) } } impl cmp::TotalEq for FreeRegion { fn equals(&self, other: &FreeRegion) -> bool { *self == *other } } /** * Enforces an arbitrary but consistent total ordering over * bound regions. This is needed for establishing a consistent * LUB in region_inference. */ impl cmp::TotalOrd for bound_region { fn cmp(&self, other: &bound_region) -> Ordering { match (self, other) { (&ty::br_self, &ty::br_self) => cmp::Equal, (&ty::br_self, _) => cmp::Less, (&ty::br_anon(ref a1), &ty::br_anon(ref a2)) => a1.cmp(a2), (&ty::br_anon(*), _) => cmp::Less, (&ty::br_named(ref a1), &ty::br_named(ref a2)) => a1.name.cmp(&a2.name), (&ty::br_named(*), _) => cmp::Less, (&ty::br_cap_avoid(ref a1, @ref b1), &ty::br_cap_avoid(ref a2, @ref b2)) => cmp::cmp2(a1, b1, a2, b2), (&ty::br_cap_avoid(*), _) => cmp::Less, (&ty::br_fresh(ref a1), &ty::br_fresh(ref a2)) => a1.cmp(a2), (&ty::br_fresh(*), _) => cmp::Less, } } } impl cmp::TotalEq for bound_region { fn equals(&self, other: &bound_region) -> bool { *self == *other } } pub fn node_id_to_trait_ref(cx: ctxt, id: ast::NodeId) -> @ty::TraitRef { match cx.trait_refs.find(&id) { Some(&t) => t, None => cx.sess.bug( format!("node_id_to_trait_ref: no trait ref for node `{}`", ast_map::node_id_to_str(cx.items, id, token::get_ident_interner()))) } } pub fn node_id_to_type(cx: ctxt, id: ast::NodeId) -> t { //printfln!("{:?}/{:?}", id, cx.node_types.len()); match cx.node_types.find(&(id as uint)) { Some(&t) => t, None => cx.sess.bug( format!("node_id_to_type: no type for node `{}`", ast_map::node_id_to_str(cx.items, id, token::get_ident_interner()))) } } // XXX(pcwalton): Makes a copy, bleh. Probably better to not do that. pub fn node_id_to_type_params(cx: ctxt, id: ast::NodeId) -> ~[t] { match cx.node_type_substs.find(&id) { None => return ~[], Some(ts) => return (*ts).clone(), } } fn node_id_has_type_params(cx: ctxt, id: ast::NodeId) -> bool { cx.node_type_substs.contains_key(&id) } pub fn ty_fn_sig(fty: t) -> FnSig { match get(fty).sty { ty_bare_fn(ref f) => f.sig.clone(), ty_closure(ref f) => f.sig.clone(), ref s => { fail2!("ty_fn_sig() called on non-fn type: {:?}", s) } } } // Type accessors for substructures of types pub fn ty_fn_args(fty: t) -> ~[t] { match get(fty).sty { ty_bare_fn(ref f) => f.sig.inputs.clone(), ty_closure(ref f) => f.sig.inputs.clone(), ref s => { fail2!("ty_fn_args() called on non-fn type: {:?}", s) } } } pub fn ty_closure_sigil(fty: t) -> Sigil { match get(fty).sty { ty_closure(ref f) => f.sigil, ref s => { fail2!("ty_closure_sigil() called on non-closure type: {:?}", s) } } } pub fn ty_fn_purity(fty: t) -> ast::purity { match get(fty).sty { ty_bare_fn(ref f) => f.purity, ty_closure(ref f) => f.purity, ref s => { fail2!("ty_fn_purity() called on non-fn type: {:?}", s) } } } pub fn ty_fn_ret(fty: t) -> t { match get(fty).sty { ty_bare_fn(ref f) => f.sig.output, ty_closure(ref f) => f.sig.output, ref s => { fail2!("ty_fn_ret() called on non-fn type: {:?}", s) } } } pub fn is_fn_ty(fty: t) -> bool { match get(fty).sty { ty_bare_fn(_) => true, ty_closure(_) => true, _ => false } } pub fn ty_vstore(ty: t) -> vstore { match get(ty).sty { ty_evec(_, vstore) => vstore, ty_estr(vstore) => vstore, ref s => fail2!("ty_vstore() called on invalid sty: {:?}", s) } } pub fn ty_region(tcx: ctxt, span: Span, ty: t) -> Region { match get(ty).sty { ty_rptr(r, _) => r, ty_evec(_, vstore_slice(r)) => r, ty_estr(vstore_slice(r)) => r, ref s => { tcx.sess.span_bug( span, format!("ty_region() invoked on in appropriate ty: {:?}", s)); } } } pub fn replace_fn_sig(cx: ctxt, fsty: &sty, new_sig: FnSig) -> t { match *fsty { ty_bare_fn(ref f) => mk_bare_fn(cx, BareFnTy {sig: new_sig, ..*f}), ty_closure(ref f) => mk_closure(cx, ClosureTy {sig: new_sig, ..*f}), ref s => { cx.sess.bug( format!("ty_fn_sig() called on non-fn type: {:?}", s)); } } } pub fn replace_closure_return_type(tcx: ctxt, fn_type: t, ret_type: t) -> t { /*! * * Returns a new function type based on `fn_type` but returning a value of * type `ret_type` instead. */ match ty::get(fn_type).sty { ty::ty_closure(ref fty) => { ty::mk_closure(tcx, ClosureTy { sig: FnSig {output: ret_type, ..fty.sig.clone()}, ..(*fty).clone() }) } _ => { tcx.sess.bug(format!( "replace_fn_ret() invoked with non-fn-type: {}", ty_to_str(tcx, fn_type))); } } } // Returns a vec of all the input and output types of fty. pub fn tys_in_fn_sig(sig: &FnSig) -> ~[t] { vec::append_one(sig.inputs.map(|a| *a), sig.output) } // Type accessors for AST nodes pub fn block_ty(cx: ctxt, b: &ast::Block) -> t { return node_id_to_type(cx, b.id); } // Returns the type of a pattern as a monotype. Like @expr_ty, this function // doesn't provide type parameter substitutions. pub fn pat_ty(cx: ctxt, pat: &ast::Pat) -> t { return node_id_to_type(cx, pat.id); } // Returns the type of an expression as a monotype. // // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in // some cases, we insert `AutoAdjustment` annotations such as auto-deref or // auto-ref. The type returned by this function does not consider such // adjustments. See `expr_ty_adjusted()` instead. // // NB (2): This type doesn't provide type parameter substitutions; e.g. if you // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int" // instead of "fn(t) -> T with T = int". If this isn't what you want, see // expr_ty_params_and_ty() below. pub fn expr_ty(cx: ctxt, expr: &ast::Expr) -> t { return node_id_to_type(cx, expr.id); } pub fn expr_ty_adjusted(cx: ctxt, expr: &ast::Expr) -> t { /*! * * Returns the type of `expr`, considering any `AutoAdjustment` * entry recorded for that expression. * * It would almost certainly be better to store the adjusted ty in with * the `AutoAdjustment`, but I opted not to do this because it would * require serializing and deserializing the type and, although that's not * hard to do, I just hate that code so much I didn't want to touch it * unless it was to fix it properly, which seemed a distraction from the * task at hand! -nmatsakis */ let unadjusted_ty = expr_ty(cx, expr); adjust_ty(cx, expr.span, unadjusted_ty, cx.adjustments.find_copy(&expr.id)) } pub fn adjust_ty(cx: ctxt, span: Span, unadjusted_ty: ty::t, adjustment: Option<@AutoAdjustment>) -> ty::t { /*! See `expr_ty_adjusted` */ return match adjustment { None => unadjusted_ty, Some(@AutoAddEnv(r, s)) => { match ty::get(unadjusted_ty).sty { ty::ty_bare_fn(ref b) => { ty::mk_closure( cx, ty::ClosureTy {purity: b.purity, sigil: s, onceness: ast::Many, region: r, bounds: ty::AllBuiltinBounds(), sig: b.sig.clone()}) } ref b => { cx.sess.bug( format!("add_env adjustment on non-bare-fn: {:?}", b)); } } } Some(@AutoDerefRef(ref adj)) => { let mut adjusted_ty = unadjusted_ty; if (!ty::type_is_error(adjusted_ty)) { for i in range(0, adj.autoderefs) { match ty::deref(cx, adjusted_ty, true) { Some(mt) => { adjusted_ty = mt.ty; } None => { cx.sess.span_bug( span, format!("The {}th autoderef failed: {}", i, ty_to_str(cx, adjusted_ty))); } } } } match adj.autoref { None => adjusted_ty, Some(ref autoref) => { match *autoref { AutoPtr(r, m) => { mk_rptr(cx, r, mt {ty: adjusted_ty, mutbl: m}) } AutoBorrowVec(r, m) => { borrow_vec(cx, span, r, m, adjusted_ty) } AutoBorrowVecRef(r, m) => { adjusted_ty = borrow_vec(cx, span, r, m, adjusted_ty); mk_rptr(cx, r, mt {ty: adjusted_ty, mutbl: ast::MutImmutable}) } AutoBorrowFn(r) => { borrow_fn(cx, span, r, adjusted_ty) } AutoUnsafe(m) => { mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m}) } AutoBorrowObj(r, m) => { borrow_obj(cx, span, r, m, adjusted_ty) } } } } } }; fn borrow_vec(cx: ctxt, span: Span, r: Region, m: ast::Mutability, ty: ty::t) -> ty::t { match get(ty).sty { ty_evec(mt, _) => { ty::mk_evec(cx, mt {ty: mt.ty, mutbl: m}, vstore_slice(r)) } ty_estr(_) => { ty::mk_estr(cx, vstore_slice(r)) } ref s => { cx.sess.span_bug( span, format!("borrow-vec associated with bad sty: {:?}", s)); } } } fn borrow_fn(cx: ctxt, span: Span, r: Region, ty: ty::t) -> ty::t { match get(ty).sty { ty_closure(ref fty) => { ty::mk_closure(cx, ClosureTy { sigil: BorrowedSigil, region: r, ..(*fty).clone() }) } ref s => { cx.sess.span_bug( span, format!("borrow-fn associated with bad sty: {:?}", s)); } } } fn borrow_obj(cx: ctxt, span: Span, r: Region, m: ast::Mutability, ty: ty::t) -> ty::t { match get(ty).sty { ty_trait(trt_did, ref trt_substs, _, _, b) => { ty::mk_trait(cx, trt_did, trt_substs.clone(), RegionTraitStore(r), m, b) } ref s => { cx.sess.span_bug( span, format!("borrow-trait-obj associated with bad sty: {:?}", s)); } } } } impl AutoRef { pub fn map_region(&self, f: &fn(Region) -> Region) -> AutoRef { match *self { ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m), ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m), ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m), ty::AutoBorrowFn(r) => ty::AutoBorrowFn(f(r)), ty::AutoUnsafe(m) => ty::AutoUnsafe(m), ty::AutoBorrowObj(r, m) => ty::AutoBorrowObj(f(r), m), } } } pub struct ParamsTy { params: ~[t], ty: t } pub fn expr_ty_params_and_ty(cx: ctxt, expr: &ast::Expr) -> ParamsTy { ParamsTy { params: node_id_to_type_params(cx, expr.id), ty: node_id_to_type(cx, expr.id) } } pub fn expr_has_ty_params(cx: ctxt, expr: &ast::Expr) -> bool { return node_id_has_type_params(cx, expr.id); } pub fn method_call_type_param_defs(tcx: ctxt, method_map: typeck::method_map, id: ast::NodeId) -> Option<@~[TypeParameterDef]> { do method_map.find(&id).map |method| { match method.origin { typeck::method_static(did) => { // n.b.: When we encode impl methods, the bounds // that we encode include both the impl bounds // and then the method bounds themselves... ty::lookup_item_type(tcx, did).generics.type_param_defs } typeck::method_param(typeck::method_param { trait_id: trt_id, method_num: n_mth, _}) | typeck::method_object(typeck::method_object { trait_id: trt_id, method_num: n_mth, _}) => { // ...trait methods bounds, in contrast, include only the // method bounds, so we must preprend the tps from the // trait itself. This ought to be harmonized. let trait_type_param_defs = lookup_trait_def(tcx, trt_id).generics.type_param_defs; @vec::append( (*trait_type_param_defs).clone(), *ty::trait_method(tcx, trt_id, n_mth).generics.type_param_defs) } } } } pub fn resolve_expr(tcx: ctxt, expr: &ast::Expr) -> ast::Def { match tcx.def_map.find(&expr.id) { Some(&def) => def, None => { tcx.sess.span_bug(expr.span, format!( "No def-map entry for expr {:?}", expr.id)); } } } pub fn expr_is_lval(tcx: ctxt, method_map: typeck::method_map, e: &ast::Expr) -> bool { match expr_kind(tcx, method_map, e) { LvalueExpr => true, RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false } } /// We categorize expressions into three kinds. The distinction between /// lvalue/rvalue is fundamental to the language. The distinction between the /// two kinds of rvalues is an artifact of trans which reflects how we will /// generate code for that kind of expression. See trans/expr.rs for more /// information. pub enum ExprKind { LvalueExpr, RvalueDpsExpr, RvalueDatumExpr, RvalueStmtExpr } pub fn expr_kind(tcx: ctxt, method_map: typeck::method_map, expr: &ast::Expr) -> ExprKind { if method_map.contains_key(&expr.id) { // Overloaded operations are generally calls, and hence they are // generated via DPS. However, assign_op (e.g., `x += y`) is an // exception, as its result is always unit. return match expr.node { ast::ExprAssignOp(*) => RvalueStmtExpr, _ => RvalueDpsExpr }; } match expr.node { ast::ExprPath(*) | ast::ExprSelf => { match resolve_expr(tcx, expr) { ast::DefVariant(*) | ast::DefStruct(*) => RvalueDpsExpr, // Fn pointers are just scalar values. ast::DefFn(*) | ast::DefStaticMethod(*) => RvalueDatumExpr, // Note: there is actually a good case to be made that // def_args, particularly those of immediate type, ought to // considered rvalues. ast::DefStatic(*) | ast::DefBinding(*) | ast::DefUpvar(*) | ast::DefArg(*) | ast::DefLocal(*) | ast::DefSelf(*) => LvalueExpr, def => { tcx.sess.span_bug(expr.span, format!( "Uncategorized def for expr {:?}: {:?}", expr.id, def)); } } } ast::ExprUnary(_, ast::UnDeref, _) | ast::ExprField(*) | ast::ExprIndex(*) => { LvalueExpr } ast::ExprCall(*) | ast::ExprMethodCall(*) | ast::ExprStruct(*) | ast::ExprTup(*) | ast::ExprIf(*) | ast::ExprMatch(*) | ast::ExprFnBlock(*) | ast::ExprDoBody(*) | ast::ExprBlock(*) | ast::ExprRepeat(*) | ast::ExprLit(@codemap::Spanned {node: lit_str(*), _}) | ast::ExprVstore(_, ast::ExprVstoreSlice) | ast::ExprVstore(_, ast::ExprVstoreMutSlice) | ast::ExprVec(*) => { RvalueDpsExpr } ast::ExprCast(*) => { match tcx.node_types.find(&(expr.id as uint)) { Some(&t) => { if type_is_trait(t) { RvalueDpsExpr } else { RvalueDatumExpr } } None => { // Technically, it should not happen that the expr is not // present within the table. However, it DOES happen // during type check, because the final types from the // expressions are not yet recorded in the tcx. At that // time, though, we are only interested in knowing lvalue // vs rvalue. It would be better to base this decision on // the AST type in cast node---but (at the time of this // writing) it's not easy to distinguish casts to traits // from other casts based on the AST. This should be // easier in the future, when casts to traits would like // like @Foo, ~Foo, or &Foo. RvalueDatumExpr } } } ast::ExprBreak(*) | ast::ExprAgain(*) | ast::ExprRet(*) | ast::ExprWhile(*) | ast::ExprLoop(*) | ast::ExprAssign(*) | ast::ExprInlineAsm(*) | ast::ExprAssignOp(*) => { RvalueStmtExpr } ast::ExprForLoop(*) => fail2!("non-desugared expr_for_loop"), ast::ExprLogLevel | ast::ExprLit(_) | // Note: lit_str is carved out above ast::ExprUnary(*) | ast::ExprAddrOf(*) | ast::ExprBinary(*) | ast::ExprVstore(_, ast::ExprVstoreBox) | ast::ExprVstore(_, ast::ExprVstoreMutBox) | ast::ExprVstore(_, ast::ExprVstoreUniq) => { RvalueDatumExpr } ast::ExprParen(e) => expr_kind(tcx, method_map, e), ast::ExprMac(*) => { tcx.sess.span_bug( expr.span, "macro expression remains after expansion"); } } } pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId { match s.node { ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => { return id; } ast::StmtMac(*) => fail2!("unexpanded macro in trans") } } pub fn field_idx(name: ast::Name, fields: &[field]) -> Option<uint> { let mut i = 0u; for f in fields.iter() { if f.ident.name == name { return Some(i); } i += 1u; } return None; } pub fn field_idx_strict(tcx: ty::ctxt, name: ast::Name, fields: &[field]) -> uint { let mut i = 0u; for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; } tcx.sess.bug(format!( "No field named `{}` found in the list of fields `{:?}`", token::interner_get(name), fields.map(|f| tcx.sess.str_of(f.ident)))); } pub fn method_idx(id: ast::Ident, meths: &[@Method]) -> Option<uint> { meths.iter().position(|m| m.ident == id) } /// Returns a vector containing the indices of all type parameters that appear /// in `ty`. The vector may contain duplicates. Probably should be converted /// to a bitset or some other representation. pub fn param_tys_in_type(ty: t) -> ~[param_ty] { let mut rslt = ~[]; do walk_ty(ty) |ty| { match get(ty).sty { ty_param(p) => { rslt.push(p); } _ => () } } rslt } pub fn occurs_check(tcx: ctxt, sp: Span, vid: TyVid, rt: t) { // Returns a vec of all the type variables occurring in `ty`. It may // contain duplicates. (Integral type vars aren't counted.) fn vars_in_type(ty: t) -> ~[TyVid] { let mut rslt = ~[]; do walk_ty(ty) |ty| { match get(ty).sty { ty_infer(TyVar(v)) => rslt.push(v), _ => () } } rslt } // Fast path if !type_needs_infer(rt) { return; } // Occurs check! if vars_in_type(rt).contains(&vid) { // Maybe this should be span_err -- however, there's an // assertion later on that the type doesn't contain // variables, so in this case we have to be sure to die. tcx.sess.span_fatal (sp, ~"type inference failed because I \ could not find a type\n that's both of the form " + ::util::ppaux::ty_to_str(tcx, mk_var(tcx, vid)) + " and of the form " + ::util::ppaux::ty_to_str(tcx, rt) + " - such a type would have to be infinitely large."); } } pub fn ty_sort_str(cx: ctxt, t: t) -> ~str { match get(t).sty { ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) | ty_estr(_) | ty_type | ty_opaque_box | ty_opaque_closure_ptr(_) => { ::util::ppaux::ty_to_str(cx, t) } ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)), ty_box(_) => ~"@-ptr", ty_uniq(_) => ~"~-ptr", ty_evec(_, _) => ~"vector", ty_unboxed_vec(_) => ~"unboxed vector", ty_ptr(_) => ~"*-ptr", ty_rptr(_, _) => ~"&-ptr", ty_bare_fn(_) => ~"extern fn", ty_closure(_) => ~"fn", ty_trait(id, _, _, _, _) => format!("trait {}", item_path_str(cx, id)), ty_struct(id, _) => format!("struct {}", item_path_str(cx, id)), ty_tup(_) => ~"tuple", ty_infer(TyVar(_)) => ~"inferred type", ty_infer(IntVar(_)) => ~"integral variable", ty_infer(FloatVar(_)) => ~"floating-point variable", ty_param(_) => ~"type parameter", ty_self(_) => ~"self", ty_err => ~"type error" } } pub fn type_err_to_str(cx: ctxt, err: &type_err) -> ~str { /*! * * Explains the source of a type err in a short, * human readable way. This is meant to be placed in * parentheses after some larger message. You should * also invoke `note_and_explain_type_err()` afterwards * to present additional details, particularly when * it comes to lifetime-related errors. */ fn terr_vstore_kind_to_str(k: terr_vstore_kind) -> ~str { match k { terr_vec => ~"[]", terr_str => ~"str", terr_fn => ~"fn", terr_trait => ~"trait" } } match *err { terr_mismatch => ~"types differ", terr_purity_mismatch(values) => { format!("expected {} fn but found {} fn", values.expected.to_str(), values.found.to_str()) } terr_abi_mismatch(values) => { format!("expected {} fn but found {} fn", values.expected.to_str(), values.found.to_str()) } terr_onceness_mismatch(values) => { format!("expected {} fn but found {} fn", values.expected.to_str(), values.found.to_str()) } terr_sigil_mismatch(values) => { format!("expected {} closure, found {} closure", values.expected.to_str(), values.found.to_str()) } terr_mutability => ~"values differ in mutability", terr_box_mutability => ~"boxed values differ in mutability", terr_vec_mutability => ~"vectors differ in mutability", terr_ptr_mutability => ~"pointers differ in mutability", terr_ref_mutability => ~"references differ in mutability", terr_ty_param_size(values) => { format!("expected a type with {} type params \ but found one with {} type params", values.expected, values.found) } terr_tuple_size(values) => { format!("expected a tuple with {} elements \ but found one with {} elements", values.expected, values.found) } terr_record_size(values) => { format!("expected a record with {} fields \ but found one with {} fields", values.expected, values.found) } terr_record_mutability => { ~"record elements differ in mutability" } terr_record_fields(values) => { format!("expected a record with field `{}` but found one with field \ `{}`", cx.sess.str_of(values.expected), cx.sess.str_of(values.found)) } terr_arg_count => ~"incorrect number of function parameters", terr_regions_does_not_outlive(*) => { format!("lifetime mismatch") } terr_regions_not_same(*) => { format!("lifetimes are not the same") } terr_regions_no_overlap(*) => { format!("lifetimes do not intersect") } terr_regions_insufficiently_polymorphic(br, _) => { format!("expected bound lifetime parameter {}, \ but found concrete lifetime", bound_region_ptr_to_str(cx, br)) } terr_regions_overly_polymorphic(br, _) => { format!("expected concrete lifetime, \ but found bound lifetime parameter {}", bound_region_ptr_to_str(cx, br)) } terr_vstores_differ(k, ref values) => { format!("{} storage differs: expected {} but found {}", terr_vstore_kind_to_str(k), vstore_to_str(cx, (*values).expected), vstore_to_str(cx, (*values).found)) } terr_trait_stores_differ(_, ref values) => { format!("trait storage differs: expected {} but found {}", trait_store_to_str(cx, (*values).expected), trait_store_to_str(cx, (*values).found)) } terr_in_field(err, fname) => { format!("in field `{}`, {}", cx.sess.str_of(fname), type_err_to_str(cx, err)) } terr_sorts(values) => { format!("expected {} but found {}", ty_sort_str(cx, values.expected), ty_sort_str(cx, values.found)) } terr_traits(values) => { format!("expected trait {} but found trait {}", item_path_str(cx, values.expected), item_path_str(cx, values.found)) } terr_builtin_bounds(values) => { if values.expected.is_empty() { format!("expected no bounds but found `{}`", values.found.user_string(cx)) } else if values.found.is_empty() { format!("expected bounds `{}` but found no bounds", values.expected.user_string(cx)) } else { format!("expected bounds `{}` but found bounds `{}`", values.expected.user_string(cx), values.found.user_string(cx)) } } terr_integer_as_char => { format!("expected an integral type but found char") } terr_int_mismatch(ref values) => { format!("expected {} but found {}", values.expected.to_str(), values.found.to_str()) } terr_float_mismatch(ref values) => { format!("expected {} but found {}", values.expected.to_str(), values.found.to_str()) } } } pub fn note_and_explain_type_err(cx: ctxt, err: &type_err) { match *err { terr_regions_does_not_outlive(subregion, superregion) => { note_and_explain_region(cx, "", subregion, "..."); note_and_explain_region(cx, "...does not necessarily outlive ", superregion, ""); } terr_regions_not_same(region1, region2) => { note_and_explain_region(cx, "", region1, "..."); note_and_explain_region(cx, "...is not the same lifetime as ", region2, ""); } terr_regions_no_overlap(region1, region2) => { note_and_explain_region(cx, "", region1, "..."); note_and_explain_region(cx, "...does not overlap ", region2, ""); } terr_regions_insufficiently_polymorphic(_, conc_region) => { note_and_explain_region(cx, "concrete lifetime that was found is ", conc_region, ""); } terr_regions_overly_polymorphic(_, conc_region) => { note_and_explain_region(cx, "expected concrete lifetime is ", conc_region, ""); } _ => {} } } pub fn def_has_ty_params(def: ast::Def) -> bool { match def { ast::DefFn(_, _) | ast::DefVariant(_, _, _) | ast::DefStruct(_) => true, _ => false } } pub fn provided_source(cx: ctxt, id: ast::DefId) -> Option<ast::DefId> { cx.provided_method_sources.find(&id).map(|x| *x) } pub fn provided_trait_methods(cx: ctxt, id: ast::DefId) -> ~[@Method] { if is_local(id) { match cx.items.find(&id.node) { Some(&ast_map::node_item(@ast::item { node: item_trait(_, _, ref ms), _ }, _)) => match ast_util::split_trait_methods(*ms) { (_, p) => p.map(|m| method(cx, ast_util::local_def(m.id))) }, _ => cx.sess.bug(format!("provided_trait_methods: {:?} is not a trait", id)) } } else { csearch::get_provided_trait_methods(cx, id) } } pub fn trait_supertraits(cx: ctxt, id: ast::DefId) -> @~[@TraitRef] { // Check the cache. match cx.supertraits.find(&id) { Some(&trait_refs) => { return trait_refs; } None => {} // Continue. } // Not in the cache. It had better be in the metadata, which means it // shouldn't be local. assert!(!is_local(id)); // Get the supertraits out of the metadata and create the // TraitRef for each. let result = @csearch::get_supertraits(cx, id); cx.supertraits.insert(id, result); return result; } pub fn trait_ref_supertraits(cx: ctxt, trait_ref: &ty::TraitRef) -> ~[@TraitRef] { let supertrait_refs = trait_supertraits(cx, trait_ref.def_id); supertrait_refs.map( |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs)) } fn lookup_locally_or_in_crate_store<V:Clone>( descr: &str, def_id: ast::DefId, map: &mut HashMap<ast::DefId, V>, load_external: &fn() -> V) -> V { /*! * * Helper for looking things up in the various maps * that are populated during typeck::collect (e.g., * `cx.methods`, `cx.tcache`, etc). All of these share * the pattern that if the id is local, it should have * been loaded into the map by the `typeck::collect` phase. * If the def-id is external, then we have to go consult * the crate loading code (and cache the result for the future). */ match map.find(&def_id) { Some(&ref v) => { return (*v).clone(); } None => { } } if def_id.crate == ast::LOCAL_CRATE { fail2!("No def'n found for {:?} in tcx.{}", def_id, descr); } let v = load_external(); map.insert(def_id, v.clone()); v } pub fn trait_method(cx: ctxt, trait_did: ast::DefId, idx: uint) -> @Method { let method_def_id = ty::trait_method_def_ids(cx, trait_did)[idx]; ty::method(cx, method_def_id) } pub fn trait_methods(cx: ctxt, trait_did: ast::DefId) -> @~[@Method] { match cx.trait_methods_cache.find(&trait_did) { Some(&methods) => methods, None => { let def_ids = ty::trait_method_def_ids(cx, trait_did); let methods = @def_ids.map(|d| ty::method(cx, *d)); cx.trait_methods_cache.insert(trait_did, methods); methods } } } pub fn method(cx: ctxt, id: ast::DefId) -> @Method { lookup_locally_or_in_crate_store( "methods", id, cx.methods, || @csearch::get_method(cx, id)) } pub fn trait_method_def_ids(cx: ctxt, id: ast::DefId) -> @~[DefId] { lookup_locally_or_in_crate_store( "methods", id, cx.trait_method_def_ids, || @csearch::get_trait_method_def_ids(cx.cstore, id)) } pub fn impl_trait_ref(cx: ctxt, id: ast::DefId) -> Option<@TraitRef> { match cx.impl_trait_cache.find(&id) { Some(&ret) => { return ret; } None => {} } let ret = if id.crate == ast::LOCAL_CRATE { debug2!("(impl_trait_ref) searching for trait impl {:?}", id); match cx.items.find(&id.node) { Some(&ast_map::node_item(@ast::item { node: ast::item_impl(_, ref opt_trait, _, _), _}, _)) => { match opt_trait { &Some(ref t) => Some(ty::node_id_to_trait_ref(cx, t.ref_id)), &None => None } } _ => None } } else { csearch::get_impl_trait(cx, id) }; cx.impl_trait_cache.insert(id, ret); return ret; } pub fn trait_ref_to_def_id(tcx: ctxt, tr: &ast::trait_ref) -> ast::DefId { let def = tcx.def_map.find(&tr.ref_id).expect("no def-map entry for trait"); ast_util::def_id_of_def(*def) } pub fn try_add_builtin_trait(tcx: ctxt, trait_def_id: ast::DefId, builtin_bounds: &mut BuiltinBounds) -> bool { //! Checks whether `trait_ref` refers to one of the builtin //! traits, like `Send`, and adds the corresponding //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref` //! is a builtin trait. match tcx.lang_items.to_builtin_kind(trait_def_id) { Some(bound) => { builtin_bounds.add(bound); true } None => false } } pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> { match get(ty).sty { ty_trait(id, _, _, _, _) | ty_struct(id, _) | ty_enum(id, _) => Some(id), _ => None } } /// Returns the def ID of the constructor for the given tuple-like struct, or /// None if the struct is not tuple-like. Fails if the given def ID does not /// refer to a struct at all. fn struct_ctor_id(cx: ctxt, struct_did: ast::DefId) -> Option<ast::DefId> { if struct_did.crate != ast::LOCAL_CRATE { // XXX: Cross-crate functionality. cx.sess.unimpl("constructor ID of cross-crate tuple structs"); } match cx.items.find(&struct_did.node) { Some(&ast_map::node_item(item, _)) => { match item.node { ast::item_struct(struct_def, _) => { do struct_def.ctor_id.map |ctor_id| { ast_util::local_def(ctor_id) } } _ => cx.sess.bug("called struct_ctor_id on non-struct") } } _ => cx.sess.bug("called struct_ctor_id on non-struct") } } // Enum information #[deriving(Clone)] pub struct VariantInfo { args: ~[t], arg_names: Option<~[ast::Ident]>, ctor_ty: t, name: ast::Ident, id: ast::DefId, disr_val: Disr, vis: visibility } impl VariantInfo { /// Creates a new VariantInfo from the corresponding ast representation. /// /// Does not do any caching of the value in the type context. pub fn from_ast_variant(cx: ctxt, ast_variant: &ast::variant, discriminant: Disr) -> VariantInfo { let ctor_ty = node_id_to_type(cx, ast_variant.node.id); match ast_variant.node.kind { ast::tuple_variant_kind(ref args) => { let arg_tys = if args.len() > 0 { ty_fn_args(ctor_ty).map(|a| *a) } else { ~[] }; return VariantInfo { args: arg_tys, arg_names: None, ctor_ty: ctor_ty, name: ast_variant.node.name, id: ast_util::local_def(ast_variant.node.id), disr_val: discriminant, vis: ast_variant.node.vis }; }, ast::struct_variant_kind(ref struct_def) => { let fields: &[@struct_field] = struct_def.fields; assert!(fields.len() > 0); let arg_tys = ty_fn_args(ctor_ty).map(|a| *a); let arg_names = do fields.map |field| { match field.node.kind { named_field(ident, _) => ident, unnamed_field => cx.sess.bug( "enum_variants: all fields in struct must have a name") } }; return VariantInfo { args: arg_tys, arg_names: Some(arg_names), ctor_ty: ctor_ty, name: ast_variant.node.name, id: ast_util::local_def(ast_variant.node.id), disr_val: discriminant, vis: ast_variant.node.vis }; } } } } pub fn substd_enum_variants(cx: ctxt, id: ast::DefId, substs: &substs) -> ~[@VariantInfo] { do enum_variants(cx, id).iter().map |variant_info| { let substd_args = variant_info.args.iter() .map(|aty| subst(cx, substs, *aty)).collect(); let substd_ctor_ty = subst(cx, substs, variant_info.ctor_ty); @VariantInfo { args: substd_args, ctor_ty: substd_ctor_ty, ..(**variant_info).clone() } }.collect() } pub fn item_path_str(cx: ctxt, id: ast::DefId) -> ~str { ast_map::path_to_str(item_path(cx, id), token::get_ident_interner()) } pub enum DtorKind { NoDtor, TraitDtor(DefId, bool) } impl DtorKind { pub fn is_not_present(&self) -> bool { match *self { NoDtor => true, _ => false } } pub fn is_present(&self) -> bool { !self.is_not_present() } pub fn has_drop_flag(&self) -> bool { match self { &NoDtor => false, &TraitDtor(_, flag) => flag } } } /* If struct_id names a struct with a dtor, return Some(the dtor's id). Otherwise return none. */ pub fn ty_dtor(cx: ctxt, struct_id: DefId) -> DtorKind { match cx.destructor_for_type.find(&struct_id) { Some(&method_def_id) => { let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag"); TraitDtor(method_def_id, flag) } None => NoDtor, } } pub fn has_dtor(cx: ctxt, struct_id: DefId) -> bool { ty_dtor(cx, struct_id).is_present() } pub fn item_path(cx: ctxt, id: ast::DefId) -> ast_map::path { if id.crate != ast::LOCAL_CRATE { csearch::get_item_path(cx, id) } else { // FIXME (#5521): uncomment this code and don't have a catch-all at the // end of the match statement. Favor explicitly listing // each variant. // let node = cx.items.get(&id.node); // match *node { match *cx.items.get(&id.node) { ast_map::node_item(item, path) => { let item_elt = match item.node { item_mod(_) | item_foreign_mod(_) => { ast_map::path_mod(item.ident) } _ => { ast_map::path_name(item.ident) } }; vec::append_one((*path).clone(), item_elt) } ast_map::node_foreign_item(nitem, _, _, path) => { vec::append_one((*path).clone(), ast_map::path_name(nitem.ident)) } ast_map::node_method(method, _, path) => { vec::append_one((*path).clone(), ast_map::path_name(method.ident)) } ast_map::node_trait_method(trait_method, _, path) => { let method = ast_util::trait_method_to_ty_method(&*trait_method); vec::append_one((*path).clone(), ast_map::path_name(method.ident)) } ast_map::node_variant(ref variant, _, path) => { vec::append_one(path.init().to_owned(), ast_map::path_name((*variant).node.name)) } ast_map::node_struct_ctor(_, item, path) => { vec::append_one((*path).clone(), ast_map::path_name(item.ident)) } ref node => { cx.sess.bug(format!("cannot find item_path for node {:?}", node)); } } } } pub fn enum_is_univariant(cx: ctxt, id: ast::DefId) -> bool { enum_variants(cx, id).len() == 1 } pub fn type_is_empty(cx: ctxt, t: t) -> bool { match ty::get(t).sty { ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(), _ => false } } pub fn enum_variants(cx: ctxt, id: ast::DefId) -> @~[@VariantInfo] { match cx.enum_var_cache.find(&id) { Some(&variants) => return variants, _ => { /* fallthrough */ } } let result = if ast::LOCAL_CRATE != id.crate { @csearch::get_enum_variants(cx, id) } else { /* Although both this code and check_enum_variants in typeck/check call eval_const_expr, it should never get called twice for the same expr, since check_enum_variants also updates the enum_var_cache */ match cx.items.get_copy(&id.node) { ast_map::node_item(@ast::item { node: ast::item_enum(ref enum_definition, _), _ }, _) => { let mut last_discriminant: Option<Disr> = None; @enum_definition.variants.iter().map(|variant| { let mut discriminant = match last_discriminant { Some(val) => val + 1, None => INITIAL_DISCRIMINANT_VALUE }; match variant.node.disr_expr { Some(e) => match const_eval::eval_const_expr_partial(&cx, e) { Ok(const_eval::const_int(val)) => discriminant = val as Disr, Ok(const_eval::const_uint(val)) => discriminant = val as Disr, Ok(_) => { cx.sess.span_err(e.span, "expected signed integer constant"); } Err(ref err) => { cx.sess.span_err(e.span, format!("expected constant: {}", (*err))); } }, None => {} }; let variant_info = @VariantInfo::from_ast_variant(cx, variant, discriminant); last_discriminant = Some(discriminant); variant_info }).collect() } _ => cx.sess.bug("enum_variants: id not bound to an enum") } }; cx.enum_var_cache.insert(id, result); result } // Returns information about the enum variant with the given ID: pub fn enum_variant_with_id(cx: ctxt, enum_id: ast::DefId, variant_id: ast::DefId) -> @VariantInfo { let variants = enum_variants(cx, enum_id); let mut i = 0; while i < variants.len() { let variant = variants[i]; if variant.id == variant_id { return variant; } i += 1; } cx.sess.bug("enum_variant_with_id(): no variant exists with that ID"); } // If the given item is in an external crate, looks up its type and adds it to // the type cache. Returns the type parameters and type. pub fn lookup_item_type(cx: ctxt, did: ast::DefId) -> ty_param_bounds_and_ty { lookup_locally_or_in_crate_store( "tcache", did, cx.tcache, || csearch::get_type(cx, did)) } pub fn lookup_impl_vtables(cx: ctxt, did: ast::DefId) -> typeck::impl_res { lookup_locally_or_in_crate_store( "impl_vtables", did, cx.impl_vtables, || csearch::get_impl_vtables(cx, did) ) } /// Given the did of a trait, returns its canonical trait ref. pub fn lookup_trait_def(cx: ctxt, did: ast::DefId) -> @ty::TraitDef { match cx.trait_defs.find(&did) { Some(&trait_def) => { // The item is in this crate. The caller should have added it to the // type cache already return trait_def; } None => { assert!(did.crate != ast::LOCAL_CRATE); let trait_def = @csearch::get_trait_def(cx, did); cx.trait_defs.insert(did, trait_def); return trait_def; } } } /// Determine whether an item is annotated with an attribute pub fn has_attr(tcx: ctxt, did: DefId, attr: &str) -> bool { if is_local(did) { match tcx.items.find(&did.node) { Some( &ast_map::node_item(@ast::item { attrs: ref attrs, _ }, _)) => attr::contains_name(*attrs, attr), _ => tcx.sess.bug(format!("has_attr: {:?} is not an item", did)) } } else { let mut ret = false; do csearch::get_item_attrs(tcx.cstore, did) |meta_items| { ret = ret || attr::contains_name(meta_items, attr); } ret } } /// Determine whether an item is annotated with `#[packed]` pub fn lookup_packed(tcx: ctxt, did: DefId) -> bool { has_attr(tcx, did, "packed") } /// Determine whether an item is annotated with `#[simd]` pub fn lookup_simd(tcx: ctxt, did: DefId) -> bool { has_attr(tcx, did, "simd") } // Look up a field ID, whether or not it's local // Takes a list of type substs in case the struct is generic pub fn lookup_field_type(tcx: ctxt, struct_id: DefId, id: DefId, substs: &substs) -> ty::t { let t = if id.crate == ast::LOCAL_CRATE { node_id_to_type(tcx, id.node) } else { match tcx.tcache.find(&id) { Some(&ty_param_bounds_and_ty {ty, _}) => ty, None => { let tpt = csearch::get_field_type(tcx, struct_id, id); tcx.tcache.insert(id, tpt); tpt.ty } } }; subst(tcx, substs, t) } // Look up the list of field names and IDs for a given struct // Fails if the id is not bound to a struct. pub fn lookup_struct_fields(cx: ctxt, did: ast::DefId) -> ~[field_ty] { if did.crate == ast::LOCAL_CRATE { match cx.items.find(&did.node) { Some(&ast_map::node_item(i,_)) => { match i.node { ast::item_struct(struct_def, _) => { struct_field_tys(struct_def.fields) } _ => cx.sess.bug("struct ID bound to non-struct") } } Some(&ast_map::node_variant(ref variant, _, _)) => { match (*variant).node.kind { ast::struct_variant_kind(struct_def) => { struct_field_tys(struct_def.fields) } _ => { cx.sess.bug("struct ID bound to enum variant that isn't \ struct-like") } } } _ => { cx.sess.bug( format!("struct ID not bound to an item: {}", ast_map::node_id_to_str(cx.items, did.node, token::get_ident_interner()))); } } } else { return csearch::get_struct_fields(cx.sess.cstore, did); } } pub fn lookup_struct_field(cx: ctxt, parent: ast::DefId, field_id: ast::DefId) -> field_ty { let r = lookup_struct_fields(cx, parent); match r.iter().find( |f| f.id.node == field_id.node) { Some(t) => *t, None => cx.sess.bug("struct ID not found in parent's fields") } } fn struct_field_tys(fields: &[@struct_field]) -> ~[field_ty] { do fields.map |field| { match field.node.kind { named_field(ident, visibility) => { field_ty { name: ident.name, id: ast_util::local_def(field.node.id), vis: visibility, } } unnamed_field => { field_ty { name: syntax::parse::token::special_idents::unnamed_field.name, id: ast_util::local_def(field.node.id), vis: ast::public, } } } } } // Returns a list of fields corresponding to the struct's items. trans uses // this. Takes a list of substs with which to instantiate field types. pub fn struct_fields(cx: ctxt, did: ast::DefId, substs: &substs) -> ~[field] { do lookup_struct_fields(cx, did).map |f| { field { // FIXME #6993: change type of field to Name and get rid of new() ident: ast::Ident::new(f.name), mt: mt { ty: lookup_field_type(cx, did, f.id, substs), mutbl: MutImmutable } } } } pub fn is_binopable(cx: ctxt, ty: t, op: ast::BinOp) -> bool { static tycat_other: int = 0; static tycat_bool: int = 1; static tycat_char: int = 2; static tycat_int: int = 3; static tycat_float: int = 4; static tycat_bot: int = 5; static tycat_raw_ptr: int = 6; static opcat_add: int = 0; static opcat_sub: int = 1; static opcat_mult: int = 2; static opcat_shift: int = 3; static opcat_rel: int = 4; static opcat_eq: int = 5; static opcat_bit: int = 6; static opcat_logic: int = 7; fn opcat(op: ast::BinOp) -> int { match op { ast::BiAdd => opcat_add, ast::BiSub => opcat_sub, ast::BiMul => opcat_mult, ast::BiDiv => opcat_mult, ast::BiRem => opcat_mult, ast::BiAnd => opcat_logic, ast::BiOr => opcat_logic, ast::BiBitXor => opcat_bit, ast::BiBitAnd => opcat_bit, ast::BiBitOr => opcat_bit, ast::BiShl => opcat_shift, ast::BiShr => opcat_shift, ast::BiEq => opcat_eq, ast::BiNe => opcat_eq, ast::BiLt => opcat_rel, ast::BiLe => opcat_rel, ast::BiGe => opcat_rel, ast::BiGt => opcat_rel } } fn tycat(cx: ctxt, ty: t) -> int { if type_is_simd(cx, ty) { return tycat(cx, simd_type(cx, ty)) } match get(ty).sty { ty_char => tycat_char, ty_bool => tycat_bool, ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int, ty_float(_) | ty_infer(FloatVar(_)) => tycat_float, ty_bot => tycat_bot, ty_ptr(_) => tycat_raw_ptr, _ => tycat_other } } static t: bool = true; static f: bool = false; let tbl = [ // +, -, *, shift, rel, ==, bit, logic /*other*/ [f, f, f, f, f, f, f, f], /*bool*/ [f, f, f, f, t, t, t, t], /*char*/ [f, f, f, f, t, t, f, f], /*int*/ [t, t, t, t, t, t, t, f], /*float*/ [t, t, t, f, t, t, f, f], /*bot*/ [t, t, t, t, t, t, t, t], /*raw ptr*/ [f, f, f, f, t, t, f, f]]; return tbl[tycat(cx, ty)][opcat(op)]; } pub fn ty_params_to_tys(tcx: ty::ctxt, generics: &ast::Generics) -> ~[t] { vec::from_fn(generics.ty_params.len(), |i| { let id = generics.ty_params.get(i).id; ty::mk_param(tcx, i, ast_util::local_def(id)) }) } /// Returns an equivalent type with all the typedefs and self regions removed. pub fn normalize_ty(cx: ctxt, t: t) -> t { fn normalize_mt(cx: ctxt, mt: mt) -> mt { mt { ty: normalize_ty(cx, mt.ty), mutbl: mt.mutbl } } fn normalize_vstore(vstore: vstore) -> vstore { match vstore { vstore_fixed(*) | vstore_uniq | vstore_box => vstore, vstore_slice(_) => vstore_slice(re_static) } } match cx.normalized_cache.find(&t) { Some(&t) => return t, None => () } let t = match get(t).sty { ty_evec(mt, vstore) => // This type has a vstore. Get rid of it mk_evec(cx, normalize_mt(cx, mt), normalize_vstore(vstore)), ty_estr(vstore) => // This type has a vstore. Get rid of it mk_estr(cx, normalize_vstore(vstore)), ty_rptr(_, mt) => // This type has a region. Get rid of it mk_rptr(cx, re_static, normalize_mt(cx, mt)), ty_closure(ref closure_ty) => { mk_closure(cx, ClosureTy { region: ty::re_static, ..(*closure_ty).clone() }) } ty_enum(did, ref r) => { match (*r).regions { NonerasedRegions(_) => { // trans doesn't care about regions mk_enum(cx, did, substs {regions: ty::ErasedRegions, self_ty: None, tps: (*r).tps.clone()}) } ErasedRegions => { t } } } ty_struct(did, ref r) => { match (*r).regions { NonerasedRegions(_) => { // Ditto. mk_struct(cx, did, substs {regions: ty::ErasedRegions, self_ty: None, tps: (*r).tps.clone()}) } ErasedRegions => { t } } } _ => t }; let sty = fold_sty(&get(t).sty, |t| { normalize_ty(cx, t) }); let t_norm = mk_t(cx, sty); cx.normalized_cache.insert(t, t_norm); return t_norm; } pub trait ExprTyProvider { fn expr_ty(&self, ex: &ast::Expr) -> t; fn ty_ctxt(&self) -> ctxt; } impl ExprTyProvider for ctxt { fn expr_ty(&self, ex: &ast::Expr) -> t { expr_ty(*self, ex) } fn ty_ctxt(&self) -> ctxt { *self } } // Returns the repeat count for a repeating vector expression. pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) -> uint { match const_eval::eval_const_expr_partial(tcx, count_expr) { Ok(ref const_val) => match *const_val { const_eval::const_int(count) => if count < 0 { tcx.ty_ctxt().sess.span_err(count_expr.span, "expected positive integer for \ repeat count but found negative integer"); return 0; } else { return count as uint }, const_eval::const_uint(count) => return count as uint, const_eval::const_float(count) => { tcx.ty_ctxt().sess.span_err(count_expr.span, "expected positive integer for \ repeat count but found float"); return count as uint; } const_eval::const_str(_) => { tcx.ty_ctxt().sess.span_err(count_expr.span, "expected positive integer for \ repeat count but found string"); return 0; } const_eval::const_bool(_) => { tcx.ty_ctxt().sess.span_err(count_expr.span, "expected positive integer for \ repeat count but found boolean"); return 0; } }, Err(*) => { tcx.ty_ctxt().sess.span_err(count_expr.span, "expected constant integer for repeat count \ but found variable"); return 0; } } } // Determine what purity to check a nested function under pub fn determine_inherited_purity(parent: (ast::purity, ast::NodeId), child: (ast::purity, ast::NodeId), child_sigil: ast::Sigil) -> (ast::purity, ast::NodeId) { // If the closure is a stack closure and hasn't had some non-standard // purity inferred for it, then check it under its parent's purity. // Otherwise, use its own match child_sigil { ast::BorrowedSigil if child.first() == ast::impure_fn => parent, _ => child } } // Iterate over a type parameter's bounded traits and any supertraits // of those traits, ignoring kinds. // Here, the supertraits are the transitive closure of the supertrait // relation on the supertraits from each bounded trait's constraint // list. pub fn each_bound_trait_and_supertraits(tcx: ctxt, bounds: &[@TraitRef], f: &fn(@TraitRef) -> bool) -> bool { for &bound_trait_ref in bounds.iter() { let mut supertrait_set = HashMap::new(); let mut trait_refs = ~[]; let mut i = 0; // Seed the worklist with the trait from the bound supertrait_set.insert(bound_trait_ref.def_id, ()); trait_refs.push(bound_trait_ref); // Add the given trait ty to the hash map while i < trait_refs.len() { debug2!("each_bound_trait_and_supertraits(i={:?}, trait_ref={})", i, trait_refs[i].repr(tcx)); if !f(trait_refs[i]) { return false; } // Add supertraits to supertrait_set let supertrait_refs = trait_ref_supertraits(tcx, trait_refs[i]); for &supertrait_ref in supertrait_refs.iter() { debug2!("each_bound_trait_and_supertraits(supertrait_ref={})", supertrait_ref.repr(tcx)); let d_id = supertrait_ref.def_id; if !supertrait_set.contains_key(&d_id) { // FIXME(#5527) Could have same trait multiple times supertrait_set.insert(d_id, ()); trait_refs.push(supertrait_ref); } } i += 1; } } return true; } pub fn count_traits_and_supertraits(tcx: ctxt, type_param_defs: &[TypeParameterDef]) -> uint { let mut total = 0; for type_param_def in type_param_defs.iter() { do each_bound_trait_and_supertraits( tcx, type_param_def.bounds.trait_bounds) |_| { total += 1; true }; } return total; } pub fn get_tydesc_ty(tcx: ctxt) -> Result<t, ~str> { do tcx.lang_items.require(TyDescStructLangItem).map_move |tydesc_lang_item| { tcx.intrinsic_defs.find_copy(&tydesc_lang_item) .expect("Failed to resolve TyDesc") } } pub fn get_opaque_ty(tcx: ctxt) -> Result<t, ~str> { do tcx.lang_items.require(OpaqueStructLangItem).map_move |opaque_lang_item| { tcx.intrinsic_defs.find_copy(&opaque_lang_item) .expect("Failed to resolve Opaque") } } pub fn visitor_object_ty(tcx: ctxt, region: ty::Region) -> Result<(@TraitRef, t), ~str> { let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) { Ok(id) => id, Err(s) => { return Err(s); } }; let substs = substs { regions: ty::NonerasedRegions(opt_vec::Empty), self_ty: None, tps: ~[] }; let trait_ref = @TraitRef { def_id: trait_lang_item, substs: substs }; Ok((trait_ref, mk_trait(tcx, trait_ref.def_id, trait_ref.substs.clone(), RegionTraitStore(region), ast::MutMutable, EmptyBuiltinBounds()))) } /// Records a trait-to-implementation mapping. fn record_trait_implementation(tcx: ctxt, trait_def_id: DefId, implementation: @Impl) { let implementation_list; match tcx.trait_impls.find(&trait_def_id) { None => { implementation_list = @mut ~[]; tcx.trait_impls.insert(trait_def_id, implementation_list); } Some(&existing_implementation_list) => { implementation_list = existing_implementation_list } } implementation_list.push(implementation); } /// Populates the type context with all the implementations for the given type /// if necessary. pub fn populate_implementations_for_type_if_necessary(tcx: ctxt, type_id: ast::DefId) { if type_id.crate == LOCAL_CRATE { return } if tcx.populated_external_types.contains(&type_id) { return } do csearch::each_implementation_for_type(tcx.sess.cstore, type_id) |implementation_def_id| { let implementation = @csearch::get_impl(tcx, implementation_def_id); // Record the trait->implementation mappings, if applicable. let associated_traits = csearch::get_impl_trait(tcx, implementation.did); for trait_ref in associated_traits.iter() { record_trait_implementation(tcx, trait_ref.def_id, implementation); } // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. for method in implementation.methods.iter() { for source in method.provided_source.iter() { tcx.provided_method_sources.insert(method.def_id, *source); } } // If this is an inherent implementation, record it. if associated_traits.is_none() { let implementation_list; match tcx.inherent_impls.find(&type_id) { None => { implementation_list = @mut ~[]; tcx.inherent_impls.insert(type_id, implementation_list); } Some(&existing_implementation_list) => { implementation_list = existing_implementation_list; } } implementation_list.push(implementation); } // Store the implementation info. tcx.impls.insert(implementation_def_id, implementation); } tcx.populated_external_types.insert(type_id); } /// Populates the type context with all the implementations for the given /// trait if necessary. pub fn populate_implementations_for_trait_if_necessary( tcx: ctxt, trait_id: ast::DefId) { if trait_id.crate == LOCAL_CRATE { return } if tcx.populated_external_traits.contains(&trait_id) { return } do csearch::each_implementation_for_trait(tcx.sess.cstore, trait_id) |implementation_def_id| { let implementation = @csearch::get_impl(tcx, implementation_def_id); // Record the trait->implementation mapping. record_trait_implementation(tcx, trait_id, implementation); // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. for method in implementation.methods.iter() { for source in method.provided_source.iter() { tcx.provided_method_sources.insert(method.def_id, *source); } } // Store the implementation info. tcx.impls.insert(implementation_def_id, implementation); } tcx.populated_external_traits.insert(trait_id); } /// If the given def ID describes a trait method, returns the ID of the trait /// that the method belongs to. Otherwise, returns `None`. pub fn trait_of_method(tcx: ctxt, def_id: ast::DefId) -> Option<ast::DefId> { match tcx.methods.find(&def_id) { Some(method_descriptor) => { match method_descriptor.container { TraitContainer(id) => return Some(id), _ => {} } } None => {} } // If the method was in the local crate, then if we got here we know the // answer is negative. if def_id.crate == LOCAL_CRATE { return None } let result = csearch::get_trait_of_method(tcx.cstore, def_id, tcx); result }
31.986363
97
0.54945
9b177c34d3edf9a5a8cb5045ef6c619fc5a445f8
10,958
/// Oids are BER encoded and defined in the various RFCs. Oids are /// horrible. This module is horrible. I'm so pleased to share my /// horror with you. use crate::error::{Error, MajorFlags}; use libgssapi_sys::{ gss_OID, gss_OID_desc, gss_OID_set, gss_OID_set_desc, gss_add_oid_set_member, gss_create_empty_oid_set, gss_release_oid_set, gss_test_oid_set_member, OM_uint32, GSS_S_COMPLETE, }; use std::{ self, cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, collections::HashMap, fmt, hash::{Hash, Hasher}, iter::{ExactSizeIterator, FromIterator, IntoIterator, Iterator}, ops::{Deref, Index}, ptr, slice, os::raw::c_int, }; // CR estokes: do I need the attributes from rfc 5587? There are loads of them. pub static GSS_NT_USER_NAME: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x01"); pub static GSS_NT_MACHINE_UID_NAME: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"); pub static GSS_NT_STRING_UID_NAME: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x03"); pub static GSS_NT_HOSTBASED_SERVICE: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x04"); pub static GSS_NT_ANONYMOUS: Oid = Oid::from_slice(b"\x2b\x06\01\x05\x06\x03"); pub static GSS_NT_EXPORT_NAME: Oid = Oid::from_slice(b"\x2b\x06\x01\x05\x06\x04"); pub static GSS_NT_COMPOSITE_EXPORT: Oid = Oid::from_slice(b"\x2b\x06\x01\x05\x06\x06"); pub static GSS_NT_KRB5_PRINCIPAL: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x01"); pub static GSS_INQ_SSPI_SESSION_KEY: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x05"); pub static GSS_INQ_NEGOEX_KEY: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x10"); pub static GSS_INQ_NEGOEX_VERIFY_KEY: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x11"); pub static GSS_MA_NEGOEX_AND_SPNEGO: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x12"); pub static GSS_SEC_CONTEXT_SASL_SSF: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x0f"); pub static GSS_MECH_KRB5: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"); pub static GSS_MECH_IAKERB: Oid = Oid::from_slice(b"\x2b\x06\x01\x05\x02\x05"); pub static GSS_KRB5_CRED_NO_CI_FLAGS_X: Oid = Oid::from_slice(b"\x2a\x85\x70\x2b\x0d\x1d"); pub static GSS_KRB5_GET_CRED_IMPERSONATOR: Oid = Oid::from_slice(b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x0e"); pub(crate) const NO_OID: gss_OID = ptr::null_mut(); pub(crate) const NO_OID_SET: gss_OID_set = ptr::null_mut(); lazy_static! { static ref OIDS: HashMap<Oid, &'static str> = HashMap::from_iter( [ (GSS_NT_USER_NAME, "GSS_NT_USER_NAME"), (GSS_NT_MACHINE_UID_NAME, "GSS_NT_MACHINE_UID_NAME"), (GSS_NT_STRING_UID_NAME, "GSS_NT_STRING_UID_NAME"), (GSS_NT_HOSTBASED_SERVICE, "GSS_NT_HOSTBASED_SERVICE"), (GSS_NT_ANONYMOUS, "GSS_NT_ANONYMOUS"), (GSS_NT_EXPORT_NAME, "GSS_NT_EXPORT_NAME"), (GSS_NT_COMPOSITE_EXPORT, "GSS_NT_COMPOSITE_EXPORT"), (GSS_INQ_SSPI_SESSION_KEY, "GSS_INQ_SSPI_SESSION_KEY"), (GSS_INQ_NEGOEX_KEY, "GSS_INQ_NEGOEX_KEY"), (GSS_INQ_NEGOEX_VERIFY_KEY, "GSS_INQ_NEGOEX_VERIFY_KEY"), (GSS_MA_NEGOEX_AND_SPNEGO, "GSS_MA_NEGOEX_AND_SPNEGO"), (GSS_SEC_CONTEXT_SASL_SSF, "GSS_SEC_CONTEXT_SASL_SSF"), (GSS_MECH_KRB5, "GSS_MECH_KRB5"), (GSS_MECH_IAKERB, "GSS_MECH_IAKERB"), (GSS_NT_KRB5_PRINCIPAL, "GSS_KRB5_NT_PRINCIPAL"), (GSS_KRB5_CRED_NO_CI_FLAGS_X, "GSS_KRB5_CRED_NO_CI_FLAGS_X"), ( GSS_KRB5_GET_CRED_IMPERSONATOR, "GSS_KRB5_GET_CRED_IMPERSONATOR" ) ] .iter() .copied() ); } /* I've copied lots of OIDs from lots of standards into this module in * order to make your life easier, and also in order to not have to * run bindgen on ALL the header files. The standard says * implementations must put their oids in static memory, and that they * much be ber encoded, but it doesn't say they can't check equality * by pointer comparison. MIT Kerberos apparantly isn't that evil, but * some other implementation might be. So if that happens I guess file * a bug. */ /// An Oid. Did I mention I hate OIDs. #[repr(transparent)] #[derive(Clone, Copy)] pub struct Oid(gss_OID_desc); /* OIDs are defined in the standard as const pointers into static * memory, so this should be safe. */ unsafe impl Send for Oid {} unsafe impl Sync for Oid {} impl fmt::Debug for Oid { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match OIDS.get(self) { None => write!(f, "{:?}", &*self as &[u8]), Some(name) => write!(f, "{}", name), } } } impl fmt::Display for Oid { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::Debug::fmt(self, f) } } impl Deref for Oid { type Target = [u8]; fn deref(&self) -> &Self::Target { unsafe { slice::from_raw_parts(self.0.elements as *const u8, self.0.length as usize) } } } impl PartialEq for Oid { fn eq(&self, other: &Oid) -> bool { &*self as &[u8] == &*other as &[u8] } } impl Eq for Oid {} impl PartialOrd for Oid { fn partial_cmp(&self, other: &Oid) -> Option<Ordering> { (&*self as &[u8]).partial_cmp(&*other as &[u8]) } } impl Ord for Oid { fn cmp(&self, other: &Oid) -> Ordering { (&*self as &[u8]).cmp(&*other as &[u8]) } } impl Hash for Oid { fn hash<H>(&self, state: &mut H) where H: Hasher, { (&*self as &[u8]).hash(state) } } impl From<gss_OID_desc> for Oid { fn from(oid: gss_OID_desc) -> Self { Oid(oid) } } impl Oid { #[allow(dead_code)] pub(crate) unsafe fn from_c<'a>(ptr: gss_OID) -> &'a Oid { &*(ptr as *const Oid) } pub(crate) unsafe fn to_c(&self) -> gss_OID { self as *const Oid as gss_OID } /// If you need to use an OID I didn't define, then you must /// construct a BER encoded slice of it's components and store it /// in static memory (yes the standard REQUIRES that). Then you /// can pass it to this function and get a proper `Oid` handle. If /// you get the BER wrong something wonderful will happen, I just /// can't (won't?) say what. pub const fn from_slice(ber: &'static [u8]) -> Oid { let length = ber.len() as OM_uint32; let elements = ber.as_ptr() as *mut std::ffi::c_void; Oid(gss_OID_desc { length, elements }) } } pub struct OidSetIter<'a> { current: usize, set: &'a OidSet, } impl<'a> Iterator for OidSetIter<'a> { type Item = &'a Oid; fn next(&mut self) -> Option<Self::Item> { if self.current < self.len() { let res = Some(&self.set[self.current]); self.current += 1; res } else { None } } } impl<'a> ExactSizeIterator for OidSetIter<'a> { fn len(&self) -> usize { self.set.len() - self.current } } /// A set of OIDs. pub struct OidSet(gss_OID_set); // these are safe if we assume that the gssapi calls we pass oid sets // to make copies if they need to retain the sets. They'd be crazy not // to, given that the user will probably free the set soon after // making the call. unsafe impl Send for OidSet {} unsafe impl Sync for OidSet {} impl Drop for OidSet { fn drop(&mut self) { if !self.0.is_null() { let mut _minor = GSS_S_COMPLETE; let _major = unsafe { gss_release_oid_set( &mut _minor as *mut OM_uint32, &mut self.0 as *mut gss_OID_set, ) }; } // CR estokes: What to do on error? } } impl Index<usize> for OidSet { type Output = Oid; fn index(&self, index: usize) -> &Self::Output { let len = self.len(); if index < len { unsafe { &*((*self.0).elements.add(index) as *const Oid) } } else { panic!("index {} out of bounds count {}", index, len); } } } impl<'a> IntoIterator for &'a OidSet { type Item = &'a Oid; type IntoIter = OidSetIter<'a>; fn into_iter(self) -> Self::IntoIter { OidSetIter { current: 0, set: self, } } } impl fmt::Debug for OidSet { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::Debug::fmt(&self.into_iter().collect::<Vec<_>>(), f) } } impl OidSet { /// Create an empty OID set. I don't know how this can fail unless /// malloc fails. pub fn new() -> Result<OidSet, Error> { let mut minor = GSS_S_COMPLETE; let mut out = ptr::null_mut::<gss_OID_set_desc>(); let major = unsafe { gss_create_empty_oid_set( &mut minor as *mut OM_uint32, &mut out as *mut gss_OID_set, ) }; if major == GSS_S_COMPLETE { Ok(OidSet(out)) } else { Err(Error { major: unsafe { MajorFlags::from_bits_unchecked(major) }, minor, }) } } #[allow(dead_code)] pub(crate) unsafe fn from_c(ptr: gss_OID_set) -> OidSet { OidSet(ptr) } pub(crate) unsafe fn to_c(&self) -> gss_OID_set { self.0 } /// How many oids are in this set pub fn len(&self) -> usize { unsafe { (*self.0).count as usize } } /// Add an OID to the set. pub fn add(&mut self, id: &Oid) -> Result<(), Error> { let mut minor = GSS_S_COMPLETE; let major = unsafe { gss_add_oid_set_member( &mut minor as *mut OM_uint32, id.to_c(), &mut self.0 as *mut gss_OID_set, ) }; if major == GSS_S_COMPLETE { Ok(()) } else { Err(Error { major: unsafe { MajorFlags::from_bits_unchecked(major) }, minor, }) } } /// Ask gssapi whether it thinks the specified oid is in the /// specified set. pub fn contains(&self, id: &Oid) -> Result<bool, Error> { let mut minor = GSS_S_COMPLETE; let mut present = 0; let major = unsafe { gss_test_oid_set_member( &mut minor as *mut OM_uint32, id.to_c(), self.0, &mut present as *mut c_int, ) }; if major == GSS_S_COMPLETE { Ok(if present != 0 { true } else { false }) } else { Err(Error { major: unsafe { MajorFlags::from_bits_unchecked(major) }, minor, }) } } }
30.270718
89
0.593356
ef83966795f5e0677f98f80e859e63a6d42d5c94
8,847
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. //! Changes tries build cache. use std::collections::{HashMap, HashSet}; use crate::StorageKey; use sp_core::storage::PrefixedStorageKey; /// Changes trie build cache. /// /// Helps to avoid read of changes tries from the database when digest trie /// is built. It holds changed keys for every block (indexed by changes trie /// root) that could be referenced by future digest items. For digest entries /// it also holds keys covered by this digest. Entries for top level digests /// are never created, because they'll never be used to build other digests. /// /// Entries are pruned from the cache once digest block that is using this entry /// is inserted (because digest block will includes all keys from this entry). /// When there's a fork, entries are pruned when first changes trie is inserted. pub struct BuildCache<H, N> { /// Map of block (implies changes true) number => changes trie root. roots_by_number: HashMap<N, H>, /// Map of changes trie root => set of storage keys that are in this trie. /// The `Option<Vec<u8>>` in inner `HashMap` stands for the child storage key. /// If it is `None`, then the `HashSet` contains keys changed in top-level storage. /// If it is `Some`, then the `HashSet` contains keys changed in child storage, identified by the key. changed_keys: HashMap<H, HashMap<Option<PrefixedStorageKey>, HashSet<StorageKey>>>, } /// The action to perform when block-with-changes-trie is imported. #[derive(Debug, PartialEq)] pub enum CacheAction<H, N> { /// Cache data that has been collected when CT has been built. CacheBuildData(CachedBuildData<H, N>), /// Clear cache from all existing entries. Clear, } /// The data that has been cached during changes trie building. #[derive(Debug, PartialEq)] pub struct CachedBuildData<H, N> { block: N, trie_root: H, digest_input_blocks: Vec<N>, changed_keys: HashMap<Option<PrefixedStorageKey>, HashSet<StorageKey>>, } /// The action to perform when block-with-changes-trie is imported. #[derive(Debug, PartialEq)] pub(crate) enum IncompleteCacheAction<N> { /// Cache data that has been collected when CT has been built. CacheBuildData(IncompleteCachedBuildData<N>), /// Clear cache from all existing entries. Clear, } /// The data (without changes trie root) that has been cached during changes trie building. #[derive(Debug, PartialEq)] pub(crate) struct IncompleteCachedBuildData<N> { digest_input_blocks: Vec<N>, changed_keys: HashMap<Option<PrefixedStorageKey>, HashSet<StorageKey>>, } impl<H, N> BuildCache<H, N> where N: Eq + ::std::hash::Hash, H: Eq + ::std::hash::Hash + Clone, { /// Create new changes trie build cache. pub fn new() -> Self { BuildCache { roots_by_number: HashMap::new(), changed_keys: HashMap::new(), } } /// Get cached changed keys for changes trie with given root. pub fn get(&self, root: &H) -> Option<&HashMap<Option<PrefixedStorageKey>, HashSet<StorageKey>>> { self.changed_keys.get(&root) } /// Execute given functor with cached entry for given block. /// Returns true if the functor has been called and false otherwise. pub fn with_changed_keys( &self, root: &H, functor: &mut dyn FnMut(&HashMap<Option<PrefixedStorageKey>, HashSet<StorageKey>>), ) -> bool { match self.changed_keys.get(&root) { Some(changed_keys) => { functor(changed_keys); true }, None => false, } } /// Insert data into cache. pub fn perform(&mut self, action: CacheAction<H, N>) { match action { CacheAction::CacheBuildData(data) => { self.roots_by_number.insert(data.block, data.trie_root.clone()); self.changed_keys.insert(data.trie_root, data.changed_keys); for digest_input_block in data.digest_input_blocks { let digest_input_block_hash = self.roots_by_number.remove(&digest_input_block); if let Some(digest_input_block_hash) = digest_input_block_hash { self.changed_keys.remove(&digest_input_block_hash); } } }, CacheAction::Clear => { self.roots_by_number.clear(); self.changed_keys.clear(); }, } } } impl<N> IncompleteCacheAction<N> { /// Returns true if we need to collect changed keys for this action. pub fn collects_changed_keys(&self) -> bool { match *self { IncompleteCacheAction::CacheBuildData(_) => true, IncompleteCacheAction::Clear => false, } } /// Complete cache action with computed changes trie root. pub(crate) fn complete<H: Clone>(self, block: N, trie_root: &H) -> CacheAction<H, N> { match self { IncompleteCacheAction::CacheBuildData(build_data) => CacheAction::CacheBuildData(build_data.complete(block, trie_root.clone())), IncompleteCacheAction::Clear => CacheAction::Clear, } } /// Set numbers of blocks that are superseded by this new entry. /// /// If/when this build data is committed to the cache, entries for these blocks /// will be removed from the cache. pub(crate) fn set_digest_input_blocks(self, digest_input_blocks: Vec<N>) -> Self { match self { IncompleteCacheAction::CacheBuildData(build_data) => IncompleteCacheAction::CacheBuildData(build_data.set_digest_input_blocks(digest_input_blocks)), IncompleteCacheAction::Clear => IncompleteCacheAction::Clear, } } /// Insert changed keys of given storage into cached data. pub(crate) fn insert( self, storage_key: Option<PrefixedStorageKey>, changed_keys: HashSet<StorageKey>, ) -> Self { match self { IncompleteCacheAction::CacheBuildData(build_data) => IncompleteCacheAction::CacheBuildData(build_data.insert(storage_key, changed_keys)), IncompleteCacheAction::Clear => IncompleteCacheAction::Clear, } } } impl<N> IncompleteCachedBuildData<N> { /// Create new cached data. pub(crate) fn new() -> Self { IncompleteCachedBuildData { digest_input_blocks: Vec::new(), changed_keys: HashMap::new(), } } fn complete<H>(self, block: N, trie_root: H) -> CachedBuildData<H, N> { CachedBuildData { block, trie_root, digest_input_blocks: self.digest_input_blocks, changed_keys: self.changed_keys, } } fn set_digest_input_blocks(mut self, digest_input_blocks: Vec<N>) -> Self { self.digest_input_blocks = digest_input_blocks; self } fn insert( mut self, storage_key: Option<PrefixedStorageKey>, changed_keys: HashSet<StorageKey>, ) -> Self { self.changed_keys.insert(storage_key, changed_keys); self } } #[cfg(test)] mod tests { use super::*; #[test] fn updated_keys_are_stored_when_non_top_level_digest_is_built() { let mut data = IncompleteCachedBuildData::<u32>::new(); data = data.insert(None, vec![vec![1]].into_iter().collect()); assert_eq!(data.changed_keys.len(), 1); let mut cache = BuildCache::new(); cache.perform(CacheAction::CacheBuildData(data.complete(1, 1))); assert_eq!(cache.changed_keys.len(), 1); assert_eq!( cache.get(&1).unwrap().clone(), vec![(None, vec![vec![1]].into_iter().collect())].into_iter().collect(), ); } #[test] fn obsolete_entries_are_purged_when_new_ct_is_built() { let mut cache = BuildCache::<u32, u32>::new(); cache.perform(CacheAction::CacheBuildData(IncompleteCachedBuildData::new() .insert(None, vec![vec![1]].into_iter().collect()) .complete(1, 1))); cache.perform(CacheAction::CacheBuildData(IncompleteCachedBuildData::new() .insert(None, vec![vec![2]].into_iter().collect()) .complete(2, 2))); cache.perform(CacheAction::CacheBuildData(IncompleteCachedBuildData::new() .insert(None, vec![vec![3]].into_iter().collect()) .complete(3, 3))); assert_eq!(cache.changed_keys.len(), 3); cache.perform(CacheAction::CacheBuildData(IncompleteCachedBuildData::new() .set_digest_input_blocks(vec![1, 2, 3]) .complete(4, 4))); assert_eq!(cache.changed_keys.len(), 1); cache.perform(CacheAction::CacheBuildData(IncompleteCachedBuildData::new() .insert(None, vec![vec![8]].into_iter().collect()) .complete(8, 8))); cache.perform(CacheAction::CacheBuildData(IncompleteCachedBuildData::new() .insert(None, vec![vec![12]].into_iter().collect()) .complete(12, 12))); assert_eq!(cache.changed_keys.len(), 3); cache.perform(CacheAction::Clear); assert_eq!(cache.changed_keys.len(), 0); } }
33.134831
103
0.71821
e8a5cd141b9032b5d6948ce991895ea88d1a7c65
2,535
use caesium; use std::sync::Once; use std::fs; static INIT: Once = Once::new(); pub fn initialize(file: &str) { INIT.call_once(|| { if fs::metadata(file).is_ok() { fs::remove_file(file).unwrap(); } }); } pub fn cleanup(file: &str) { if fs::metadata(file).is_ok() { fs::remove_file(file).unwrap(); } } #[test] fn compress_20() { let output = "tests/samples/output/compressed_20.webp"; initialize(output); let mut params = caesium::initialize_parameters(); params.webp.quality = 20; caesium::compress(String::from("tests/samples/uncompressed_家.webp"), String::from(output), params) .unwrap(); assert!(std::path::Path::new(output).exists()); cleanup(output) } #[test] fn compress_50() { let output = "tests/samples/output/compressed_50.webp"; initialize(output); let mut params = caesium::initialize_parameters(); params.webp.quality = 50; caesium::compress(String::from("tests/samples/uncompressed_家.webp"), String::from(output), params) .unwrap(); assert!(std::path::Path::new(output).exists()); cleanup(output) } #[test] fn compress_80() { let output = "tests/samples/output/compressed_80.webp"; initialize(output); let mut params = caesium::initialize_parameters(); params.webp.quality = 80; caesium::compress(String::from("tests/samples/uncompressed_家.webp"), String::from(output), params) .unwrap(); assert!(std::path::Path::new(output).exists()); cleanup(output) } #[test] fn compress_100() { let output = "tests/samples/output/compressed_100.webp"; initialize(output); let mut params = caesium::initialize_parameters(); params.webp.quality = 100; caesium::compress(String::from("tests/samples/uncompressed_家.webp"), String::from(output), params) .unwrap(); assert!(std::path::Path::new(output).exists()); cleanup(output) } #[test] fn optimize() { let output = "tests/samples/output/optimized.webp"; initialize(output); let mut params = caesium::initialize_parameters(); params.optimize = true; caesium::compress(String::from("tests/samples/uncompressed_家.webp"), String::from(output), params) .unwrap(); assert!(std::path::Path::new(output).exists()); cleanup(output) }
28.166667
72
0.595661
4a2a18e488ecb253ed0eb77c740339012b9e5024
3,266
#[doc = "Reader of register EVENTS_COLLISION"] pub type R = crate::R<u32, super::EVENTS_COLLISION>; #[doc = "Writer for register EVENTS_COLLISION"] pub type W = crate::W<u32, super::EVENTS_COLLISION>; #[doc = "Register EVENTS_COLLISION `reset()`'s with value 0"] impl crate::ResetValue for super::EVENTS_COLLISION { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "NFC auto collision resolution error reported.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EVENTS_COLLISION_A { #[doc = "0: Event not generated"] NOTGENERATED, #[doc = "1: Event generated"] GENERATED, } impl From<EVENTS_COLLISION_A> for bool { #[inline(always)] fn from(variant: EVENTS_COLLISION_A) -> Self { match variant { EVENTS_COLLISION_A::NOTGENERATED => false, EVENTS_COLLISION_A::GENERATED => true, } } } #[doc = "Reader of field `EVENTS_COLLISION`"] pub type EVENTS_COLLISION_R = crate::R<bool, EVENTS_COLLISION_A>; impl EVENTS_COLLISION_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EVENTS_COLLISION_A { match self.bits { false => EVENTS_COLLISION_A::NOTGENERATED, true => EVENTS_COLLISION_A::GENERATED, } } #[doc = "Checks if the value of the field is `NOTGENERATED`"] #[inline(always)] pub fn is_not_generated(&self) -> bool { *self == EVENTS_COLLISION_A::NOTGENERATED } #[doc = "Checks if the value of the field is `GENERATED`"] #[inline(always)] pub fn is_generated(&self) -> bool { *self == EVENTS_COLLISION_A::GENERATED } } #[doc = "Write proxy for field `EVENTS_COLLISION`"] pub struct EVENTS_COLLISION_W<'a> { w: &'a mut W, } impl<'a> EVENTS_COLLISION_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EVENTS_COLLISION_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Event not generated"] #[inline(always)] pub fn not_generated(self) -> &'a mut W { self.variant(EVENTS_COLLISION_A::NOTGENERATED) } #[doc = "Event generated"] #[inline(always)] pub fn generated(self) -> &'a mut W { self.variant(EVENTS_COLLISION_A::GENERATED) } #[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 } } impl R { #[doc = "Bit 0 - NFC auto collision resolution error reported."] #[inline(always)] pub fn events_collision(&self) -> EVENTS_COLLISION_R { EVENTS_COLLISION_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 0 - NFC auto collision resolution error reported."] #[inline(always)] pub fn events_collision(&mut self) -> EVENTS_COLLISION_W { EVENTS_COLLISION_W { w: self } } }
31.104762
77
0.60992
5d85fedab83561e2ee28d103b560bbb1a6f61dc1
1,971
// 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. use common_datablocks::DataBlock; use common_datavalues::DataType; use common_datavalues::TypeSerializer; use common_exception::ErrorCode; use common_exception::Result; const FIELD_DELIMITER: u8 = b'\t'; const ROW_DELIMITER: u8 = b'\n'; pub fn block_to_tsv(block: &DataBlock) -> Result<Vec<u8>> { let rows_size = block.column(0).len(); let columns_size = block.num_columns(); let mut col_table = Vec::new(); for col_index in 0..columns_size { let column = block.column(col_index); let column = column.convert_full_column(); let field = block.schema().field(col_index); let data_type = field.data_type(); let serializer = data_type.create_serializer(); // todo(youngsofun): escape col_table.push(serializer.serialize_column(&column).map_err(|e| { ErrorCode::UnexpectedError(format!( "fail to serialize filed {}, error = {}", field.name(), e )) })?); } let mut buf = vec![]; for row_index in 0..rows_size { for col in col_table.iter().take(columns_size - 1) { buf.extend_from_slice(col[row_index].as_bytes()); buf.push(FIELD_DELIMITER); } buf.extend_from_slice(col_table[columns_size - 1][row_index].as_bytes()); buf.push(ROW_DELIMITER); } Ok(buf) }
35.836364
81
0.658549
567da10ef66aa724897163ccde71649788991f9a
753
use bytes::BytesMut; use tokio_util::codec::Decoder; use crate::IgniteError; /// A simple `Decoder` implementation for protocol messages. #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct ResponseDecoder(()); impl ResponseDecoder { /// Creates a new `ResponseDecoder` instance. #[allow(dead_code)] pub fn new() -> Self { Self(()) } } impl Decoder for ResponseDecoder { type Item = BytesMut; type Error = IgniteError; /// Decode response fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { if buf.len() > 0 { let len = buf.len(); Ok(Some(buf.split_to(len))) } else { Ok(None) } } }
23.53125
89
0.59761
f5ac75f425ddf0a8b83e17c7a67753ffbb7ae2b0
45,955
#![warn(missing_docs)] //! A macro which makes errors easy to write //! //! Minimum type is like this: //! //! ```rust //! #[macro_use] extern crate quick_error; //! # fn main() {} //! //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! Variant1 {} //! } //! } //! ``` //! Both ``pub`` and non-public types may be declared, and all meta attributes //! (such as ``#[derive(Debug)]``) are forwarded as is. The `Debug` must be //! implemented (but you may do that yourself if you like). The documentation //! comments ``/// something`` (as well as other meta attrbiutes) on variants //! are allowed. //! //! # Allowed Syntax //! //! You may add arbitrary parameters to any struct variant: //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # fn main() {} //! # //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! /// IO Error //! Io(err: std::io::Error) {} //! /// Utf8 Error //! Utf8(err: std::str::Utf8Error) {} //! } //! } //! ``` //! //! Note unlike in normal Enum declarations you declare names of fields (which //! are omitted from type). How they can be used is outlined below. //! //! Now you might have noticed trailing braces `{}`. They are used to define //! implementations. By default: //! //! * `Error::description()` returns variant name as static string //! * `Error::cause()` returns None (even if type wraps some value) //! * `Display` outputs `description()` //! * No `From` implementations are defined //! //! To define description simply add `description(value)` inside braces: //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # fn main() {} //! # //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! Io(err: std::io::Error) { //! description(err.description()) //! } //! Utf8(err: std::str::Utf8Error) { //! description("utf8 error") //! } //! } //! } //! ``` //! //! Normal rules for borrowing apply. So most of the time description either //! returns constant string or forwards description from enclosed type. //! //! To change `cause` method to return some error, add `cause(value)`, for //! example: //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # fn main() {} //! # //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! Io(err: std::io::Error) { //! cause(err) //! description(err.description()) //! } //! Utf8(err: std::str::Utf8Error) { //! description("utf8 error") //! } //! Other(err: Box<std::error::Error>) { //! cause(&**err) //! description(err.description()) //! } //! } //! } //! ``` //! Note you don't need to wrap value in `Some`, its implicit. In case you want //! `None` returned just omit the `cause`. You can't return `None` //! conditionally. //! //! To change how each clause is `Display`ed add `display(pattern,..args)`, //! for example: //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # fn main() {} //! # //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! Io(err: std::io::Error) { //! display("I/O error: {}", err) //! } //! Utf8(err: std::str::Utf8Error) { //! display("Utf8 error, valid up to {}", err.valid_up_to()) //! } //! } //! } //! ``` //! //! If you need a reference to the error when `Display`ing, you can instead use //! `display(x) -> (pattern, ..args)`, where `x` sets the name of the reference. //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # fn main() {} //! # //! use std::error::Error; // put methods like `description()` of this trait into scope //! //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! Io(err: std::io::Error) { //! display(x) -> ("{}: {}", x.description(), err) //! } //! Utf8(err: std::str::Utf8Error) { //! display(self_) -> ("{}, valid up to {}", self_.description(), err.valid_up_to()) //! } //! } //! } //! ``` //! //! To convert to the type from any other, use one of the three forms of //! `from` clause. //! //! For example, to convert simple wrapper use bare `from()`: //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # fn main() {} //! # //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! Io(err: std::io::Error) { //! from() //! } //! } //! } //! ``` //! //! This implements ``From<io::Error>``. //! //! To convert to singleton enumeration type (discarding the value), use //! the `from(type)` form: //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # fn main() {} //! # //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! FormatError { //! from(std::fmt::Error) //! } //! } //! } //! ``` //! //! And the most powerful form is `from(var: type) -> (arguments...)`. It //! might be used to convert to type with multiple arguments or for arbitrary //! value conversions: //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # fn main() {} //! # //! quick_error! { //! #[derive(Debug)] //! pub enum SomeError { //! FailedOperation(s: &'static str, errno: i32) { //! from(errno: i32) -> ("os error", errno) //! from(e: std::io::Error) -> ("io error", e.raw_os_error().unwrap()) //! } //! /// Converts from both kinds of utf8 errors //! Utf8(err: std::str::Utf8Error) { //! from() //! from(err: std::string::FromUtf8Error) -> (err.utf8_error()) //! } //! } //! } //! ``` //! # Context //! //! Since quick-error 1.1 we also have a `context` declaration, which is //! similar to (the longest form of) `from`, but allows adding some context to //! the error. We need a longer example to demonstrate this: //! //! ```rust //! # #[macro_use] extern crate quick_error; //! # use std::io; //! # use std::fs::File; //! # use std::path::{Path, PathBuf}; //! # //! use quick_error::ResultExt; //! //! quick_error! { //! #[derive(Debug)] //! pub enum Error { //! File(filename: PathBuf, err: io::Error) { //! context(path: &'a Path, err: io::Error) //! -> (path.to_path_buf(), err) //! } //! } //! } //! //! fn openfile(path: &Path) -> Result<(), Error> { //! try!(File::open(path).context(path)); //! //! // If we didn't have context, the line above would be written as; //! // //! // try!(File::open(path) //! // .map_err(|err| Error::File(path.to_path_buf(), err))); //! //! Ok(()) //! } //! //! # fn main() { //! # openfile(Path::new("/etc/somefile")).ok(); //! # } //! ``` //! //! Each `context(a: A, b: B)` clause implements //! `From<Context<A, B>> for Error`. Which means multiple `context` clauses //! are a subject to the normal coherence rules. Unfortunately, we can't //! provide full support of generics for the context, but you may either use a //! lifetime `'a` for references or `AsRef<Type>` (the latter means `A: //! AsRef<Type>`, and `Type` must be concrete). It's also occasionally useful //! to use a tuple as a type of the first argument. //! //! You also need to `use quick_error::ResultExt` extension trait to get //! working `.context()` method. //! //! More info on context in [this article](http://bit.ly/1PsuxDt). //! //! All forms of `from`, `display`, `description`, `cause`, and `context` //! clauses can be combined and put in arbitrary order. Only `from` and //! `context` can be used multiple times in single variant of enumeration. //! Docstrings are also okay. Empty braces can be omitted as of quick_error //! 0.1.3. //! //! # Private Enums //! //! Since quick-error 1.2.0 we have a way to make a private enum that is //! wrapped by public structure: //! //! ```rust //! #[macro_use] extern crate quick_error; //! # fn main() {} //! //! quick_error! { //! #[derive(Debug)] //! pub enum PubError wraps ErrorEnum { //! Variant1 {} //! } //! } //! ``` //! //! This generates data structures like this //! //! ```rust //! //! pub struct PubError(ErrorEnum); //! //! enum ErrorEnum { //! Variant1, //! } //! //! ``` //! //! Which in turn allows you to export just `PubError` in your crate and keep //! actual enumeration private to the crate. This is useful to keep backwards //! compatibility for error types. Currently there is no shorcuts to define //! error constructors for the inner type, but we consider adding some in //! future versions. //! //! It's possible to declare internal enum as public too. //! //! #![cfg_attr(all(feature = "mesalock_sgx", not(target_env = "sgx")), no_std)] #![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))] #[cfg(all(feature = "mesalock_sgx", not(target_env = "sgx")))] #[macro_use] extern crate sgx_tstd as std; /// Main macro that does all the work #[macro_export] macro_rules! quick_error { ( $(#[$meta:meta])* pub enum $name:ident { $($chunks:tt)* } ) => { quick_error!(SORT [pub enum $name $(#[$meta])* ] items [] buf [] queue [ $($chunks)* ]); }; ( $(#[$meta:meta])* enum $name:ident { $($chunks:tt)* } ) => { quick_error!(SORT [enum $name $(#[$meta])* ] items [] buf [] queue [ $($chunks)* ]); }; ( $(#[$meta:meta])* pub enum $name:ident wraps $enum_name:ident { $($chunks:tt)* } ) => { quick_error!(WRAPPER $enum_name [ pub struct ] $name $(#[$meta])*); quick_error!(SORT [enum $enum_name $(#[$meta])* ] items [] buf [] queue [ $($chunks)* ]); }; ( $(#[$meta:meta])* pub enum $name:ident wraps pub $enum_name:ident { $($chunks:tt)* } ) => { quick_error!(WRAPPER $enum_name [ pub struct ] $name $(#[$meta])*); quick_error!(SORT [pub enum $enum_name $(#[$meta])* ] items [] buf [] queue [ $($chunks)* ]); }; ( $(#[$meta:meta])* enum $name:ident wraps $enum_name:ident { $($chunks:tt)* } ) => { quick_error!(WRAPPER $enum_name [ struct ] $name $(#[$meta])*); quick_error!(SORT [enum $enum_name $(#[$meta])* ] items [] buf [] queue [ $($chunks)* ]); }; ( $(#[$meta:meta])* enum $name:ident wraps pub $enum_name:ident { $($chunks:tt)* } ) => { quick_error!(WRAPPER $enum_name [ struct ] $name $(#[$meta])*); quick_error!(SORT [pub enum $enum_name $(#[$meta])* ] items [] buf [] queue [ $($chunks)* ]); }; ( WRAPPER $internal:ident [ $($strdef:tt)* ] $strname:ident $(#[$meta:meta])* ) => { $(#[$meta])* $($strdef)* $strname ( $internal ); impl ::std::fmt::Display for $strname { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&self.0, f) } } impl From<$internal> for $strname { fn from(err: $internal) -> Self { $strname(err) } } impl ::std::error::Error for $strname { fn description(&self) -> &str { self.0.description() } fn cause(&self) -> Option<&::std::error::Error> { self.0.cause() } } }; // Queue is empty, can do the work (SORT [enum $name:ident $( #[$meta:meta] )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [ ] queue [ ] ) => { quick_error!(ENUM_DEFINITION [enum $name $( #[$meta] )*] body [] queue [$($( #[$imeta] )* => $iitem: $imode [$( $ivar: $ityp ),*] )*] ); quick_error!(IMPLEMENTATIONS $name {$( $iitem: $imode [$(#[$imeta])*] [$( $ivar: $ityp ),*] {$( $ifuncs )*} )*}); $( quick_error!(ERROR_CHECK $imode $($ifuncs)*); )* }; (SORT [pub enum $name:ident $( #[$meta:meta] )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [ ] queue [ ] ) => { quick_error!(ENUM_DEFINITION [pub enum $name $( #[$meta] )*] body [] queue [$($( #[$imeta] )* => $iitem: $imode [$( $ivar: $ityp ),*] )*] ); quick_error!(IMPLEMENTATIONS $name {$( $iitem: $imode [$(#[$imeta])*] [$( $ivar: $ityp ),*] {$( $ifuncs )*} )*}); $( quick_error!(ERROR_CHECK $imode $($ifuncs)*); )* }; // Add meta to buffer (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )*] queue [ #[$qmeta:meta] $( $tail:tt )*] ) => { quick_error!(SORT [$( $def )*] items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] buf [$( #[$bmeta] )* #[$qmeta] ] queue [$( $tail )*]); }; // Add ident to buffer (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )*] queue [ $qitem:ident $( $tail:tt )*] ) => { quick_error!(SORT [$( $def )*] items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] buf [$(#[$bmeta])* => $qitem : UNIT [ ] ] queue [$( $tail )*]); }; // Flush buffer on meta after ident (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )* => $bitem:ident: $bmode:tt [$( $bvar:ident: $btyp:ty ),*] ] queue [ #[$qmeta:meta] $( $tail:tt )*] ) => { quick_error!(SORT [$( $def )*] enum [$( $(#[$emeta])* => $eitem $(( $($etyp),* ))* )* $(#[$bmeta])* => $bitem: $bmode $(( $($btyp),* ))*] items [$($( #[$imeta:meta] )* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )* $bitem: $bmode [$( $bvar:$btyp ),*] {} ] buf [ #[$qmeta] ] queue [$( $tail )*]); }; // Add tuple enum-variant (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )* => $bitem:ident: UNIT [ ] ] queue [($( $qvar:ident: $qtyp:ty ),+) $( $tail:tt )*] ) => { quick_error!(SORT [$( $def )*] items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] buf [$( #[$bmeta] )* => $bitem: TUPLE [$( $qvar:$qtyp ),*] ] queue [$( $tail )*] ); }; // Add struct enum-variant - e.g. { descr: &'static str } (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )* => $bitem:ident: UNIT [ ] ] queue [{ $( $qvar:ident: $qtyp:ty ),+} $( $tail:tt )*] ) => { quick_error!(SORT [$( $def )*] items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] buf [$( #[$bmeta] )* => $bitem: STRUCT [$( $qvar:$qtyp ),*] ] queue [$( $tail )*]); }; // Add struct enum-variant, with excess comma - e.g. { descr: &'static str, } (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )* => $bitem:ident: UNIT [ ] ] queue [{$( $qvar:ident: $qtyp:ty ),+ ,} $( $tail:tt )*] ) => { quick_error!(SORT [$( $def )*] items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] buf [$( #[$bmeta] )* => $bitem: STRUCT [$( $qvar:$qtyp ),*] ] queue [$( $tail )*]); }; // Add braces and flush always on braces (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )* => $bitem:ident: $bmode:tt [$( $bvar:ident: $btyp:ty ),*] ] queue [ {$( $qfuncs:tt )*} $( $tail:tt )*] ) => { quick_error!(SORT [$( $def )*] items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )* $(#[$bmeta])* => $bitem: $bmode [$( $bvar:$btyp ),*] {$( $qfuncs )*} ] buf [ ] queue [$( $tail )*]); }; // Flush buffer on double ident (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )* => $bitem:ident: $bmode:tt [$( $bvar:ident: $btyp:ty ),*] ] queue [ $qitem:ident $( $tail:tt )*] ) => { quick_error!(SORT [$( $def )*] items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )* $(#[$bmeta])* => $bitem: $bmode [$( $bvar:$btyp ),*] {} ] buf [ => $qitem : UNIT [ ] ] queue [$( $tail )*]); }; // Flush buffer on end (SORT [$( $def:tt )*] items [$($( #[$imeta:meta] )* => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] {$( $ifuncs:tt )*} )* ] buf [$( #[$bmeta:meta] )* => $bitem:ident: $bmode:tt [$( $bvar:ident: $btyp:ty ),*] ] queue [ ] ) => { quick_error!(SORT [$( $def )*] items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )* $(#[$bmeta])* => $bitem: $bmode [$( $bvar:$btyp ),*] {} ] buf [ ] queue [ ]); }; // Public enum (Queue Empty) (ENUM_DEFINITION [pub enum $name:ident $( #[$meta:meta] )*] body [$($( #[$imeta:meta] )* => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] queue [ ] ) => { #[allow(unknown_lints)] // no unused_doc_comments in older rust #[allow(unused_doc_comment)] $(#[$meta])* pub enum $name { $( $(#[$imeta])* $iitem $(($( $ttyp ),*))* $({$( $svar: $styp ),*})*, )* } }; // Private enum (Queue Empty) (ENUM_DEFINITION [enum $name:ident $( #[$meta:meta] )*] body [$($( #[$imeta:meta] )* => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] queue [ ] ) => { #[allow(unknown_lints)] // no unused_doc_comments in older rust #[allow(unused_doc_comment)] $(#[$meta])* enum $name { $( $(#[$imeta])* $iitem $(($( $ttyp ),*))* $({$( $svar: $styp ),*})*, )* } }; // Unit variant (ENUM_DEFINITION [$( $def:tt )*] body [$($( #[$imeta:meta] )* => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] queue [$( #[$qmeta:meta] )* => $qitem:ident: UNIT [ ] $( $queue:tt )*] ) => { quick_error!(ENUM_DEFINITION [ $($def)* ] body [$($( #[$imeta] )* => $iitem ($(($( $ttyp ),+))*) {$({$( $svar: $styp ),*})*} )* $( #[$qmeta] )* => $qitem () {} ] queue [ $($queue)* ] ); }; // Tuple variant (ENUM_DEFINITION [$( $def:tt )*] body [$($( #[$imeta:meta] )* => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] queue [$( #[$qmeta:meta] )* => $qitem:ident: TUPLE [$( $qvar:ident: $qtyp:ty ),+] $( $queue:tt )*] ) => { quick_error!(ENUM_DEFINITION [ $($def)* ] body [$($( #[$imeta] )* => $iitem ($(($( $ttyp ),+))*) {$({$( $svar: $styp ),*})*} )* $( #[$qmeta] )* => $qitem (($( $qtyp ),*)) {} ] queue [ $($queue)* ] ); }; // Struct variant (ENUM_DEFINITION [$( $def:tt )*] body [$($( #[$imeta:meta] )* => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] queue [$( #[$qmeta:meta] )* => $qitem:ident: STRUCT [$( $qvar:ident: $qtyp:ty ),*] $( $queue:tt )*] ) => { quick_error!(ENUM_DEFINITION [ $($def)* ] body [$($( #[$imeta] )* => $iitem ($(($( $ttyp ),+))*) {$({$( $svar: $styp ),*})*} )* $( #[$qmeta] )* => $qitem () {{$( $qvar: $qtyp ),*}} ] queue [ $($queue)* ] ); }; (IMPLEMENTATIONS $name:ident {$( $item:ident: $imode:tt [$(#[$imeta:meta])*] [$( $var:ident: $typ:ty ),*] {$( $funcs:tt )*} )*} ) => { #[allow(unused)] #[allow(unknown_lints)] // no unused_doc_comments in older rust #[allow(unused_doc_comment)] impl ::std::fmt::Display for $name { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { $( $(#[$imeta])* quick_error!(ITEM_PATTERN $name $item: $imode [$( ref $var ),*] ) => { let display_fn = quick_error!(FIND_DISPLAY_IMPL $name $item: $imode {$( $funcs )*}); display_fn(self, fmt) } )* } } } #[allow(unused)] #[allow(unknown_lints)] // no unused_doc_comments in older rust #[allow(unused_doc_comment)] impl ::std::error::Error for $name { fn description(&self) -> &str { match *self { $( $(#[$imeta])* quick_error!(ITEM_PATTERN $name $item: $imode [$( ref $var ),*] ) => { quick_error!(FIND_DESCRIPTION_IMPL $item: $imode self fmt [$( $var ),*] {$( $funcs )*}) } )* } } fn cause(&self) -> Option<&::std::error::Error> { match *self { $( $(#[$imeta])* quick_error!(ITEM_PATTERN $name $item: $imode [$( ref $var ),*] ) => { quick_error!(FIND_CAUSE_IMPL $item: $imode [$( $var ),*] {$( $funcs )*}) } )* } } } $( quick_error!(FIND_FROM_IMPL $name $item: $imode [$( $var:$typ ),*] {$( $funcs )*}); )* $( quick_error!(FIND_CONTEXT_IMPL $name $item: $imode [$( $var:$typ ),*] {$( $funcs )*}); )* }; (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt { display($self_:tt) -> ($( $exprs:tt )*) $( $tail:tt )*} ) => { |quick_error!(IDENT $self_): &$name, f: &mut ::std::fmt::Formatter| { write!(f, $( $exprs )*) } }; (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt { display($pattern:expr) $( $tail:tt )*} ) => { |_, f: &mut ::std::fmt::Formatter| { write!(f, $pattern) } }; (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt { display($pattern:expr, $( $exprs:tt )*) $( $tail:tt )*} ) => { |_, f: &mut ::std::fmt::Formatter| { write!(f, $pattern, $( $exprs )*) } }; (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt { $t:tt $( $tail:tt )*} ) => { quick_error!(FIND_DISPLAY_IMPL $name $item: $imode {$( $tail )*}) }; (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt { } ) => { |self_: &$name, f: &mut ::std::fmt::Formatter| { write!(f, "{}", ::std::error::Error::description(self_)) } }; (FIND_DESCRIPTION_IMPL $item:ident: $imode:tt $me:ident $fmt:ident [$( $var:ident ),*] { description($expr:expr) $( $tail:tt )*} ) => { $expr }; (FIND_DESCRIPTION_IMPL $item:ident: $imode:tt $me:ident $fmt:ident [$( $var:ident ),*] { $t:tt $( $tail:tt )*} ) => { quick_error!(FIND_DESCRIPTION_IMPL $item: $imode $me $fmt [$( $var ),*] {$( $tail )*}) }; (FIND_DESCRIPTION_IMPL $item:ident: $imode:tt $me:ident $fmt:ident [$( $var:ident ),*] { } ) => { stringify!($item) }; (FIND_CAUSE_IMPL $item:ident: $imode:tt [$( $var:ident ),*] { cause($expr:expr) $( $tail:tt )*} ) => { Some($expr) }; (FIND_CAUSE_IMPL $item:ident: $imode:tt [$( $var:ident ),*] { $t:tt $( $tail:tt )*} ) => { quick_error!(FIND_CAUSE_IMPL $item: $imode [$( $var ),*] { $($tail)* }) }; (FIND_CAUSE_IMPL $item:ident: $imode:tt [$( $var:ident ),*] { } ) => { None }; // ----------------------------- FROM IMPL -------------------------- (FIND_FROM_IMPL $name:ident $item:ident: $imode:tt [$( $var:ident: $typ:ty ),*] { from() $( $tail:tt )*} ) => { $( impl From<$typ> for $name { fn from($var: $typ) -> $name { $name::$item($var) } } )* quick_error!(FIND_FROM_IMPL $name $item: $imode [$( $var:$typ ),*] {$( $tail )*}); }; (FIND_FROM_IMPL $name:ident $item:ident: UNIT [ ] { from($ftyp:ty) $( $tail:tt )*} ) => { impl From<$ftyp> for $name { fn from(_discarded_error: $ftyp) -> $name { $name::$item } } quick_error!(FIND_FROM_IMPL $name $item: UNIT [ ] {$( $tail )*}); }; (FIND_FROM_IMPL $name:ident $item:ident: TUPLE [$( $var:ident: $typ:ty ),*] { from($fvar:ident: $ftyp:ty) -> ($( $texpr:expr ),*) $( $tail:tt )*} ) => { impl From<$ftyp> for $name { fn from($fvar: $ftyp) -> $name { $name::$item($( $texpr ),*) } } quick_error!(FIND_FROM_IMPL $name $item: TUPLE [$( $var:$typ ),*] { $($tail)* }); }; (FIND_FROM_IMPL $name:ident $item:ident: STRUCT [$( $var:ident: $typ:ty ),*] { from($fvar:ident: $ftyp:ty) -> {$( $tvar:ident: $texpr:expr ),*} $( $tail:tt )*} ) => { impl From<$ftyp> for $name { fn from($fvar: $ftyp) -> $name { $name::$item { $( $tvar: $texpr ),* } } } quick_error!(FIND_FROM_IMPL $name $item: STRUCT [$( $var:$typ ),*] { $($tail)* }); }; (FIND_FROM_IMPL $name:ident $item:ident: $imode:tt [$( $var:ident: $typ:ty ),*] { $t:tt $( $tail:tt )*} ) => { quick_error!(FIND_FROM_IMPL $name $item: $imode [$( $var:$typ ),*] {$( $tail )*} ); }; (FIND_FROM_IMPL $name:ident $item:ident: $imode:tt [$( $var:ident: $typ:ty ),*] { } ) => { }; // ----------------------------- CONTEXT IMPL -------------------------- (FIND_CONTEXT_IMPL $name:ident $item:ident: TUPLE [$( $var:ident: $typ:ty ),*] { context($cvar:ident: AsRef<$ctyp:ty>, $fvar:ident: $ftyp:ty) -> ($( $texpr:expr ),*) $( $tail:tt )* } ) => { impl<T: AsRef<$ctyp>> From<$crate::Context<T, $ftyp>> for $name { fn from( $crate::Context($cvar, $fvar): $crate::Context<T, $ftyp>) -> $name { $name::$item($( $texpr ),*) } } quick_error!(FIND_CONTEXT_IMPL $name $item: TUPLE [$( $var:$typ ),*] { $($tail)* }); }; (FIND_CONTEXT_IMPL $name:ident $item:ident: TUPLE [$( $var:ident: $typ:ty ),*] { context($cvar:ident: $ctyp:ty, $fvar:ident: $ftyp:ty) -> ($( $texpr:expr ),*) $( $tail:tt )* } ) => { impl<'a> From<$crate::Context<$ctyp, $ftyp>> for $name { fn from( $crate::Context($cvar, $fvar): $crate::Context<$ctyp, $ftyp>) -> $name { $name::$item($( $texpr ),*) } } quick_error!(FIND_CONTEXT_IMPL $name $item: TUPLE [$( $var:$typ ),*] { $($tail)* }); }; (FIND_CONTEXT_IMPL $name:ident $item:ident: STRUCT [$( $var:ident: $typ:ty ),*] { context($cvar:ident: AsRef<$ctyp:ty>, $fvar:ident: $ftyp:ty) -> {$( $tvar:ident: $texpr:expr ),*} $( $tail:tt )* } ) => { impl<T: AsRef<$ctyp>> From<$crate::Context<T, $ftyp>> for $name { fn from( $crate::Context($cvar, $fvar): $crate::Context<$ctyp, $ftyp>) -> $name { $name::$item { $( $tvar: $texpr ),* } } } quick_error!(FIND_CONTEXT_IMPL $name $item: STRUCT [$( $var:$typ ),*] { $($tail)* }); }; (FIND_CONTEXT_IMPL $name:ident $item:ident: STRUCT [$( $var:ident: $typ:ty ),*] { context($cvar:ident: $ctyp:ty, $fvar:ident: $ftyp:ty) -> {$( $tvar:ident: $texpr:expr ),*} $( $tail:tt )* } ) => { impl<'a> From<$crate::Context<$ctyp, $ftyp>> for $name { fn from( $crate::Context($cvar, $fvar): $crate::Context<$ctyp, $ftyp>) -> $name { $name::$item { $( $tvar: $texpr ),* } } } quick_error!(FIND_CONTEXT_IMPL $name $item: STRUCT [$( $var:$typ ),*] { $($tail)* }); }; (FIND_CONTEXT_IMPL $name:ident $item:ident: $imode:tt [$( $var:ident: $typ:ty ),*] { $t:tt $( $tail:tt )*} ) => { quick_error!(FIND_CONTEXT_IMPL $name $item: $imode [$( $var:$typ ),*] {$( $tail )*} ); }; (FIND_CONTEXT_IMPL $name:ident $item:ident: $imode:tt [$( $var:ident: $typ:ty ),*] { } ) => { }; // ----------------------------- ITEM IMPL -------------------------- (ITEM_BODY $(#[$imeta:meta])* $item:ident: UNIT ) => { }; (ITEM_BODY $(#[$imeta:meta])* $item:ident: TUPLE [$( $typ:ty ),*] ) => { ($( $typ ),*) }; (ITEM_BODY $(#[$imeta:meta])* $item:ident: STRUCT [$( $var:ident: $typ:ty ),*] ) => { {$( $var:$typ ),*} }; (ITEM_PATTERN $name:ident $item:ident: UNIT [] ) => { $name::$item }; (ITEM_PATTERN $name:ident $item:ident: TUPLE [$( ref $var:ident ),*] ) => { $name::$item ($( ref $var ),*) }; (ITEM_PATTERN $name:ident $item:ident: STRUCT [$( ref $var:ident ),*] ) => { $name::$item {$( ref $var ),*} }; // This one should match all allowed sequences in "funcs" but not match // anything else. // This is to contrast FIND_* clauses which just find stuff they need and // skip everything else completely (ERROR_CHECK $imode:tt display($self_:tt) -> ($( $exprs:tt )*) $( $tail:tt )*) => { quick_error!(ERROR_CHECK $imode $($tail)*); }; (ERROR_CHECK $imode:tt display($pattern: expr) $( $tail:tt )*) => { quick_error!(ERROR_CHECK $imode $($tail)*); }; (ERROR_CHECK $imode:tt display($pattern: expr, $( $exprs:tt )*) $( $tail:tt )*) => { quick_error!(ERROR_CHECK $imode $($tail)*); }; (ERROR_CHECK $imode:tt description($expr:expr) $( $tail:tt )*) => { quick_error!(ERROR_CHECK $imode $($tail)*); }; (ERROR_CHECK $imode:tt cause($expr:expr) $($tail:tt)*) => { quick_error!(ERROR_CHECK $imode $($tail)*); }; (ERROR_CHECK $imode:tt from() $($tail:tt)*) => { quick_error!(ERROR_CHECK $imode $($tail)*); }; (ERROR_CHECK $imode:tt from($ftyp:ty) $($tail:tt)*) => { quick_error!(ERROR_CHECK $imode $($tail)*); }; (ERROR_CHECK TUPLE from($fvar:ident: $ftyp:ty) -> ($( $e:expr ),*) $( $tail:tt )*) => { quick_error!(ERROR_CHECK TUPLE $($tail)*); }; (ERROR_CHECK STRUCT from($fvar:ident: $ftyp:ty) -> {$( $v:ident: $e:expr ),*} $( $tail:tt )*) => { quick_error!(ERROR_CHECK STRUCT $($tail)*); }; (ERROR_CHECK TUPLE context($cvar:ident: $ctyp:ty, $fvar:ident: $ftyp:ty) -> ($( $e:expr ),*) $( $tail:tt )*) => { quick_error!(ERROR_CHECK TUPLE $($tail)*); }; (ERROR_CHECK STRUCT context($cvar:ident: $ctyp:ty, $fvar:ident: $ftyp:ty) -> {$( $v:ident: $e:expr ),*} $( $tail:tt )*) => { quick_error!(ERROR_CHECK STRUCT $($tail)*); }; (ERROR_CHECK $imode:tt ) => {}; // Utility functions (IDENT $ident:ident) => { $ident } } /// Generic context type /// /// Used mostly as a transport for `ResultExt::context` method #[derive(Debug)] pub struct Context<X, E>(pub X, pub E); /// Result extension trait adding a `context` method pub trait ResultExt<T, E> { /// The method is use to add context information to current operation /// /// The context data is then used in error constructor to store additional /// information within error. For example, you may add a filename as a /// context for file operation. See crate documentation for the actual /// example. fn context<X>(self, x: X) -> Result<T, Context<X, E>>; } impl<T, E> ResultExt<T, E> for Result<T, E> { fn context<X>(self, x: X) -> Result<T, Context<X, E>> { self.map_err(|e| Context(x, e)) } } #[cfg(feature = "enclave_unit_test")] extern crate crates_unittest; #[cfg(feature = "enclave_unit_test")] pub mod tests { use std::num::{ParseFloatError, ParseIntError}; use std::str::Utf8Error; use std::string::FromUtf8Error; use std::error::Error; use std::path::{Path, PathBuf}; use std::prelude::v1::*; use crates_unittest::{ test_case, run_inventory_tests }; use super::ResultExt; pub fn run_tests() { run_inventory_tests!(); } quick_error! { #[derive(Debug)] pub enum Bare { One Two } } #[test_case] fn bare_item_direct() { assert_eq!(format!("{}", Bare::One), "One".to_string()); assert_eq!(format!("{:?}", Bare::One), "One".to_string()); assert_eq!(Bare::One.description(), "One".to_string()); assert!(Bare::One.cause().is_none()); } #[test_case] fn bare_item_trait() { let err: &Error = &Bare::Two; assert_eq!(format!("{}", err), "Two".to_string()); assert_eq!(format!("{:?}", err), "Two".to_string()); assert_eq!(err.description(), "Two".to_string()); assert!(err.cause().is_none()); } quick_error! { #[derive(Debug)] pub enum Wrapper wraps Wrapped { One Two(s: String) { display("two: {}", s) from() } } } #[test_case] fn wrapper() { assert_eq!(format!("{}", Wrapper::from(Wrapped::One)), "One".to_string()); assert_eq!(format!("{}", Wrapper::from(Wrapped::from(String::from("hello")))), "two: hello".to_string()); assert_eq!(format!("{:?}", Wrapper::from(Wrapped::One)), "Wrapper(One)".to_string()); assert_eq!(Wrapper::from(Wrapped::One).description(), "One".to_string()); } quick_error! { #[derive(Debug, PartialEq)] pub enum TupleWrapper { /// ParseFloat Error ParseFloatError(err: ParseFloatError) { from() description(err.description()) display("parse float error: {err}", err=err) cause(err) } Other(descr: &'static str) { description(descr) display("Error: {}", descr) } /// FromUtf8 Error FromUtf8Error(err: Utf8Error, source: Vec<u8>) { cause(err) display(me) -> ("{desc} at index {pos}: {err}", desc=me.description(), pos=err.valid_up_to(), err=err) description("utf8 error") from(err: FromUtf8Error) -> (err.utf8_error().clone(), err.into_bytes()) } Discard { from(&'static str) } Singleton { display("Just a string") } } } #[test_case] fn tuple_wrapper_err() { let cause = "one and a half times pi".parse::<f32>().unwrap_err(); let err = TupleWrapper::ParseFloatError(cause.clone()); assert_eq!(format!("{}", err), format!("parse float error: {}", cause)); assert_eq!(format!("{:?}", err), format!("ParseFloatError({:?})", cause)); assert_eq!(err.description(), cause.description()); assert_eq!(format!("{:?}", err.cause().unwrap()), format!("{:?}", cause)); } #[test_case] fn tuple_wrapper_trait_str() { let desc = "hello"; let err: &Error = &TupleWrapper::Other(desc); assert_eq!(format!("{}", err), format!("Error: {}", desc)); assert_eq!(format!("{:?}", err), format!("Other({:?})", desc)); assert_eq!(err.description(), desc); assert!(err.cause().is_none()); } #[test_case] fn tuple_wrapper_trait_two_fields() { let invalid_utf8: Vec<u8> = vec![0, 159, 146, 150]; let cause = String::from_utf8(invalid_utf8.clone()).unwrap_err().utf8_error(); let err: &Error = &TupleWrapper::FromUtf8Error(cause.clone(), invalid_utf8.clone()); assert_eq!(format!("{}", err), format!("{desc} at index {pos}: {cause}", desc=err.description(), pos=cause.valid_up_to(), cause=cause)); assert_eq!(format!("{:?}", err), format!("FromUtf8Error({:?}, {:?})", cause, invalid_utf8)); assert_eq!(err.description(), "utf8 error"); assert_eq!(format!("{:?}", err.cause().unwrap()), format!("{:?}", cause)); } #[test_case] fn tuple_wrapper_from() { let cause = "one and a half times pi".parse::<f32>().unwrap_err(); let err = TupleWrapper::ParseFloatError(cause.clone()); let err_from: TupleWrapper = From::from(cause); assert_eq!(err_from, err); } #[test_case] fn tuple_wrapper_custom_from() { let invalid_utf8: Vec<u8> = vec![0, 159, 146, 150]; let cause = String::from_utf8(invalid_utf8.clone()).unwrap_err(); let err = TupleWrapper::FromUtf8Error(cause.utf8_error().clone(), invalid_utf8); let err_from: TupleWrapper = From::from(cause); assert_eq!(err_from, err); } #[test_case] fn tuple_wrapper_discard() { let err: TupleWrapper = From::from("hello"); assert_eq!(format!("{}", err), format!("Discard")); assert_eq!(format!("{:?}", err), format!("Discard")); assert_eq!(err.description(), "Discard"); assert!(err.cause().is_none()); } #[test_case] fn tuple_wrapper_singleton() { let err: TupleWrapper = TupleWrapper::Singleton; assert_eq!(format!("{}", err), format!("Just a string")); assert_eq!(format!("{:?}", err), format!("Singleton")); assert_eq!(err.description(), "Singleton"); assert!(err.cause().is_none()); } quick_error! { #[derive(Debug, PartialEq)] pub enum StructWrapper { // Utf8 Error Utf8Error{ err: Utf8Error, hint: Option<&'static str> } { cause(err) display(me) -> ("{desc} at index {pos}: {err}", desc=me.description(), pos=err.valid_up_to(), err=err) description("utf8 error") from(err: Utf8Error) -> { err: err, hint: None } } // Utf8 Error ExcessComma { descr: &'static str, } { description(descr) display("Error: {}", descr) } } } #[test_case] fn struct_wrapper_err() { let invalid_utf8: Vec<u8> = vec![0, 159, 146, 150]; let cause = String::from_utf8(invalid_utf8.clone()).unwrap_err().utf8_error(); let err: &Error = &StructWrapper::Utf8Error{ err: cause.clone(), hint: Some("nonsense") }; assert_eq!(format!("{}", err), format!("{desc} at index {pos}: {cause}", desc=err.description(), pos=cause.valid_up_to(), cause=cause)); assert_eq!(format!("{:?}", err), format!("Utf8Error {{ err: {:?}, hint: {:?} }}", cause, Some("nonsense"))); assert_eq!(err.description(), "utf8 error"); assert_eq!(format!("{:?}", err.cause().unwrap()), format!("{:?}", cause)); } #[test_case] fn struct_wrapper_struct_from() { let invalid_utf8: Vec<u8> = vec![0, 159, 146, 150]; let cause = String::from_utf8(invalid_utf8.clone()).unwrap_err().utf8_error(); let err = StructWrapper::Utf8Error{ err: cause.clone(), hint: None }; let err_from: StructWrapper = From::from(cause); assert_eq!(err_from, err); } #[test_case] fn struct_wrapper_excess_comma() { let descr = "hello"; let err = StructWrapper::ExcessComma { descr: descr }; assert_eq!(format!("{}", err), format!("Error: {}", descr)); assert_eq!(format!("{:?}", err), format!("ExcessComma {{ descr: {:?} }}", descr)); assert_eq!(err.description(), descr); assert!(err.cause().is_none()); } quick_error! { #[derive(Debug)] pub enum ContextErr { Float(src: String, err: ParseFloatError) { context(s: &'a str, e: ParseFloatError) -> (s.to_string(), e) display("Float error {:?}: {}", src, err) } Int { src: String, err: ParseIntError } { context(s: &'a str, e: ParseIntError) -> {src: s.to_string(), err: e} display("Int error {:?}: {}", src, err) } Utf8(path: PathBuf, err: Utf8Error) { context(p: AsRef<Path>, e: Utf8Error) -> (p.as_ref().to_path_buf(), e) display("Path error at {:?}: {}", path, err) } Utf8Str(s: String, err: ::std::io::Error) { context(s: AsRef<str>, e: ::std::io::Error) -> (s.as_ref().to_string(), e) display("Str error {:?}: {}", s, err) } } } #[test_case] fn parse_float_error() { fn parse_float(s: &str) -> Result<f32, ContextErr> { Ok(try!(s.parse().context(s))) } assert_eq!(format!("{}", parse_float("12ab").unwrap_err()), r#"Float error "12ab": invalid float literal"#); } #[test_case] fn parse_int_error() { fn parse_int(s: &str) -> Result<i32, ContextErr> { Ok(try!(s.parse().context(s))) } assert_eq!(format!("{}", parse_int("12.5").unwrap_err()), r#"Int error "12.5": invalid digit found in string"#); } #[test_case] fn debug_context() { fn parse_int(s: &str) -> i32 { s.parse().context(s).unwrap() } assert_eq!(parse_int("12"), 12); assert_eq!(format!("{:?}", "x".parse::<i32>().context("x")), r#"Err(Context("x", ParseIntError { kind: InvalidDigit }))"#); } #[test_case] fn path_context() { fn parse_utf<P: AsRef<Path>>(s: &[u8], p: P) -> Result<(), ContextErr> { try!(::std::str::from_utf8(s).context(p)); Ok(()) } let etext = parse_utf(b"a\x80\x80", "/etc").unwrap_err().to_string(); assert!(etext.starts_with( "Path error at \"/etc\": invalid utf-8")); let etext = parse_utf(b"\x80\x80", PathBuf::from("/tmp")).unwrap_err() .to_string(); assert!(etext.starts_with( "Path error at \"/tmp\": invalid utf-8")); } #[test_case] fn conditional_compilation() { quick_error! { #[allow(dead_code)] #[derive(Debug)] pub enum Test { #[cfg(feature = "foo")] Variant } } } }
34.946768
144
0.460298
719d260cbc205f1318726b91ecf5267ddb4c228f
9,921
use clap::{crate_description, crate_name, App, Arg, ArgMatches}; use solana_faucet::faucet::FAUCET_PORT; use solana_sdk::fee_calculator::FeeRateGovernor; use solana_sdk::signature::{read_keypair_file, Keypair}; use std::{net::SocketAddr, process::exit, time::Duration}; const NUM_LAMPORTS_PER_ACCOUNT_DEFAULT: u64 = solana_sdk::native_token::LAMPORTS_PER_SOL; /// Holds the configuration for a single run of the benchmark pub struct Config { pub entrypoint_addr: SocketAddr, pub faucet_addr: SocketAddr, pub id: Keypair, pub threads: usize, pub num_nodes: usize, pub duration: Duration, pub tx_count: usize, pub keypair_multiplier: usize, pub thread_batch_sleep_ms: usize, pub sustained: bool, pub client_ids_and_stake_file: String, pub write_to_client_file: bool, pub read_from_client_file: bool, pub target_lamports_per_signature: u64, pub multi_client: bool, pub use_move: bool, pub num_lamports_per_account: u64, pub target_slots_per_epoch: u64, } impl Default for Config { fn default() -> Config { Config { entrypoint_addr: SocketAddr::from(([127, 0, 0, 1], 8001)), faucet_addr: SocketAddr::from(([127, 0, 0, 1], FAUCET_PORT)), id: Keypair::new(), threads: 4, num_nodes: 1, duration: Duration::new(std::u64::MAX, 0), tx_count: 50_000, keypair_multiplier: 8, thread_batch_sleep_ms: 1000, sustained: false, client_ids_and_stake_file: String::new(), write_to_client_file: false, read_from_client_file: false, target_lamports_per_signature: FeeRateGovernor::default().target_lamports_per_signature, multi_client: true, use_move: false, num_lamports_per_account: NUM_LAMPORTS_PER_ACCOUNT_DEFAULT, target_slots_per_epoch: 0, } } } /// Defines and builds the CLI args for a run of the benchmark pub fn build_args<'a, 'b>(version: &'b str) -> App<'a, 'b> { App::new(crate_name!()).about(crate_description!()) .version(version) .arg( Arg::with_name("entrypoint") .short("n") .long("entrypoint") .value_name("HOST:PORT") .takes_value(true) .help("Rendezvous with the cluster at this entry point; defaults to 127.0.0.1:8001"), ) .arg( Arg::with_name("faucet") .short("d") .long("faucet") .value_name("HOST:PORT") .takes_value(true) .help("Location of the faucet; defaults to entrypoint:FAUCET_PORT"), ) .arg( Arg::with_name("identity") .short("i") .long("identity") .value_name("PATH") .takes_value(true) .help("File containing a client identity (keypair)"), ) .arg( Arg::with_name("num-nodes") .short("N") .long("num-nodes") .value_name("NUM") .takes_value(true) .help("Wait for NUM nodes to converge"), ) .arg( Arg::with_name("threads") .short("t") .long("threads") .value_name("NUM") .takes_value(true) .help("Number of threads"), ) .arg( Arg::with_name("duration") .long("duration") .value_name("SECS") .takes_value(true) .help("Seconds to run benchmark, then exit; default is forever"), ) .arg( Arg::with_name("sustained") .long("sustained") .help("Use sustained performance mode vs. peak mode. This overlaps the tx generation with transfers."), ) .arg( Arg::with_name("use-move") .long("use-move") .help("Use Move language transactions to perform transfers."), ) .arg( Arg::with_name("no-multi-client") .long("no-multi-client") .help("Disable multi-client support, only transact with the entrypoint."), ) .arg( Arg::with_name("tx_count") .long("tx_count") .value_name("NUM") .takes_value(true) .help("Number of transactions to send per batch") ) .arg( Arg::with_name("keypair_multiplier") .long("keypair-multiplier") .value_name("NUM") .takes_value(true) .help("Multiply by transaction count to determine number of keypairs to create") ) .arg( Arg::with_name("thread-batch-sleep-ms") .short("z") .long("thread-batch-sleep-ms") .value_name("NUM") .takes_value(true) .help("Per-thread-per-iteration sleep in ms"), ) .arg( Arg::with_name("write-client-keys") .long("write-client-keys") .value_name("FILENAME") .takes_value(true) .help("Generate client keys and stakes and write the list to YAML file"), ) .arg( Arg::with_name("read-client-keys") .long("read-client-keys") .value_name("FILENAME") .takes_value(true) .help("Read client keys and stakes from the YAML file"), ) .arg( Arg::with_name("target_lamports_per_signature") .long("target-lamports-per-signature") .value_name("LAMPORTS") .takes_value(true) .help( "The cost in lamports that the cluster will charge for signature \ verification when the cluster is operating at target-signatures-per-slot", ), ) .arg( Arg::with_name("num_lamports_per_account") .long("num-lamports-per-account") .value_name("LAMPORTS") .takes_value(true) .help( "Number of lamports per account.", ), ) .arg( Arg::with_name("target_slots_per_epoch") .long("target-slots-per-epoch") .value_name("SLOTS") .takes_value(true) .help( "Wait until epochs are this many slots long.", ), ) } /// Parses a clap `ArgMatches` structure into a `Config` /// # Arguments /// * `matches` - command line arguments parsed by clap /// # Panics /// Panics if there is trouble parsing any of the arguments pub fn extract_args<'a>(matches: &ArgMatches<'a>) -> Config { let mut args = Config::default(); if let Some(addr) = matches.value_of("entrypoint") { args.entrypoint_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| { eprintln!("failed to parse entrypoint address: {}", e); exit(1) }); } if let Some(addr) = matches.value_of("faucet") { args.faucet_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| { eprintln!("failed to parse faucet address: {}", e); exit(1) }); } if matches.is_present("identity") { args.id = read_keypair_file(matches.value_of("identity").unwrap()) .expect("can't read client identity"); } if let Some(t) = matches.value_of("threads") { args.threads = t.to_string().parse().expect("can't parse threads"); } if let Some(n) = matches.value_of("num-nodes") { args.num_nodes = n.to_string().parse().expect("can't parse num-nodes"); } if let Some(duration) = matches.value_of("duration") { args.duration = Duration::new( duration.to_string().parse().expect("can't parse duration"), 0, ); } if let Some(s) = matches.value_of("tx_count") { args.tx_count = s.to_string().parse().expect("can't parse tx_count"); } if let Some(s) = matches.value_of("keypair_multiplier") { args.keypair_multiplier = s .to_string() .parse() .expect("can't parse keypair-multiplier"); assert!(args.keypair_multiplier >= 2); } if let Some(t) = matches.value_of("thread-batch-sleep-ms") { args.thread_batch_sleep_ms = t .to_string() .parse() .expect("can't parse thread-batch-sleep-ms"); } args.sustained = matches.is_present("sustained"); if let Some(s) = matches.value_of("write-client-keys") { args.write_to_client_file = true; args.client_ids_and_stake_file = s.to_string(); } if let Some(s) = matches.value_of("read-client-keys") { assert!(!args.write_to_client_file); args.read_from_client_file = true; args.client_ids_and_stake_file = s.to_string(); } if let Some(v) = matches.value_of("target_lamports_per_signature") { args.target_lamports_per_signature = v.to_string().parse().expect("can't parse lamports"); } args.use_move = matches.is_present("use-move"); args.multi_client = !matches.is_present("no-multi-client"); if let Some(v) = matches.value_of("num_lamports_per_account") { args.num_lamports_per_account = v.to_string().parse().expect("can't parse lamports"); } if let Some(t) = matches.value_of("target_slots_per_epoch") { args.target_slots_per_epoch = t .to_string() .parse() .expect("can't parse target slots per epoch"); } args }
35.180851
119
0.550953
d64266480d56795fbf743f38bee98dd67b3c1427
580
#![feature(unsize)] #![feature(coerce_unsized)] use std::marker::Unsize; use std::ops::CoerceUnsized; use std::ptr; struct MyPtr<T: ?Sized>(*const T); impl<T: Unsize<U> + ?Sized, U: ?Sized> CoerceUnsized<MyPtr<U>> for MyPtr<T> {} #[cfg_attr(crux, crux_test)] fn crux_test() -> (i32, i32) { let a = [1, 2]; let arr_ptr = MyPtr(&a as *const [i32; 2]); // This cast requires CoerceUnsized let slice_ptr = arr_ptr as MyPtr<[i32]>; let ptr = slice_ptr.0 as *const i32; unsafe { (*ptr, *ptr.offset(1)) } } pub fn main() { println!("{:?}", crux_test()); }
25.217391
78
0.613793
72072ff5a62904f4559177d21250ab8a8031c174
2,749
/* * Copyright © 2021 Peter M. Stahl [email protected] * * 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 expressed or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use assert_cmd::prelude::*; use indoc::indoc; use predicates::prelude::*; use std::process::Command; #[test] fn succeeds_with_character_search_option() { let mut chr = init_command(); chr.args(&["--no-paging", "Ä", "@", "$", "ß", "!"]); chr.assert() .success() .stdout(predicate::str::contains(indoc!( " 1. ! U+0021 EXCLAMATION MARK Basic Latin Other Punctuation since 1.1 2. $ U+0024 DOLLAR SIGN Basic Latin Currency Sign since 1.1 3. @ U+0040 COMMERCIAL AT Basic Latin Other Punctuation since 1.1 4. Ä U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS Latin-1 Supplement Uppercase Letter since 1.1 5. ß U+00DF LATIN SMALL LETTER SHARP S Latin-1 Supplement Lowercase Letter since 1.1 " ))); } #[test] fn succeeds_with_name_search_option() { let mut chr = init_command(); chr.args(&["--no-paging", "--name", "honey"]); chr.assert() .success() .stdout(predicate::str::contains(indoc!( " 1. 🍯 U+1F36F HONEY POT Miscellaneous Symbols and Pictographs Other Symbol since 6.0 2. 🐝 U+1F41D HONEYBEE Miscellaneous Symbols and Pictographs Other Symbol since 6.0 " ))); } #[test] fn fails_with_string_instead_of_chars() { let mut chr = init_command(); chr.args(&["Ä@"]); chr.assert().failure().stderr(predicate::str::contains( "Invalid value for '<CHARS>...': too many characters in string", )); } #[test] fn fails_with_both_character_and_name_search_option() { let mut chr = init_command(); chr.args(&["Ä@", "--name", "honey"]); chr.assert().failure().stderr(predicate::str::contains( "error: The argument '--name <NAME>' cannot be used with 'chars'", )); } fn init_command() -> Command { Command::cargo_bin("chr").unwrap() }
27.49
77
0.581666
d9ead82c5d56741f3f8fb65dde2154b7f26f7c3b
486
use specs::prelude::*; use crate::ecs::components::*; pub fn move_randomly(ecs: &mut World, entity: Entity, duration: usize) { if !ecs.entities().is_alive(entity) { error!( "Entity {:?} cannot move because it is no longer alive.", entity ); return; } ecs.write_storage::<WantsToMove>() .insert(entity, WantsToMove::Randomly { duration }) .expect(format!("Could not move {:?} randomly.", entity).as_str()); }
28.588235
75
0.584362
3a184a1fcb61cdd2d6e0dff2dde153f4bcd79f46
4,565
use std::sync::Arc; use bonsaidb_core::{ custom_api::{CustomApi, CustomApiResult}, networking::{Payload, Response}, }; use bonsaidb_utils::fast_async_lock; use flume::Receiver; use futures::{ stream::{SplitSink, SplitStream}, SinkExt, StreamExt, }; use tokio::net::TcpStream; use tokio_tungstenite::{tungstenite::Message, MaybeTlsStream, WebSocketStream}; use url::Url; use super::{CustomApiCallback, PendingRequest}; use crate::{ client::{OutstandingRequestMapHandle, SubscriberMap}, Error, }; pub async fn reconnecting_client_loop<A: CustomApi>( url: Url, protocol_version: &str, request_receiver: Receiver<PendingRequest<A>>, custom_api_callback: Option<Arc<dyn CustomApiCallback<A>>>, subscribers: SubscriberMap, ) -> Result<(), Error<A::Error>> { while let Ok(request) = { subscribers.clear().await; request_receiver.recv_async().await } { let (stream, _) = match tokio_tungstenite::connect_async( tokio_tungstenite::tungstenite::handshake::client::Request::get(url.as_str()) .header("Sec-WebSocket-Protocol", protocol_version) .body(()) .unwrap(), ) .await { Ok(result) => result, Err(err) => { drop(request.responder.send(Err(Error::from(err)))); continue; } }; let (mut sender, receiver) = stream.split(); let outstanding_requests = OutstandingRequestMapHandle::default(); { let mut outstanding_requests = fast_async_lock!(outstanding_requests); if let Err(err) = sender .send(Message::Binary(bincode::serialize(&request.request)?)) .await { drop(request.responder.send(Err(Error::from(err)))); continue; } outstanding_requests.insert( request.request.id.expect("all requests must have ids"), request, ); } if let Err(err) = tokio::try_join!( request_sender(&request_receiver, sender, outstanding_requests.clone()), response_processor( receiver, outstanding_requests.clone(), custom_api_callback.as_deref(), subscribers.clone() ) ) { // Our socket was disconnected, clear the outstanding requests before returning. let mut outstanding_requests = fast_async_lock!(outstanding_requests); for (_, pending) in outstanding_requests.drain() { drop(pending.responder.send(Err(Error::Disconnected))); } log::error!("Error on socket {:?}", err); } } Ok(()) } async fn request_sender<Api: CustomApi>( request_receiver: &Receiver<PendingRequest<Api>>, mut sender: SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>, outstanding_requests: OutstandingRequestMapHandle<Api>, ) -> Result<(), Error<Api::Error>> { while let Ok(pending) = request_receiver.recv_async().await { let mut outstanding_requests = fast_async_lock!(outstanding_requests); sender .send(Message::Binary(bincode::serialize(&pending.request)?)) .await?; outstanding_requests.insert( pending.request.id.expect("all requests must have ids"), pending, ); } Err(Error::Disconnected) } #[allow(clippy::collapsible_else_if)] // not possible due to cfg statement async fn response_processor<A: CustomApi>( mut receiver: SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>, outstanding_requests: OutstandingRequestMapHandle<A>, custom_api_callback: Option<&dyn CustomApiCallback<A>>, subscribers: SubscriberMap, ) -> Result<(), Error<A::Error>> { while let Some(message) = receiver.next().await { let message = message?; match message { Message::Binary(response) => { let payload = bincode::deserialize::<Payload<Response<CustomApiResult<A>>>>(&response)?; super::process_response_payload( payload, &outstanding_requests, custom_api_callback, &subscribers, ) .await; } other => { log::error!("Unexpected websocket message: {:?}", other); } } } Ok(()) }
33.07971
94
0.587952
29191d0bbaa09969c9a0149bc07362c65bb57f73
5,515
use crate::prelude::*; use tendermint_proto::Protobuf; use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; use crate::core::ics04_channel::error::Error; use crate::core::ics04_channel::packet::Packet; use crate::proofs::Proofs; use crate::signer::Signer; use crate::tx_msg::Msg; pub const TYPE_URL: &str = "/ibc.core.channel.v1.MsgRecvPacket"; /// /// Message definition for the "packet receiving" datagram. /// #[derive(Clone, Debug, PartialEq)] pub struct MsgRecvPacket { pub packet: Packet, pub proofs: Proofs, pub signer: Signer, } impl MsgRecvPacket { pub fn new(packet: Packet, proofs: Proofs, signer: Signer) -> MsgRecvPacket { Self { packet, proofs, signer, } } } impl Msg for MsgRecvPacket { type ValidationError = Error; type Raw = RawMsgRecvPacket; fn route(&self) -> String { crate::keys::ROUTER_KEY.to_string() } fn type_url(&self) -> String { TYPE_URL.to_string() } } impl Protobuf<RawMsgRecvPacket> for MsgRecvPacket {} impl TryFrom<RawMsgRecvPacket> for MsgRecvPacket { type Error = Error; fn try_from(raw_msg: RawMsgRecvPacket) -> Result<Self, Self::Error> { let proofs = Proofs::new( raw_msg.proof_commitment.into(), None, None, None, raw_msg .proof_height .ok_or_else(Error::missing_height)? .into(), ) .map_err(Error::invalid_proof)?; Ok(MsgRecvPacket { packet: raw_msg .packet .ok_or_else(Error::missing_packet)? .try_into()?, proofs, signer: raw_msg.signer.into(), }) } } impl From<MsgRecvPacket> for RawMsgRecvPacket { fn from(domain_msg: MsgRecvPacket) -> Self { RawMsgRecvPacket { packet: Some(domain_msg.packet.into()), proof_commitment: domain_msg.proofs.object_proof().clone().into(), proof_height: Some(domain_msg.proofs.height().into()), signer: domain_msg.signer.to_string(), } } } #[cfg(test)] pub mod test_util { use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; use ibc_proto::ibc::core::client::v1::Height as RawHeight; use crate::core::ics04_channel::packet::test_utils::get_dummy_raw_packet; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; /// Returns a dummy `RawMsgRecvPacket`, for testing only! The `height` parametrizes both the /// proof height as well as the timeout height. pub fn get_dummy_raw_msg_recv_packet(height: u64) -> RawMsgRecvPacket { RawMsgRecvPacket { packet: Some(get_dummy_raw_packet(height, 9)), proof_commitment: get_dummy_proof(), proof_height: Some(RawHeight { revision_number: 0, revision_height: height, }), signer: get_dummy_bech32_account(), } } } #[cfg(test)] mod test { use crate::prelude::*; use test_env_log::test; use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; use crate::core::ics04_channel::error::Error; use crate::core::ics04_channel::msgs::recv_packet::test_util::get_dummy_raw_msg_recv_packet; use crate::core::ics04_channel::msgs::recv_packet::MsgRecvPacket; #[test] fn msg_recv_packet_try_from_raw() { struct Test { name: String, raw: RawMsgRecvPacket, want_pass: bool, } let height = 20; let default_raw_msg = get_dummy_raw_msg_recv_packet(height); let tests: Vec<Test> = vec![ Test { name: "Good parameters".to_string(), raw: default_raw_msg.clone(), want_pass: true, }, Test { name: "Missing proof".to_string(), raw: RawMsgRecvPacket { proof_commitment: Vec::new(), ..default_raw_msg.clone() }, want_pass: false, }, Test { name: "Missing proof height".to_string(), raw: RawMsgRecvPacket { proof_height: None, ..default_raw_msg.clone() }, want_pass: false, }, Test { name: "Empty signer".to_string(), raw: RawMsgRecvPacket { signer: "".to_string(), ..default_raw_msg }, want_pass: true, }, ]; for test in tests { let res_msg: Result<MsgRecvPacket, Error> = test.raw.clone().try_into(); assert_eq!( res_msg.is_ok(), test.want_pass, "MsgRecvPacket::try_from failed for test {} \nraw message: {:?} with error: {:?}", test.name, test.raw, res_msg.err() ); } } #[test] fn to_and_from() { let raw = get_dummy_raw_msg_recv_packet(15); let msg = MsgRecvPacket::try_from(raw.clone()).unwrap(); let raw_back = RawMsgRecvPacket::from(msg.clone()); let msg_back = MsgRecvPacket::try_from(raw_back.clone()).unwrap(); assert_eq!(raw, raw_back); assert_eq!(msg, msg_back); } }
29.179894
98
0.560653
d6612035750836e49accc865a8f2d05dcaeb35b3
377
// run-pass // only-32bit too impatient for 2⁶⁴ items // ignore-wasm32-bare compiled with panic=abort by default // compile-flags: -C debug_assertions=yes -C opt-level=3 use std::panic; use std::usize::MAX; fn main() { assert_eq!((0..MAX).by_ref().count(), MAX); let r = panic::catch_unwind(|| { (0..=MAX).by_ref().count() }); assert!(r.is_err()); }
22.176471
58
0.623342
56aab1307cfebaa229e0d8ea9a26ae6e1dd1cc40
2,316
use futures::stream::unfold; use futures::Stream; macro_rules! r#try { ($expr:expr $(,)?) => { match $expr { Result::Ok(val) => val, Result::Err(err) => { return Some((Err(err.into()), State::Done)); } } }; } /// A pageable stream that yields items of type `T` /// /// Internally uses the Azure specific continuation header to /// make repeated requests to Azure yielding a new page each time. pub struct Pageable<T> { stream: std::pin::Pin<Box<dyn Stream<Item = Result<T, crate::ReqwestPipelineError>>>>, } impl<T: Continuable> Pageable<T> { pub fn new<F>(make_request: impl Fn(Option<String>) -> F + Clone + 'static) -> Self where F: std::future::Future<Output = Result<T, crate::ReqwestPipelineError>> + 'static, { let stream = unfold(State::Init, move |state: State| { let make_request = make_request.clone(); async move { let response = match state { State::Init => r#try!(make_request(None).await), State::Continuation(token) => { r#try!(make_request(Some(token)).await) } State::Done => return None, }; let next_state = response .continuation() .map(State::Continuation) .unwrap_or(State::Done); Some((Ok(response), next_state)) } }); Self { stream: Box::pin(stream), } } } impl<T> Stream for Pageable<T> { type Item = Result<T, crate::ReqwestPipelineError>; fn poll_next( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Option<Self::Item>> { std::pin::Pin::new(&mut self.stream).poll_next(cx) } } impl<T> std::fmt::Debug for Pageable<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Pageable").finish_non_exhaustive() } } /// A type that can yield an optional continuation token pub trait Continuable { fn continuation(&self) -> Option<String>; } #[derive(Debug, Clone, PartialEq)] enum State { Init, Continuation(String), Done, }
28.592593
90
0.541019
ab73c7272a93acca44bb746724baad99b30801fe
112,620
#![allow( clippy::cognitive_complexity, clippy::float_cmp, clippy::inconsistent_digit_grouping, clippy::unreadable_literal )] use crate::error::{Error, Result}; use crate::tag_code::TagCode; use crate::types::*; use byteorder::{LittleEndian, WriteBytesExt}; use enumset::EnumSet; use std::cmp::max; use std::io::{self, Write}; /// Writes an SWF file to an output stream. /// # Example /// ``` /// use swf::*; /// /// let swf = Swf { /// header: Header { /// compression: Compression::Zlib, /// version: 6, /// uncompressed_length: 1024, /// stage_size: Rectangle { x_min: Twips::from_pixels(0.0), x_max: Twips::from_pixels(400.0), y_min: Twips::from_pixels(0.0), y_max: Twips::from_pixels(400.0) }, /// frame_rate: 60.0, /// num_frames: 1, /// }, /// tags: vec![ /// Tag::SetBackgroundColor(Color { r: 255, g: 0, b: 0, a: 255 }), /// Tag::ShowFrame /// ] /// }; /// let output = Vec::new(); /// swf::write_swf(&swf, output).unwrap(); /// ``` pub fn write_swf<W: Write>(swf: &Swf, mut output: W) -> Result<()> { let signature = match swf.header.compression { Compression::None => b"FWS", Compression::Zlib => b"CWS", Compression::Lzma => b"ZWS", }; output.write_all(&signature[..])?; output.write_u8(swf.header.version)?; // Write SWF body. let mut swf_body = Vec::new(); { let mut writer = Writer::new(&mut swf_body, swf.header.version); writer.write_rectangle(&swf.header.stage_size)?; writer.write_fixed8(swf.header.frame_rate)?; writer.write_u16(swf.header.num_frames)?; // Write main timeline tag list. writer.write_tag_list(&swf.tags)?; } // Write SWF header. // Uncompressed SWF length. output.write_u32::<LittleEndian>(swf_body.len() as u32 + 8)?; // Compress SWF body. match swf.header.compression { Compression::None => { output.write_all(&swf_body)?; } Compression::Zlib => write_zlib_swf(&mut output, &swf_body)?, // LZMA header. // SWF format has a mangled LZMA header, so we have to do some magic to convert the // standard LZMA header to SWF format. // https://adobe.ly/2s8oYzn Compression::Lzma => { write_lzma_swf(&mut output, &swf_body)?; // 5 bytes of garbage data? //output.write_all(&[0xFF, 0xB5, 0xE6, 0xF8, 0xCB])?; } }; Ok(()) } #[cfg(feature = "flate2")] fn write_zlib_swf<W: Write>(mut output: W, swf_body: &[u8]) -> Result<()> { use flate2::write::ZlibEncoder; use flate2::Compression; let mut encoder = ZlibEncoder::new(&mut output, Compression::best()); encoder.write_all(&swf_body)?; encoder.finish()?; Ok(()) } #[cfg(all(feature = "libflate", not(feature = "flate2")))] fn write_zlib_swf<W: Write>(mut output: W, swf_body: &[u8]) -> Result<()> { use libflate::zlib::Encoder; let mut encoder = Encoder::new(&mut output)?; encoder.write_all(&swf_body)?; encoder.finish().into_result()?; Ok(()) } #[cfg(not(any(feature = "flate2", feature = "libflate")))] fn write_zlib_swf<W: Write>(_output: W, _swf_body: &[u8]) -> Result<()> { Err(Error::unsupported( "Support for Zlib compressed SWFs is not enabled.", )) } #[cfg(feature = "lzma")] fn write_lzma_swf<W: Write>(mut output: W, mut swf_body: &[u8]) -> Result<()> { // Compress data using LZMA. let mut data = vec![]; lzma_rs::lzma_compress(&mut swf_body, &mut data)?; // Flash uses a mangled LZMA header, so we have to massage it into the SWF format. // https://helpx.adobe.com/flash-player/kb/exception-thrown-you-decompress-lzma-compressed.html output.write_u32::<LittleEndian>(data.len() as u32 - 13)?; // Compressed length (- 13 to not include lzma header) output.write_all(&data[0..5])?; // LZMA properties output.write_all(&data[13..])?; // Data Ok(()) } #[cfg(not(feature = "lzma"))] fn write_lzma_swf<W: Write>(_output: W, _swf_body: &[u8]) -> Result<()> { Err(Error::unsupported( "Support for LZMA compressed SWFs is not enabled.", )) } pub trait SwfWrite<W: Write> { fn get_inner(&mut self) -> &mut W; fn write_u8(&mut self, n: u8) -> io::Result<()> { self.get_inner().write_u8(n) } fn write_u16(&mut self, n: u16) -> io::Result<()> { self.get_inner().write_u16::<LittleEndian>(n) } fn write_u32(&mut self, n: u32) -> io::Result<()> { self.get_inner().write_u32::<LittleEndian>(n) } fn write_u64(&mut self, n: u64) -> io::Result<()> { self.get_inner().write_u64::<LittleEndian>(n) } fn write_i8(&mut self, n: i8) -> io::Result<()> { self.get_inner().write_i8(n) } fn write_i16(&mut self, n: i16) -> io::Result<()> { self.get_inner().write_i16::<LittleEndian>(n) } fn write_i32(&mut self, n: i32) -> io::Result<()> { self.get_inner().write_i32::<LittleEndian>(n) } fn write_fixed8(&mut self, n: f32) -> io::Result<()> { self.write_i16((n * 256f32) as i16) } fn write_fixed16(&mut self, n: f64) -> io::Result<()> { self.write_i32((n * 65536f64) as i32) } fn write_f32(&mut self, n: f32) -> io::Result<()> { self.get_inner().write_f32::<LittleEndian>(n) } fn write_f64(&mut self, n: f64) -> io::Result<()> { // Flash weirdly stores f64 as two LE 32-bit chunks. // First word is the hi-word, second word is the lo-word. let mut num = [0u8; 8]; (&mut num[..]).write_f64::<LittleEndian>(n)?; num.swap(0, 4); num.swap(1, 5); num.swap(2, 6); num.swap(3, 7); self.get_inner().write_all(&num) } fn write_c_string(&mut self, s: &str) -> io::Result<()> { self.get_inner().write_all(s.as_bytes())?; self.write_u8(0) } } struct Writer<W: Write> { pub output: W, pub version: u8, pub byte: u8, pub bit_index: u8, pub num_fill_bits: u8, pub num_line_bits: u8, } impl<W: Write> SwfWrite<W> for Writer<W> { fn get_inner(&mut self) -> &mut W { &mut self.output } fn write_u8(&mut self, n: u8) -> io::Result<()> { self.flush_bits()?; self.output.write_u8(n) } fn write_u16(&mut self, n: u16) -> io::Result<()> { self.flush_bits()?; self.output.write_u16::<LittleEndian>(n) } fn write_u32(&mut self, n: u32) -> io::Result<()> { self.flush_bits()?; self.output.write_u32::<LittleEndian>(n) } fn write_i8(&mut self, n: i8) -> io::Result<()> { self.flush_bits()?; self.output.write_i8(n) } fn write_i16(&mut self, n: i16) -> io::Result<()> { self.flush_bits()?; self.output.write_i16::<LittleEndian>(n) } fn write_i32(&mut self, n: i32) -> io::Result<()> { self.flush_bits()?; self.output.write_i32::<LittleEndian>(n) } fn write_f32(&mut self, n: f32) -> io::Result<()> { self.flush_bits()?; self.output.write_f32::<LittleEndian>(n) } fn write_f64(&mut self, n: f64) -> io::Result<()> { self.flush_bits()?; self.output.write_f64::<LittleEndian>(n) } fn write_c_string(&mut self, s: &str) -> io::Result<()> { self.flush_bits()?; self.get_inner().write_all(s.as_bytes())?; self.write_u8(0) } } impl<W: Write> Writer<W> { fn new(output: W, version: u8) -> Writer<W> { Writer { output, version, byte: 0, bit_index: 8, num_fill_bits: 0, num_line_bits: 0, } } #[allow(dead_code)] fn into_inner(self) -> W { self.output } fn write_bit(&mut self, set: bool) -> Result<()> { self.bit_index -= 1; if set { self.byte |= 1 << self.bit_index; } if self.bit_index == 0 { self.flush_bits()?; } Ok(()) } fn flush_bits(&mut self) -> io::Result<()> { if self.bit_index != 8 { self.output.write_u8(self.byte)?; self.bit_index = 8; self.byte = 0; } Ok(()) } fn write_ubits(&mut self, num_bits: u8, n: u32) -> Result<()> { for i in 0..num_bits { self.write_bit(n & (1 << u32::from(num_bits - i - 1)) != 0)?; } Ok(()) } fn write_sbits(&mut self, num_bits: u8, n: i32) -> Result<()> { self.write_ubits(num_bits, n as u32) } fn write_sbits_twips(&mut self, num_bits: u8, twips: Twips) -> Result<()> { self.write_sbits(num_bits, twips.get()) } fn write_fbits(&mut self, num_bits: u8, n: f32) -> Result<()> { self.write_sbits(num_bits, (n * 65536f32) as i32) } fn write_encoded_u32(&mut self, mut n: u32) -> Result<()> { loop { let mut byte = (n & 0b01111111) as u8; n >>= 7; if n != 0 { byte |= 0b10000000; } self.write_u8(byte)?; if n == 0 { break; } } Ok(()) } fn write_rectangle(&mut self, rectangle: &Rectangle) -> Result<()> { self.flush_bits()?; let num_bits: u8 = [ rectangle.x_min, rectangle.x_max, rectangle.y_min, rectangle.y_max, ] .iter() .map(|x| count_sbits_twips(*x)) .max() .unwrap(); self.write_ubits(5, num_bits.into())?; self.write_sbits_twips(num_bits, rectangle.x_min)?; self.write_sbits_twips(num_bits, rectangle.x_max)?; self.write_sbits_twips(num_bits, rectangle.y_min)?; self.write_sbits_twips(num_bits, rectangle.y_max)?; Ok(()) } fn write_character_id(&mut self, id: CharacterId) -> Result<()> { self.write_u16(id)?; Ok(()) } fn write_rgb(&mut self, color: &Color) -> Result<()> { self.write_u8(color.r)?; self.write_u8(color.g)?; self.write_u8(color.b)?; Ok(()) } fn write_rgba(&mut self, color: &Color) -> Result<()> { self.write_u8(color.r)?; self.write_u8(color.g)?; self.write_u8(color.b)?; self.write_u8(color.a)?; Ok(()) } fn write_color_transform_no_alpha(&mut self, color_transform: &ColorTransform) -> Result<()> { // TODO: Assert that alpha is 1.0? self.flush_bits()?; let has_mult = color_transform.r_multiply != 1f32 || color_transform.g_multiply != 1f32 || color_transform.b_multiply != 1f32; let has_add = color_transform.r_add != 0 || color_transform.g_add != 0 || color_transform.b_add != 0; let multiply = [ color_transform.r_multiply, color_transform.g_multiply, color_transform.b_multiply, ]; let add = [ color_transform.a_add, color_transform.g_add, color_transform.b_add, color_transform.a_add, ]; self.write_bit(has_mult)?; self.write_bit(has_add)?; let mut num_bits = if has_mult { multiply .iter() .map(|n| count_sbits((*n * 256f32) as i32)) .max() .unwrap() } else { 0u8 }; if has_add { num_bits = max( num_bits, add.iter() .map(|n| count_sbits(i32::from(*n))) .max() .unwrap(), ); } self.write_ubits(4, num_bits.into())?; if has_mult { self.write_sbits(num_bits, (color_transform.r_multiply * 256f32) as i32)?; self.write_sbits(num_bits, (color_transform.g_multiply * 256f32) as i32)?; self.write_sbits(num_bits, (color_transform.b_multiply * 256f32) as i32)?; } if has_add { self.write_sbits(num_bits, color_transform.r_add.into())?; self.write_sbits(num_bits, color_transform.g_add.into())?; self.write_sbits(num_bits, color_transform.b_add.into())?; } Ok(()) } fn write_color_transform(&mut self, color_transform: &ColorTransform) -> Result<()> { self.flush_bits()?; let has_mult = color_transform.r_multiply != 1f32 || color_transform.g_multiply != 1f32 || color_transform.b_multiply != 1f32 || color_transform.a_multiply != 1f32; let has_add = color_transform.r_add != 0 || color_transform.g_add != 0 || color_transform.b_add != 0 || color_transform.a_add != 0; let multiply = [ color_transform.r_multiply, color_transform.g_multiply, color_transform.b_multiply, color_transform.a_multiply, ]; let add = [ color_transform.r_add, color_transform.g_add, color_transform.b_add, color_transform.a_add, ]; self.write_bit(has_add)?; self.write_bit(has_mult)?; let mut num_bits = if has_mult { multiply .iter() .map(|n| count_sbits((*n * 256f32) as i32)) .max() .unwrap() } else { 0u8 }; if has_add { num_bits = max( num_bits, add.iter() .map(|n| count_sbits(i32::from(*n))) .max() .unwrap(), ); } self.write_ubits(4, num_bits.into())?; if has_mult { self.write_sbits(num_bits, (color_transform.r_multiply * 256f32) as i32)?; self.write_sbits(num_bits, (color_transform.g_multiply * 256f32) as i32)?; self.write_sbits(num_bits, (color_transform.b_multiply * 256f32) as i32)?; self.write_sbits(num_bits, (color_transform.a_multiply * 256f32) as i32)?; } if has_add { self.write_sbits(num_bits, color_transform.r_add.into())?; self.write_sbits(num_bits, color_transform.g_add.into())?; self.write_sbits(num_bits, color_transform.b_add.into())?; self.write_sbits(num_bits, color_transform.a_add.into())?; } Ok(()) } fn write_matrix(&mut self, m: &Matrix) -> Result<()> { self.flush_bits()?; // Scale let has_scale = m.a != 1f32 || m.d != 1f32; self.write_bit(has_scale)?; if has_scale { let num_bits = max(count_fbits(m.a), count_fbits(m.d)); self.write_ubits(5, num_bits.into())?; self.write_fbits(num_bits, m.a)?; self.write_fbits(num_bits, m.d)?; } // Rotate/Skew let has_rotate_skew = m.b != 0f32 || m.c != 0f32; self.write_bit(has_rotate_skew)?; if has_rotate_skew { let num_bits = max(count_fbits(m.b), count_fbits(m.c)); self.write_ubits(5, num_bits.into())?; self.write_fbits(num_bits, m.b)?; self.write_fbits(num_bits, m.c)?; } // Translate (always written) let num_bits = max(count_sbits_twips(m.tx), count_sbits_twips(m.ty)); self.write_ubits(5, num_bits.into())?; self.write_sbits_twips(num_bits, m.tx)?; self.write_sbits_twips(num_bits, m.ty)?; self.flush_bits()?; Ok(()) } fn write_language(&mut self, language: Language) -> Result<()> { self.write_u8(match language { Language::Unknown => 0, Language::Latin => 1, Language::Japanese => 2, Language::Korean => 3, Language::SimplifiedChinese => 4, Language::TraditionalChinese => 5, })?; Ok(()) } fn write_tag(&mut self, tag: &Tag) -> Result<()> { match *tag { Tag::ShowFrame => self.write_tag_header(TagCode::ShowFrame, 0)?, Tag::ExportAssets(ref exports) => self.write_export_assets(&exports[..])?, Tag::Protect(ref password) => { if let Some(ref password_md5) = *password { self.write_tag_header(TagCode::Protect, password_md5.len() as u32 + 3)?; self.write_u16(0)?; // Two null bytes? Not specified in SWF19. self.write_c_string(password_md5)?; } else { self.write_tag_header(TagCode::Protect, 0)?; } } Tag::CsmTextSettings(ref settings) => { self.write_tag_header(TagCode::CsmTextSettings, 12)?; self.write_character_id(settings.id)?; self.write_u8( if settings.use_advanced_rendering { 0b01_000000 } else { 0 } | match settings.grid_fit { TextGridFit::None => 0, TextGridFit::Pixel => 0b01_000, TextGridFit::SubPixel => 0b10_000, }, )?; self.write_f32(settings.thickness)?; self.write_f32(settings.sharpness)?; self.write_u8(0)?; // Reserved (0). } Tag::DefineBinaryData { id, ref data } => { self.write_tag_header(TagCode::DefineBinaryData, data.len() as u32 + 6)?; self.write_u16(id)?; self.write_u32(0)?; // Reserved self.output.write_all(data)?; } Tag::DefineBits { id, ref jpeg_data } => { self.write_tag_header(TagCode::DefineBits, jpeg_data.len() as u32 + 2)?; self.write_u16(id)?; self.output.write_all(jpeg_data)?; } Tag::DefineBitsJpeg2 { id, ref jpeg_data } => { self.write_tag_header(TagCode::DefineBitsJpeg2, jpeg_data.len() as u32 + 2)?; self.write_u16(id)?; self.output.write_all(jpeg_data)?; } Tag::DefineBitsJpeg3(ref jpeg) => { self.write_tag_header( TagCode::DefineBitsJpeg3, (jpeg.data.len() + jpeg.alpha_data.len() + 6) as u32, )?; self.write_u16(jpeg.id)?; if jpeg.version >= 4 { self.write_fixed8(jpeg.deblocking)?; } // TODO(Herschel): Verify deblocking parameter is zero in version 3. self.write_u32(jpeg.data.len() as u32)?; self.output.write_all(&jpeg.data)?; self.output.write_all(&jpeg.alpha_data)?; } Tag::DefineBitsLossless(ref tag) => { let mut length = 7 + tag.data.len(); if tag.format == BitmapFormat::ColorMap8 { length += 1; } // TODO(Herschel): Throw error if RGB15 in tag version 2. let tag_code = if tag.version == 1 { TagCode::DefineBitsLossless } else { TagCode::DefineBitsLossless2 }; self.write_tag_header(tag_code, length as u32)?; self.write_character_id(tag.id)?; let format_id = match tag.format { BitmapFormat::ColorMap8 => 3, BitmapFormat::Rgb15 => 4, BitmapFormat::Rgb32 => 5, }; self.write_u8(format_id)?; self.write_u16(tag.width)?; self.write_u16(tag.height)?; if tag.format == BitmapFormat::ColorMap8 { self.write_u8(tag.num_colors)?; } self.output.write_all(&tag.data)?; } Tag::DefineButton(ref button) => self.write_define_button(button)?, Tag::DefineButton2(ref button) => self.write_define_button_2(button)?, Tag::DefineButtonColorTransform(ref button_color) => { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_character_id(button_color.id)?; for color_transform in &button_color.color_transforms { writer.write_color_transform_no_alpha(color_transform)?; writer.flush_bits()?; } } self.write_tag_header(TagCode::DefineButtonCxform, buf.len() as u32)?; self.output.write_all(&buf)?; } Tag::DefineButtonSound(ref button_sounds) => { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_u16(button_sounds.id)?; if let Some(ref sound) = button_sounds.over_to_up_sound { writer.write_u16(sound.0)?; writer.write_sound_info(&sound.1)?; } else { writer.write_u16(0)? }; if let Some(ref sound) = button_sounds.up_to_over_sound { writer.write_u16(sound.0)?; writer.write_sound_info(&sound.1)?; } else { writer.write_u16(0)? }; if let Some(ref sound) = button_sounds.over_to_down_sound { writer.write_u16(sound.0)?; writer.write_sound_info(&sound.1)?; } else { writer.write_u16(0)? }; if let Some(ref sound) = button_sounds.down_to_over_sound { writer.write_u16(sound.0)?; writer.write_sound_info(&sound.1)?; } else { writer.write_u16(0)? }; } self.write_tag_header(TagCode::DefineButtonSound, buf.len() as u32)?; self.output.write_all(&buf)?; } Tag::DefineEditText(ref edit_text) => self.write_define_edit_text(edit_text)?, Tag::DefineFont(ref font) => { let num_glyphs = font.glyphs.len(); let mut offsets = vec![]; let mut buf = vec![]; { let mut writer = Writer::new(&mut buf, self.version); for glyph in &font.glyphs { let offset = num_glyphs * 2 + writer.output.len(); offsets.push(offset as u16); // Bit length for fill and line indices. // TODO: This theoretically could be >1? writer.num_fill_bits = 1; writer.num_line_bits = 0; writer.write_ubits(4, 1)?; writer.write_ubits(4, 0)?; for shape_record in glyph { writer.write_shape_record(shape_record, 1)?; } // End shape record. writer.write_ubits(6, 0)?; writer.flush_bits()?; } } let tag_len = (2 + 2 * font.glyphs.len() + buf.len()) as u32; self.write_tag_header(TagCode::DefineFont, tag_len)?; self.write_u16(font.id)?; for offset in offsets { self.write_u16(offset)?; } self.output.write_all(&buf)?; } Tag::DefineFont2(ref font) => self.write_define_font_2(font)?, Tag::DefineFont4(ref font) => self.write_define_font_4(font)?, Tag::DefineFontAlignZones { id, thickness, ref zones, } => { self.write_tag_header(TagCode::DefineFontAlignZones, 3 + 10 * zones.len() as u32)?; self.write_character_id(id)?; self.write_u8(match thickness { FontThickness::Thin => 0b00_000000, FontThickness::Medium => 0b01_000000, FontThickness::Thick => 0b10_000000, })?; for zone in zones { self.write_u8(2)?; // Always 2 dimensions. self.write_i16(zone.left)?; self.write_i16(zone.width)?; self.write_i16(zone.bottom)?; self.write_i16(zone.height)?; self.write_u8(0b000000_11)?; // Always 2 dimensions. } } Tag::DefineFontInfo(ref font_info) => { let use_wide_codes = self.version >= 6 || font_info.version >= 2; let len = font_info.name.len() + if use_wide_codes { 2 } else { 1 } * font_info.code_table.len() + if font_info.version >= 2 { 1 } else { 0 } + 4; let tag_id = if font_info.version == 1 { TagCode::DefineFontInfo } else { TagCode::DefineFontInfo2 }; self.write_tag_header(tag_id, len as u32)?; self.write_u16(font_info.id)?; // SWF19 has ANSI and Shift-JIS backwards? self.write_u8(font_info.name.len() as u8)?; self.output.write_all(font_info.name.as_bytes())?; self.write_u8( if font_info.is_small_text { 0b100000 } else { 0 } | if font_info.is_ansi { 0b10000 } else { 0 } | if font_info.is_shift_jis { 0b1000 } else { 0 } | if font_info.is_italic { 0b100 } else { 0 } | if font_info.is_bold { 0b10 } else { 0 } | if use_wide_codes { 0b1 } else { 0 }, )?; // TODO(Herschel): Assert language is unknown for v1. if font_info.version >= 2 { self.write_language(font_info.language)?; } for &code in &font_info.code_table { if use_wide_codes { self.write_u16(code)?; } else { self.write_u8(code as u8)?; } } } Tag::DefineFontName { id, ref name, ref copyright_info, } => { let len = name.len() + copyright_info.len() + 4; self.write_tag_header(TagCode::DefineFontName, len as u32)?; self.write_character_id(id)?; self.write_c_string(name)?; self.write_c_string(copyright_info)?; } Tag::DefineMorphShape(ref define_morph_shape) => { self.write_define_morph_shape(define_morph_shape)? } Tag::DefineScalingGrid { id, ref splitter_rect, } => { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_u16(id)?; writer.write_rectangle(splitter_rect)?; writer.flush_bits()?; } self.write_tag_header(TagCode::DefineScalingGrid, buf.len() as u32)?; self.output.write_all(&buf)?; } Tag::DefineShape(ref shape) => self.write_define_shape(shape)?, Tag::DefineSound(ref sound) => self.write_define_sound(sound)?, Tag::DefineSprite(ref sprite) => self.write_define_sprite(sprite)?, Tag::DefineText(ref text) => self.write_define_text(text)?, Tag::DefineVideoStream(ref video) => self.write_define_video_stream(video)?, Tag::DoAbc(ref do_abc) => { let len = do_abc.data.len() + do_abc.name.len() + 5; self.write_tag_header(TagCode::DoAbc, len as u32)?; self.write_u32(if do_abc.is_lazy_initialize { 1 } else { 0 })?; self.write_c_string(&do_abc.name)?; self.output.write_all(&do_abc.data)?; } Tag::DoAction(ref action_data) => { self.write_tag_header(TagCode::DoAction, action_data.len() as u32)?; self.output.write_all(action_data)?; } Tag::DoInitAction { id, ref action_data, } => { self.write_tag_header(TagCode::DoInitAction, action_data.len() as u32 + 2)?; self.write_u16(id)?; self.output.write_all(action_data)?; } Tag::EnableDebugger(ref password_md5) => { let len = password_md5.len() as u32 + 1; if self.version >= 6 { // SWF v6+ uses EnableDebugger2 tag. self.write_tag_header(TagCode::EnableDebugger2, len + 2)?; self.write_u16(0)?; // Reserved } else { self.write_tag_header(TagCode::EnableDebugger, len)?; } self.write_c_string(password_md5)?; } Tag::EnableTelemetry { ref password_hash } => { if !password_hash.is_empty() { self.write_tag_header(TagCode::EnableTelemetry, 34)?; self.write_u16(0)?; self.output.write_all(&password_hash[0..32])?; } else { self.write_tag_header(TagCode::EnableTelemetry, 2)?; self.write_u16(0)?; } } Tag::End => self.write_tag_header(TagCode::End, 0)?, Tag::ImportAssets { ref url, ref imports, } => { let len = imports.iter().map(|e| e.name.len() as u32 + 3).sum::<u32>() + url.len() as u32 + 1 + 2; // SWF v8 and later use ImportAssets2 tag. if self.version >= 8 { self.write_tag_header(TagCode::ImportAssets2, len + 2)?; self.write_c_string(url)?; self.write_u8(1)?; self.write_u8(0)?; } else { self.write_tag_header(TagCode::ImportAssets, len)?; self.write_c_string(url)?; } self.write_u16(imports.len() as u16)?; for &ExportedAsset { id, ref name } in imports { self.write_u16(id)?; self.write_c_string(name)?; } } Tag::JpegTables(ref data) => { self.write_tag_header(TagCode::JpegTables, data.len() as u32)?; self.output.write_all(data)?; } Tag::Metadata(ref metadata) => { self.write_tag_header(TagCode::Metadata, metadata.len() as u32 + 1)?; self.write_c_string(metadata)?; } // TODO: Allow clone of color. Tag::SetBackgroundColor(ref color) => { self.write_tag_header(TagCode::SetBackgroundColor, 3)?; self.write_rgb(&color)?; } Tag::ScriptLimits { max_recursion_depth, timeout_in_seconds, } => { self.write_tag_header(TagCode::ScriptLimits, 4)?; self.write_u16(max_recursion_depth)?; self.write_u16(timeout_in_seconds)?; } Tag::SetTabIndex { depth, tab_index } => { self.write_tag_header(TagCode::SetTabIndex, 4)?; self.write_u16(depth)?; self.write_u16(tab_index)?; } Tag::PlaceObject(ref place_object) => match (*place_object).version { 1 => self.write_place_object(place_object)?, 2 => self.write_place_object_2_or_3(place_object, 2)?, 3 => self.write_place_object_2_or_3(place_object, 3)?, 4 => self.write_place_object_2_or_3(place_object, 4)?, _ => return Err(Error::invalid_data("Invalid PlaceObject version.")), }, Tag::RemoveObject(ref remove_object) => { if let Some(id) = remove_object.character_id { self.write_tag_header(TagCode::RemoveObject, 4)?; self.write_u16(id)?; } else { self.write_tag_header(TagCode::RemoveObject2, 2)?; } self.write_u16(remove_object.depth)?; } Tag::SoundStreamBlock(ref data) => { self.write_tag_header(TagCode::SoundStreamBlock, data.len() as u32)?; self.output.write_all(data)?; } Tag::SoundStreamHead(ref sound_stream_head) => { self.write_sound_stream_head(sound_stream_head, 1)?; } Tag::SoundStreamHead2(ref sound_stream_head) => { self.write_sound_stream_head(sound_stream_head, 2)?; } Tag::StartSound(ref start_sound) => { let sound_info = &start_sound.sound_info; let length = 3 + if sound_info.in_sample.is_some() { 4 } else { 0 } + if sound_info.out_sample.is_some() { 4 } else { 0 } + if sound_info.num_loops > 1 { 2 } else { 0 } + if let Some(ref e) = sound_info.envelope { e.len() as u32 * 8 + 1 } else { 0 }; self.write_tag_header(TagCode::StartSound, length)?; self.write_u16(start_sound.id)?; self.write_sound_info(sound_info)?; } Tag::StartSound2 { ref class_name, ref sound_info, } => { let length = class_name.len() as u32 + 2 + if sound_info.in_sample.is_some() { 4 } else { 0 } + if sound_info.out_sample.is_some() { 4 } else { 0 } + if sound_info.num_loops > 1 { 2 } else { 0 } + if let Some(ref e) = sound_info.envelope { e.len() as u32 * 8 + 1 } else { 0 }; self.write_tag_header(TagCode::StartSound2, length)?; self.write_c_string(class_name)?; self.write_sound_info(sound_info)?; } Tag::SymbolClass(ref symbols) => { let len = symbols .iter() .map(|e| e.class_name.len() as u32 + 3) .sum::<u32>() + 2; self.write_tag_header(TagCode::SymbolClass, len)?; self.write_u16(symbols.len() as u16)?; for &SymbolClassLink { id, ref class_name } in symbols { self.write_u16(id)?; self.write_c_string(class_name)?; } } Tag::VideoFrame(ref frame) => { self.write_tag_header(TagCode::VideoFrame, 4 + frame.data.len() as u32)?; self.write_character_id(frame.stream_id)?; self.write_u16(frame.frame_num)?; self.output.write_all(&frame.data)?; } Tag::FileAttributes(ref attributes) => { self.write_tag_header(TagCode::FileAttributes, 4)?; let mut flags = 0u32; if attributes.use_direct_blit { flags |= 0b01000000; } if attributes.use_gpu { flags |= 0b00100000; } if attributes.has_metadata { flags |= 0b00010000; } if attributes.is_action_script_3 { flags |= 0b00001000; } if attributes.use_network_sandbox { flags |= 0b00000001; } self.write_u32(flags)?; } Tag::FrameLabel(FrameLabel { ref label, is_anchor, }) => { // TODO: Assert proper version let is_anchor = is_anchor && self.version >= 6; let length = label.len() as u32 + if is_anchor { 2 } else { 1 }; self.write_tag_header(TagCode::FrameLabel, length)?; self.write_c_string(label)?; if is_anchor { self.write_u8(1)?; } } Tag::DefineSceneAndFrameLabelData(ref data) => { self.write_define_scene_and_frame_label_data(data)? } Tag::ProductInfo(ref product_info) => self.write_product_info(product_info)?, Tag::DebugId(ref debug_id) => self.write_debug_id(debug_id)?, Tag::Unknown { tag_code, ref data } => { self.write_tag_code_and_length(tag_code, data.len() as u32)?; self.output.write_all(data)?; } } Ok(()) } fn write_define_button(&mut self, button: &Button) -> Result<()> { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_u16(button.id)?; for record in &button.records { writer.write_button_record(record, 1)?; } writer.write_u8(0)?; // End button records // TODO: Assert we have some action. writer.output.write_all(&button.actions[0].action_data)?; } self.write_tag_header(TagCode::DefineButton, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_define_button_2(&mut self, button: &Button) -> Result<()> { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_u16(button.id)?; let flags = if button.is_track_as_menu { 1 } else { 0 }; writer.write_u8(flags)?; let mut record_data = Vec::new(); { let mut writer_2 = Writer::new(&mut record_data, self.version); for record in &button.records { writer_2.write_button_record(record, 2)?; } writer_2.write_u8(0)?; // End button records } writer.write_u16(record_data.len() as u16 + 2)?; writer.output.write_all(&record_data)?; let mut iter = button.actions.iter().peekable(); while let Some(action) = iter.next() { if iter.peek().is_some() { let length = action.action_data.len() as u16 + 4; writer.write_u16(length)?; } else { writer.write_u16(0)?; } writer.write_u8( if action .conditions .contains(&ButtonActionCondition::IdleToOverDown) { 0b1000_0000 } else { 0 } | if action .conditions .contains(&ButtonActionCondition::OutDownToIdle) { 0b100_0000 } else { 0 } | if action .conditions .contains(&ButtonActionCondition::OutDownToOverDown) { 0b10_0000 } else { 0 } | if action .conditions .contains(&ButtonActionCondition::OverDownToOutDown) { 0b1_0000 } else { 0 } | if action .conditions .contains(&ButtonActionCondition::OverDownToOverUp) { 0b1000 } else { 0 } | if action .conditions .contains(&ButtonActionCondition::OverUpToOverDown) { 0b100 } else { 0 } | if action .conditions .contains(&ButtonActionCondition::OverUpToIdle) { 0b10 } else { 0 } | if action .conditions .contains(&ButtonActionCondition::IdleToOverUp) { 0b1 } else { 0 }, )?; let mut flags = if action .conditions .contains(&ButtonActionCondition::OverDownToIdle) { 0b1 } else { 0 }; if action.conditions.contains(&ButtonActionCondition::KeyPress) { if let Some(key_code) = action.key_code { flags |= key_code << 1; } } writer.write_u8(flags)?; writer.output.write_all(&action.action_data)?; } } self.write_tag_header(TagCode::DefineButton2, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_define_morph_shape(&mut self, data: &DefineMorphShape) -> Result<()> { if data.start.fill_styles.len() != data.end.fill_styles.len() || data.start.line_styles.len() != data.end.line_styles.len() { return Err(Error::invalid_data( "Start and end state of a morph shape must have the same number of styles.", )); } let num_fill_styles = data.start.fill_styles.len(); let num_line_styles = data.start.line_styles.len(); let num_fill_bits = count_ubits(num_fill_styles as u32); let num_line_bits = count_ubits(num_line_styles as u32); // Need to write styles first, to calculate offset to EndEdges. let mut start_buf = Vec::new(); { let mut writer = Writer::new(&mut start_buf, self.version); // Styles // TODO(Herschel): Make fn write_style_len. Check version. if num_fill_styles >= 0xff { writer.write_u8(0xff)?; writer.write_u16(num_fill_styles as u16)?; } else { writer.write_u8(num_fill_styles as u8)?; } for (start, end) in data .start .fill_styles .iter() .zip(data.end.fill_styles.iter()) { writer.write_morph_fill_style(start, end, data.version)?; } if num_line_styles >= 0xff { writer.write_u8(0xff)?; writer.write_u16(num_line_styles as u16)?; } else { writer.write_u8(num_line_styles as u8)?; } for (start, end) in data .start .line_styles .iter() .zip(data.end.line_styles.iter()) { writer.write_morph_line_style(start, end, data.version)?; } // TODO(Herschel): Make fn write_shape. writer.write_ubits(4, num_fill_bits.into())?; writer.write_ubits(4, num_line_bits.into())?; writer.num_fill_bits = num_fill_bits; writer.num_line_bits = num_line_bits; for shape_record in &data.start.shape { writer.write_shape_record(shape_record, 1)?; } // End shape record. writer.write_ubits(6, 0)?; writer.flush_bits()?; } let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_character_id(data.id)?; writer.write_rectangle(&data.start.shape_bounds)?; writer.write_rectangle(&data.end.shape_bounds)?; if data.version >= 2 { writer.write_rectangle(&data.start.edge_bounds)?; writer.write_rectangle(&data.end.edge_bounds)?; writer.write_u8( if data.has_non_scaling_strokes { 0b10 } else { 0 } | if data.has_scaling_strokes { 0b1 } else { 0 }, )?; } // Offset to EndEdges. writer.write_u32(start_buf.len() as u32)?; writer.output.write_all(&start_buf)?; // EndEdges. writer.write_u8(0)?; // NumFillBits and NumLineBits are written as 0 for the end shape. writer.num_fill_bits = num_fill_bits; writer.num_line_bits = num_line_bits; for shape_record in &data.end.shape { writer.write_shape_record(shape_record, 1)?; } // End shape record. writer.write_ubits(6, 0)?; writer.flush_bits()?; } let tag_code = if data.version == 1 { TagCode::DefineMorphShape } else { TagCode::DefineMorphShape2 }; self.write_tag_header(tag_code, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_morph_fill_style( &mut self, start: &FillStyle, end: &FillStyle, shape_version: u8, ) -> Result<()> { match (start, end) { (&FillStyle::Color(ref start_color), &FillStyle::Color(ref end_color)) => { self.write_u8(0x00)?; // Solid color. self.write_rgba(start_color)?; self.write_rgba(end_color)?; } ( &FillStyle::LinearGradient(ref start_gradient), &FillStyle::LinearGradient(ref end_gradient), ) => { self.write_u8(0x10)?; // Linear gradient. self.write_morph_gradient(start_gradient, end_gradient)?; } ( &FillStyle::RadialGradient(ref start_gradient), &FillStyle::RadialGradient(ref end_gradient), ) => { self.write_u8(0x12)?; // Linear gradient. self.write_morph_gradient(start_gradient, end_gradient)?; } ( &FillStyle::FocalGradient { gradient: ref start_gradient, focal_point: start_focal_point, }, &FillStyle::FocalGradient { gradient: ref end_gradient, focal_point: end_focal_point, }, ) => { if self.version < 8 || shape_version < 2 { return Err(Error::invalid_data( "Focal gradients are only support in SWF version 8 \ and higher.", )); } self.write_u8(0x13)?; // Focal gradient. self.write_morph_gradient(start_gradient, end_gradient)?; self.write_fixed8(start_focal_point)?; self.write_fixed8(end_focal_point)?; } ( &FillStyle::Bitmap { id, matrix: ref start_matrix, is_smoothed, is_repeating, }, &FillStyle::Bitmap { id: end_id, matrix: ref end_matrix, is_smoothed: end_is_smoothed, is_repeating: end_is_repeating, }, ) if id == end_id && is_smoothed == end_is_smoothed || is_repeating == end_is_repeating => { let fill_style_type = match (is_smoothed, is_repeating) { (true, true) => 0x40, (true, false) => 0x41, (false, true) => 0x42, (false, false) => 0x43, }; self.write_u8(fill_style_type)?; self.write_u16(id)?; self.write_matrix(start_matrix)?; self.write_matrix(end_matrix)?; } _ => { return Err(Error::invalid_data( "Morph start and end fill styles must be the same variant.", )) } } Ok(()) } fn write_morph_gradient(&mut self, start: &Gradient, end: &Gradient) -> Result<()> { self.write_matrix(&start.matrix)?; self.write_matrix(&end.matrix)?; if start.records.len() != end.records.len() { return Err(Error::invalid_data( "Morph start and end gradient must have the same amount of records.", )); } self.write_gradient_flags(start)?; for (start_record, end_record) in start.records.iter().zip(end.records.iter()) { self.write_u8(start_record.ratio)?; self.write_rgba(&start_record.color)?; self.write_u8(end_record.ratio)?; self.write_rgba(&end_record.color)?; } Ok(()) } fn write_morph_line_style( &mut self, start: &LineStyle, end: &LineStyle, shape_version: u8, ) -> Result<()> { if shape_version < 2 { // TODO(Herschel): Handle overflow. self.write_u16(start.width.get() as u16)?; self.write_u16(end.width.get() as u16)?; self.write_rgba(&start.color)?; self.write_rgba(&end.color)?; } else { if start.start_cap != end.start_cap || start.join_style != end.join_style || start.allow_scale_x != end.allow_scale_x || start.allow_scale_y != end.allow_scale_y || start.is_pixel_hinted != end.is_pixel_hinted || start.allow_close != end.allow_close || start.end_cap != end.end_cap { return Err(Error::invalid_data( "Morph start and end line styles must have the same join parameters.", )); } // TODO(Herschel): Handle overflow. self.write_u16(start.width.get() as u16)?; self.write_u16(end.width.get() as u16)?; // MorphLineStyle2 self.write_ubits( 2, match start.start_cap { LineCapStyle::Round => 0, LineCapStyle::None => 1, LineCapStyle::Square => 2, }, )?; self.write_ubits( 2, match start.join_style { LineJoinStyle::Round => 0, LineJoinStyle::Bevel => 1, LineJoinStyle::Miter(_) => 2, }, )?; self.write_bit(start.fill_style.is_some())?; self.write_bit(!start.allow_scale_x)?; self.write_bit(!start.allow_scale_y)?; self.write_bit(start.is_pixel_hinted)?; self.write_ubits(5, 0)?; self.write_bit(!start.allow_close)?; self.write_ubits( 2, match start.end_cap { LineCapStyle::Round => 0, LineCapStyle::None => 1, LineCapStyle::Square => 2, }, )?; if let LineJoinStyle::Miter(miter_factor) = start.join_style { self.write_fixed8(miter_factor)?; } match (&start.fill_style, &end.fill_style) { (&None, &None) => { self.write_rgba(&start.color)?; self.write_rgba(&end.color)?; } (&Some(ref start_fill), &Some(ref end_fill)) => { self.write_morph_fill_style(start_fill, end_fill, shape_version)? } _ => { return Err(Error::invalid_data( "Morph start and end line styles must both have fill styles.", )) } } } Ok(()) } fn write_define_scene_and_frame_label_data( &mut self, data: &DefineSceneAndFrameLabelData, ) -> Result<()> { let mut buf = Vec::with_capacity((data.scenes.len() + data.frame_labels.len()) * 4); { let mut writer = Writer::new(&mut buf, self.version); writer.write_encoded_u32(data.scenes.len() as u32)?; for scene in &data.scenes { writer.write_encoded_u32(scene.frame_num)?; writer.write_c_string(&scene.label)?; } writer.write_encoded_u32(data.frame_labels.len() as u32)?; for frame_label in &data.frame_labels { writer.write_encoded_u32(frame_label.frame_num)?; writer.write_c_string(&frame_label.label)?; } } self.write_tag_header(TagCode::DefineSceneAndFrameLabelData, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_define_shape(&mut self, shape: &Shape) -> Result<()> { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_u16(shape.id)?; writer.write_rectangle(&shape.shape_bounds)?; if shape.version >= 4 { writer.write_rectangle(&shape.edge_bounds)?; writer.flush_bits()?; writer.write_u8( if shape.has_fill_winding_rule { 0b100 } else { 0 } | if shape.has_non_scaling_strokes { 0b10 } else { 0 } | if shape.has_scaling_strokes { 0b1 } else { 0 }, )?; } writer.write_shape_styles(&shape.styles, shape.version)?; for shape_record in &shape.shape { writer.write_shape_record(shape_record, shape.version)?; } // End shape record. writer.write_ubits(6, 0)?; writer.flush_bits()?; } let tag_code = match shape.version { 1 => TagCode::DefineShape, 2 => TagCode::DefineShape2, 3 => TagCode::DefineShape3, 4 => TagCode::DefineShape4, _ => return Err(Error::invalid_data("Invalid DefineShape version.")), }; self.write_tag_header(tag_code, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_define_sound(&mut self, sound: &Sound) -> Result<()> { self.write_tag_header(TagCode::DefineSound, 7 + sound.data.len() as u32)?; self.write_u16(sound.id)?; self.write_sound_format(&sound.format)?; self.write_u32(sound.num_samples)?; self.output.write_all(&sound.data)?; Ok(()) } fn write_define_sprite(&mut self, sprite: &Sprite) -> Result<()> { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_u16(sprite.id)?; writer.write_u16(sprite.num_frames)?; writer.write_tag_list(&sprite.tags)?; }; self.write_tag_header(TagCode::DefineSprite, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_export_assets(&mut self, exports: &[ExportedAsset]) -> Result<()> { let len = exports.iter().map(|e| e.name.len() as u32 + 1).sum::<u32>() + exports.len() as u32 * 2 + 2; self.write_tag_header(TagCode::ExportAssets, len)?; self.write_u16(exports.len() as u16)?; for &ExportedAsset { id, ref name } in exports { self.write_u16(id)?; self.write_c_string(name)?; } Ok(()) } fn write_button_record(&mut self, record: &ButtonRecord, tag_version: u8) -> Result<()> { // TODO: Validate version let flags = if record.blend_mode != BlendMode::Normal { 0b10_0000 } else { 0 } | if !record.filters.is_empty() { 0b1_0000 } else { 0 } | if record.states.contains(&ButtonState::HitTest) { 0b1000 } else { 0 } | if record.states.contains(&ButtonState::Down) { 0b100 } else { 0 } | if record.states.contains(&ButtonState::Over) { 0b10 } else { 0 } | if record.states.contains(&ButtonState::Up) { 0b1 } else { 0 }; self.write_u8(flags)?; self.write_u16(record.id)?; self.write_u16(record.depth)?; self.write_matrix(&record.matrix)?; if tag_version >= 2 { self.write_color_transform(&record.color_transform)?; if !record.filters.is_empty() { self.write_u8(record.filters.len() as u8)?; for filter in &record.filters { self.write_filter(filter)?; } } if record.blend_mode != BlendMode::Normal { self.write_blend_mode(record.blend_mode)?; } } Ok(()) } fn write_blend_mode(&mut self, blend_mode: BlendMode) -> Result<()> { self.write_u8(match blend_mode { BlendMode::Normal => 0, BlendMode::Layer => 2, BlendMode::Multiply => 3, BlendMode::Screen => 4, BlendMode::Lighten => 5, BlendMode::Darken => 6, BlendMode::Difference => 7, BlendMode::Add => 8, BlendMode::Subtract => 9, BlendMode::Invert => 10, BlendMode::Alpha => 11, BlendMode::Erase => 12, BlendMode::Overlay => 13, BlendMode::HardLight => 14, })?; Ok(()) } fn write_shape_styles(&mut self, styles: &ShapeStyles, shape_version: u8) -> Result<()> { // TODO: Check shape_version. if styles.fill_styles.len() >= 0xff { self.write_u8(0xff)?; self.write_u16(styles.fill_styles.len() as u16)?; } else { self.write_u8(styles.fill_styles.len() as u8)?; } for fill_style in &styles.fill_styles { self.write_fill_style(fill_style, shape_version)?; } if styles.line_styles.len() >= 0xff { self.write_u8(0xff)?; self.write_u16(styles.line_styles.len() as u16)?; } else { self.write_u8(styles.line_styles.len() as u8)?; } for line_style in &styles.line_styles { self.write_line_style(line_style, shape_version)?; } let num_fill_bits = count_ubits(styles.fill_styles.len() as u32); let num_line_bits = count_ubits(styles.line_styles.len() as u32); self.write_ubits(4, num_fill_bits.into())?; self.write_ubits(4, num_line_bits.into())?; self.num_fill_bits = num_fill_bits; self.num_line_bits = num_line_bits; Ok(()) } fn write_shape_record(&mut self, record: &ShapeRecord, shape_version: u8) -> Result<()> { match *record { ShapeRecord::StraightEdge { delta_x, delta_y } => { self.write_ubits(2, 0b11)?; // Straight edge // TODO: Check underflow? let mut num_bits = max(count_sbits_twips(delta_x), count_sbits_twips(delta_y)); num_bits = max(2, num_bits); let is_axis_aligned = delta_x.get() == 0 || delta_y.get() == 0; self.write_ubits(4, u32::from(num_bits) - 2)?; self.write_bit(!is_axis_aligned)?; if is_axis_aligned { self.write_bit(delta_x.get() == 0)?; } if delta_x.get() != 0 { self.write_sbits_twips(num_bits, delta_x)?; } if delta_y.get() != 0 { self.write_sbits_twips(num_bits, delta_y)?; } } ShapeRecord::CurvedEdge { control_delta_x, control_delta_y, anchor_delta_x, anchor_delta_y, } => { self.write_ubits(2, 0b10)?; // Curved edge let num_bits = [ control_delta_x, control_delta_y, anchor_delta_x, anchor_delta_y, ] .iter() .map(|x| count_sbits_twips(*x)) .max() .unwrap(); self.write_ubits(4, u32::from(num_bits) - 2)?; self.write_sbits_twips(num_bits, control_delta_x)?; self.write_sbits_twips(num_bits, control_delta_y)?; self.write_sbits_twips(num_bits, anchor_delta_x)?; self.write_sbits_twips(num_bits, anchor_delta_y)?; } ShapeRecord::StyleChange(ref style_change) => { self.write_bit(false)?; // Style change let num_fill_bits = self.num_fill_bits; let num_line_bits = self.num_line_bits; self.write_bit(style_change.new_styles.is_some())?; self.write_bit(style_change.line_style.is_some())?; self.write_bit(style_change.fill_style_1.is_some())?; self.write_bit(style_change.fill_style_0.is_some())?; self.write_bit(style_change.move_to.is_some())?; if let Some((move_x, move_y)) = style_change.move_to { let num_bits = max(count_sbits_twips(move_x), count_sbits_twips(move_y)); self.write_ubits(5, num_bits.into())?; self.write_sbits_twips(num_bits, move_x)?; self.write_sbits_twips(num_bits, move_y)?; } if let Some(fill_style_index) = style_change.fill_style_0 { self.write_ubits(num_fill_bits, fill_style_index)?; } if let Some(fill_style_index) = style_change.fill_style_1 { self.write_ubits(num_fill_bits, fill_style_index)?; } if let Some(line_style_index) = style_change.line_style { self.write_ubits(num_line_bits, line_style_index)?; } if let Some(ref new_styles) = style_change.new_styles { if shape_version < 2 { return Err(Error::invalid_data( "Only DefineShape2 and higher may change styles.", )); } self.write_shape_styles(new_styles, shape_version)?; } } } Ok(()) } fn write_fill_style(&mut self, fill_style: &FillStyle, shape_version: u8) -> Result<()> { match *fill_style { FillStyle::Color(ref color) => { self.write_u8(0x00)?; // Solid color. if shape_version >= 3 { self.write_rgba(color)? } else { self.write_rgb(color)?; } } FillStyle::LinearGradient(ref gradient) => { self.write_u8(0x10)?; // Linear gradient. self.write_gradient(gradient, shape_version)?; } FillStyle::RadialGradient(ref gradient) => { self.write_u8(0x12)?; // Linear gradient. self.write_gradient(gradient, shape_version)?; } FillStyle::FocalGradient { ref gradient, focal_point, } => { if self.version < 8 { return Err(Error::invalid_data( "Focal gradients are only support in SWF version 8 \ and higher.", )); } self.write_u8(0x13)?; // Focal gradient. self.write_gradient(gradient, shape_version)?; self.write_fixed8(focal_point)?; } FillStyle::Bitmap { id, ref matrix, is_smoothed, is_repeating, } => { // Bitmap smoothing only an option in SWF version 8+. // Lower versions use 0x40 and 0x41 type even when unsmoothed. let fill_style_type = match (is_smoothed || self.version < 8, is_repeating) { (true, true) => 0x40, (true, false) => 0x41, (false, true) => 0x42, (false, false) => 0x43, }; self.write_u8(fill_style_type)?; self.write_u16(id)?; self.write_matrix(matrix)?; } } Ok(()) } fn write_line_style(&mut self, line_style: &LineStyle, shape_version: u8) -> Result<()> { // TODO(Herschel): Handle overflow. self.write_u16(line_style.width.get() as u16)?; if shape_version >= 4 { // LineStyle2 self.write_ubits( 2, match line_style.start_cap { LineCapStyle::Round => 0, LineCapStyle::None => 1, LineCapStyle::Square => 2, }, )?; self.write_ubits( 2, match line_style.join_style { LineJoinStyle::Round => 0, LineJoinStyle::Bevel => 1, LineJoinStyle::Miter(_) => 2, }, )?; self.write_bit(line_style.fill_style.is_some())?; self.write_bit(!line_style.allow_scale_x)?; self.write_bit(!line_style.allow_scale_y)?; self.write_bit(line_style.is_pixel_hinted)?; self.write_ubits(5, 0)?; self.write_bit(!line_style.allow_close)?; self.write_ubits( 2, match line_style.end_cap { LineCapStyle::Round => 0, LineCapStyle::None => 1, LineCapStyle::Square => 2, }, )?; if let LineJoinStyle::Miter(miter_factor) = line_style.join_style { self.write_fixed8(miter_factor)?; } match line_style.fill_style { None => self.write_rgba(&line_style.color)?, Some(ref fill) => self.write_fill_style(fill, shape_version)?, } } else if shape_version >= 3 { // LineStyle1 with RGBA self.write_rgba(&line_style.color)?; } else { // LineStyle1 with RGB self.write_rgb(&line_style.color)?; } Ok(()) } fn write_gradient(&mut self, gradient: &Gradient, shape_version: u8) -> Result<()> { self.write_matrix(&gradient.matrix)?; self.flush_bits()?; self.write_gradient_flags(gradient)?; for record in &gradient.records { self.write_u8(record.ratio)?; if shape_version >= 3 { self.write_rgba(&record.color)?; } else { self.write_rgb(&record.color)?; } } Ok(()) } fn write_gradient_flags(&mut self, gradient: &Gradient) -> Result<()> { let mut flags = 0; flags |= match &gradient.spread { GradientSpread::Pad => 0, GradientSpread::Reflect => 0b0100_0000, GradientSpread::Repeat => 0b1000_0000, }; flags |= match &gradient.interpolation { GradientInterpolation::RGB => 0b00_0000, GradientInterpolation::LinearRGB => 0b_01_0000, }; flags |= (gradient.records.len() as u8) & 0b1111; self.write_u8(flags)?; Ok(()) } fn write_place_object(&mut self, place_object: &PlaceObject) -> Result<()> { // TODO: Assert that the extraneous fields are the defaults. let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); if let PlaceObjectAction::Place(character_id) = place_object.action { writer.write_u16(character_id)?; } else { return Err(Error::invalid_data( "PlaceObject version 1 can only use a Place action.", )); } writer.write_u16(place_object.depth)?; if let Some(ref matrix) = place_object.matrix { writer.write_matrix(matrix)?; } else { writer.write_matrix(&Matrix::identity())?; } if let Some(ref color_transform) = place_object.color_transform { writer.write_color_transform_no_alpha(color_transform)?; } } self.write_tag_header(TagCode::PlaceObject, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_place_object_2_or_3( &mut self, place_object: &PlaceObject, place_object_version: u8, ) -> Result<()> { let mut buf = Vec::new(); { // TODO: Assert version. let mut writer = Writer::new(&mut buf, self.version); writer.write_u8( if place_object.clip_actions.is_some() { 0b1000_0000 } else { 0 } | if place_object.clip_depth.is_some() { 0b0100_0000 } else { 0 } | if place_object.name.is_some() { 0b0010_0000 } else { 0 } | if place_object.ratio.is_some() { 0b0001_0000 } else { 0 } | if place_object.color_transform.is_some() { 0b0000_1000 } else { 0 } | if place_object.matrix.is_some() { 0b0000_0100 } else { 0 } | match place_object.action { PlaceObjectAction::Place(_) => 0b10, PlaceObjectAction::Modify => 0b01, PlaceObjectAction::Replace(_) => 0b11, }, )?; if place_object_version >= 3 { writer.write_u8( if place_object.background_color.is_some() { 0b100_0000 } else { 0 } | if place_object.is_visible.is_some() { 0b10_0000 } else { 0 } | if place_object.is_image { 0b1_0000 } else { 0 } | if place_object.class_name.is_some() { 0b1000 } else { 0 } | if place_object.is_bitmap_cached.is_some() { 0b100 } else { 0 } | if place_object.blend_mode.is_some() { 0b10 } else { 0 } | if place_object.filters.is_some() { 0b1 } else { 0 }, )?; } writer.write_u16(place_object.depth)?; if place_object_version >= 3 { if let Some(ref class_name) = place_object.class_name { writer.write_c_string(class_name)?; } } match place_object.action { PlaceObjectAction::Place(character_id) | PlaceObjectAction::Replace(character_id) => writer.write_u16(character_id)?, PlaceObjectAction::Modify => (), } if let Some(ref matrix) = place_object.matrix { writer.write_matrix(matrix)?; }; if let Some(ref color_transform) = place_object.color_transform { writer.write_color_transform(color_transform)?; }; if let Some(ratio) = place_object.ratio { writer.write_u16(ratio)?; } if let Some(ref name) = place_object.name { writer.write_c_string(name)?; }; if let Some(clip_depth) = place_object.clip_depth { writer.write_u16(clip_depth)?; } if place_object_version >= 3 { if let Some(filters) = &place_object.filters { writer.write_u8(filters.len() as u8)?; for filter in filters { writer.write_filter(filter)?; } } if let Some(blend_mode) = place_object.blend_mode { writer.write_blend_mode(blend_mode)?; } if let Some(is_bitmap_cached) = place_object.is_bitmap_cached { writer.write_u8(if is_bitmap_cached { 1 } else { 0 })?; } if let Some(is_visible) = place_object.is_visible { writer.write_u8(if is_visible { 1 } else { 0 })?; } if let Some(ref background_color) = place_object.background_color { writer.write_rgba(background_color)?; } } if let Some(clip_actions) = &place_object.clip_actions { writer.write_clip_actions(clip_actions)?; } writer.flush_bits()?; // PlaceObject4 adds some embedded AMF data per instance. if place_object_version >= 4 { if let Some(ref data) = place_object.amf_data { writer.output.write_all(data)?; } } } let tag_code = match place_object_version { 2 => TagCode::PlaceObject2, 3 => TagCode::PlaceObject3, 4 => TagCode::PlaceObject4, _ => return Err(Error::invalid_data("Invalid PlaceObject version.")), }; self.write_tag_header(tag_code, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_filter(&mut self, filter: &Filter) -> Result<()> { match *filter { Filter::DropShadowFilter(ref drop_shadow) => { self.write_u8(0)?; self.write_rgba(&drop_shadow.color)?; self.write_fixed16(drop_shadow.blur_x)?; self.write_fixed16(drop_shadow.blur_y)?; self.write_fixed16(drop_shadow.angle)?; self.write_fixed16(drop_shadow.distance)?; self.write_fixed8(drop_shadow.strength)?; self.write_bit(drop_shadow.is_inner)?; self.write_bit(drop_shadow.is_knockout)?; self.write_bit(true)?; self.write_ubits(5, drop_shadow.num_passes.into())?; } Filter::BlurFilter(ref blur) => { self.write_u8(1)?; self.write_fixed16(blur.blur_x)?; self.write_fixed16(blur.blur_y)?; self.write_u8(blur.num_passes << 3)?; } Filter::GlowFilter(ref glow) => { self.write_u8(2)?; self.write_rgba(&glow.color)?; self.write_fixed16(glow.blur_x)?; self.write_fixed16(glow.blur_y)?; self.write_fixed8(glow.strength)?; self.write_bit(glow.is_inner)?; self.write_bit(glow.is_knockout)?; self.write_bit(true)?; self.write_ubits(5, glow.num_passes.into())?; } Filter::BevelFilter(ref bevel) => { self.write_u8(3)?; self.write_rgba(&bevel.shadow_color)?; self.write_rgba(&bevel.highlight_color)?; self.write_fixed16(bevel.blur_x)?; self.write_fixed16(bevel.blur_y)?; self.write_fixed16(bevel.angle)?; self.write_fixed16(bevel.distance)?; self.write_fixed8(bevel.strength)?; self.write_bit(bevel.is_inner)?; self.write_bit(bevel.is_knockout)?; self.write_bit(true)?; self.write_bit(bevel.is_on_top)?; self.write_ubits(4, bevel.num_passes.into())?; } Filter::GradientGlowFilter(ref glow) => { self.write_u8(4)?; self.write_u8(glow.colors.len() as u8)?; for gradient_record in &glow.colors { self.write_rgba(&gradient_record.color)?; } for gradient_record in &glow.colors { self.write_u8(gradient_record.ratio)?; } self.write_fixed16(glow.blur_x)?; self.write_fixed16(glow.blur_y)?; self.write_fixed16(glow.angle)?; self.write_fixed16(glow.distance)?; self.write_fixed8(glow.strength)?; self.write_bit(glow.is_inner)?; self.write_bit(glow.is_knockout)?; self.write_bit(true)?; self.write_bit(glow.is_on_top)?; self.write_ubits(4, glow.num_passes.into())?; } Filter::ConvolutionFilter(ref convolve) => { self.write_u8(5)?; self.write_u8(convolve.num_matrix_cols)?; self.write_u8(convolve.num_matrix_rows)?; self.write_fixed16(convolve.divisor)?; self.write_fixed16(convolve.bias)?; for val in &convolve.matrix { self.write_fixed16(*val)?; } self.write_rgba(&convolve.default_color)?; self.write_u8( if convolve.is_clamped { 0b10 } else { 0 } | if convolve.is_preserve_alpha { 0b1 } else { 0 }, )?; } Filter::ColorMatrixFilter(ref color_matrix) => { self.write_u8(6)?; for i in 0..20 { self.write_fixed16(color_matrix.matrix[i])?; } } Filter::GradientBevelFilter(ref bevel) => { self.write_u8(7)?; self.write_u8(bevel.colors.len() as u8)?; for gradient_record in &bevel.colors { self.write_rgba(&gradient_record.color)?; } for gradient_record in &bevel.colors { self.write_u8(gradient_record.ratio)?; } self.write_fixed16(bevel.blur_x)?; self.write_fixed16(bevel.blur_y)?; self.write_fixed16(bevel.angle)?; self.write_fixed16(bevel.distance)?; self.write_fixed8(bevel.strength)?; self.write_bit(bevel.is_inner)?; self.write_bit(bevel.is_knockout)?; self.write_bit(true)?; self.write_bit(bevel.is_on_top)?; self.write_ubits(4, bevel.num_passes.into())?; } } self.flush_bits()?; Ok(()) } fn write_clip_actions(&mut self, clip_actions: &[ClipAction]) -> Result<()> { self.write_u16(0)?; // Reserved { let mut all_events = EnumSet::new(); for action in clip_actions { all_events |= action.events; } self.write_clip_event_flags(all_events)?; } for action in clip_actions { self.write_clip_event_flags(action.events)?; let action_length = action.action_data.len() as u32 + if action.key_code.is_some() { 1 } else { 0 }; self.write_u32(action_length)?; if let Some(k) = action.key_code { self.write_u8(k)?; } self.output.write_all(&action.action_data)?; } if self.version <= 5 { self.write_u16(0)?; } else { self.write_u32(0)?; } Ok(()) } fn write_clip_event_flags(&mut self, clip_events: EnumSet<ClipEventFlag>) -> Result<()> { // TODO: Assert proper version. self.write_bit(clip_events.contains(ClipEventFlag::KeyUp))?; self.write_bit(clip_events.contains(ClipEventFlag::KeyDown))?; self.write_bit(clip_events.contains(ClipEventFlag::MouseUp))?; self.write_bit(clip_events.contains(ClipEventFlag::MouseDown))?; self.write_bit(clip_events.contains(ClipEventFlag::MouseMove))?; self.write_bit(clip_events.contains(ClipEventFlag::Unload))?; self.write_bit(clip_events.contains(ClipEventFlag::EnterFrame))?; self.write_bit(clip_events.contains(ClipEventFlag::Load))?; self.write_bit(clip_events.contains(ClipEventFlag::DragOver))?; self.write_bit(clip_events.contains(ClipEventFlag::RollOut))?; self.write_bit(clip_events.contains(ClipEventFlag::RollOver))?; self.write_bit(clip_events.contains(ClipEventFlag::ReleaseOutside))?; self.write_bit(clip_events.contains(ClipEventFlag::Release))?; self.write_bit(clip_events.contains(ClipEventFlag::Press))?; self.write_bit(clip_events.contains(ClipEventFlag::Initialize))?; self.write_bit(clip_events.contains(ClipEventFlag::Data))?; if self.version >= 6 { self.write_ubits(5, 0)?; self.write_bit(clip_events.contains(ClipEventFlag::Construct))?; self.write_bit(clip_events.contains(ClipEventFlag::KeyPress))?; self.write_bit(clip_events.contains(ClipEventFlag::DragOut))?; self.write_u8(0)?; } self.flush_bits()?; Ok(()) } fn write_sound_stream_head( &mut self, stream_head: &SoundStreamHead, version: u8, ) -> Result<()> { let tag_code = if version >= 2 { TagCode::SoundStreamHead2 } else { TagCode::SoundStreamHead }; // MP3 compression has added latency seek field. let length = if stream_head.stream_format.compression == AudioCompression::Mp3 { 6 } else { 4 }; self.write_tag_header(tag_code, length)?; self.write_sound_format(&stream_head.playback_format)?; self.write_sound_format(&stream_head.stream_format)?; self.write_u16(stream_head.num_samples_per_block)?; if stream_head.stream_format.compression == AudioCompression::Mp3 { self.write_i16(stream_head.latency_seek)?; } Ok(()) } fn write_sound_format(&mut self, sound_format: &SoundFormat) -> Result<()> { self.write_ubits( 4, match sound_format.compression { AudioCompression::UncompressedUnknownEndian => 0, AudioCompression::Adpcm => 1, AudioCompression::Mp3 => 2, AudioCompression::Uncompressed => 3, AudioCompression::Nellymoser16Khz => 4, AudioCompression::Nellymoser8Khz => 5, AudioCompression::Nellymoser => 6, AudioCompression::Speex => 11, }, )?; self.write_ubits( 2, match sound_format.sample_rate { 5512 => 0, 11025 => 1, 22050 => 2, 44100 => 3, _ => return Err(Error::invalid_data("Invalid sample rate.")), }, )?; self.write_bit(sound_format.is_16_bit)?; self.write_bit(sound_format.is_stereo)?; self.flush_bits()?; Ok(()) } fn write_sound_info(&mut self, sound_info: &SoundInfo) -> Result<()> { let flags = match sound_info.event { SoundEvent::Event => 0b00_0000u8, SoundEvent::Start => 0b01_0000u8, SoundEvent::Stop => 0b10_0000u8, } | if sound_info.in_sample.is_some() { 0b1 } else { 0 } | if sound_info.out_sample.is_some() { 0b10 } else { 0 } | if sound_info.num_loops > 1 { 0b100 } else { 0 } | if sound_info.envelope.is_some() { 0b1000 } else { 0 }; self.write_u8(flags)?; if let Some(n) = sound_info.in_sample { self.write_u32(n)?; } if let Some(n) = sound_info.out_sample { self.write_u32(n)?; } if sound_info.num_loops > 1 { self.write_u16(sound_info.num_loops)?; } if let Some(ref envelope) = sound_info.envelope { self.write_u8(envelope.len() as u8)?; for point in envelope { self.write_u32(point.sample)?; self.write_u16((point.left_volume * 32768f32) as u16)?; self.write_u16((point.right_volume * 32768f32) as u16)?; } } Ok(()) } fn write_define_font_2(&mut self, font: &Font) -> Result<()> { let mut buf = Vec::new(); { let num_glyphs = font.glyphs.len(); // We must write the glyph shapes into a temporary buffer // so that we can calculate their offsets. let mut offsets = vec![]; let mut has_wide_offsets = false; let has_wide_codes = !font.is_ansi; let mut shape_buf = Vec::new(); { let mut shape_writer = Writer::new(&mut shape_buf, self.version); // ShapeTable shape_writer.num_fill_bits = 1; shape_writer.num_line_bits = 0; for glyph in &font.glyphs { // Store offset for later. let offset = num_glyphs * 4 + shape_writer.output.len(); offsets.push(offset); if offset > 0xFFFF { has_wide_offsets = true; } shape_writer.write_ubits(4, 1)?; shape_writer.write_ubits(4, 0)?; for shape_record in &glyph.shape_records { shape_writer.write_shape_record(shape_record, 1)?; } // End shape record. shape_writer.write_ubits(6, 0)?; shape_writer.flush_bits()?; } } let mut writer = Writer::new(&mut buf, self.version); writer.write_character_id(font.id)?; writer.write_u8( if font.layout.is_some() { 0b10000000 } else { 0 } | if font.is_shift_jis { 0b1000000 } else { 0 } | if font.is_small_text { 0b100000 } else { 0 } | if font.is_ansi { 0b10000 } else { 0 } | if has_wide_offsets { 0b1000 } else { 0 } | if has_wide_codes { 0b100 } else { 0 } | if font.is_italic { 0b10 } else { 0 } | if font.is_bold { 0b1 } else { 0 }, )?; writer.write_language(font.language)?; writer.write_u8(font.name.len() as u8)?; writer.output.write_all(font.name.as_bytes())?; writer.write_u16(num_glyphs as u16)?; // If there are no glyphs, then the following tables are omitted. if num_glyphs > 0 { // OffsetTable for offset in offsets { if has_wide_offsets { writer.write_u32(offset as u32)?; } else { writer.write_u16(offset as u16)?; } } // CodeTableOffset let code_table_offset = (num_glyphs + 1) * if has_wide_offsets { 4 } else { 2 } + shape_buf.len(); if has_wide_offsets { writer.write_u32(code_table_offset as u32)?; } else { writer.write_u16(code_table_offset as u16)?; } writer.output.write_all(&shape_buf)?; // CodeTable for glyph in &font.glyphs { if has_wide_codes { writer.write_u16(glyph.code)?; } else { writer.write_u8(glyph.code as u8)?; } } } if let Some(ref layout) = font.layout { writer.write_u16(layout.ascent)?; writer.write_u16(layout.descent)?; writer.write_i16(layout.leading)?; for glyph in &font.glyphs { writer.write_i16( glyph .advance .ok_or_else(|| Error::invalid_data("glyph.advance cannot be None"))?, )?; } for glyph in &font.glyphs { writer.write_rectangle( glyph .bounds .as_ref() .ok_or_else(|| Error::invalid_data("glyph.bounds cannot be None"))?, )?; } writer.write_u16(layout.kerning.len() as u16)?; for kerning_record in &layout.kerning { writer.write_kerning_record(kerning_record, has_wide_codes)?; } } } let tag_code = if font.version == 2 { TagCode::DefineFont2 } else { TagCode::DefineFont3 }; self.write_tag_header(tag_code, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_define_font_4(&mut self, font: &Font4) -> Result<()> { let mut tag_len = 4 + font.name.len(); if let Some(ref data) = font.data { tag_len += data.len() }; self.write_tag_header(TagCode::DefineFont4, tag_len as u32)?; self.write_character_id(font.id)?; self.write_u8( if font.data.is_some() { 0b100 } else { 0 } | if font.is_italic { 0b10 } else { 0 } | if font.is_bold { 0b1 } else { 0 }, )?; self.write_c_string(&font.name)?; if let Some(ref data) = font.data { self.output.write_all(data)?; } Ok(()) } fn write_kerning_record( &mut self, kerning: &KerningRecord, has_wide_codes: bool, ) -> Result<()> { if has_wide_codes { self.write_u16(kerning.left_code)?; self.write_u16(kerning.right_code)?; } else { self.write_u8(kerning.left_code as u8)?; self.write_u8(kerning.right_code as u8)?; } self.write_i16(kerning.adjustment.get() as i16)?; // TODO(Herschel): Handle overflow Ok(()) } fn write_define_text(&mut self, text: &Text) -> Result<()> { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_character_id(text.id)?; writer.write_rectangle(&text.bounds)?; writer.write_matrix(&text.matrix)?; let num_glyph_bits = text .records .iter() .flat_map(|r| r.glyphs.iter().map(|g| count_ubits(g.index))) .max() .unwrap_or(0); let num_advance_bits = text .records .iter() .flat_map(|r| r.glyphs.iter().map(|g| count_sbits(g.advance))) .max() .unwrap_or(0); writer.write_u8(num_glyph_bits)?; writer.write_u8(num_advance_bits)?; for record in &text.records { let flags = 0b10000000 | if record.font_id.is_some() { 0b1000 } else { 0 } | if record.color.is_some() { 0b100 } else { 0 } | if record.y_offset.is_some() { 0b10 } else { 0 } | if record.x_offset.is_some() { 0b1 } else { 0 }; writer.write_u8(flags)?; if let Some(id) = record.font_id { writer.write_character_id(id)?; } if let Some(ref color) = record.color { writer.write_rgb(color)?; } if let Some(x) = record.x_offset { writer.write_i16(x.get() as i16)?; // TODO(Herschel): Handle overflow. } if let Some(y) = record.y_offset { writer.write_i16(y.get() as i16)?; } if let Some(height) = record.height { writer.write_u16(height.get() as u16)?; } writer.write_u8(record.glyphs.len() as u8)?; for glyph in &record.glyphs { writer.write_ubits(num_glyph_bits, glyph.index)?; writer.write_sbits(num_advance_bits, glyph.advance)?; } } writer.write_u8(0)?; // End of text records. } self.write_tag_header(TagCode::DefineText, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_define_edit_text(&mut self, edit_text: &EditText) -> Result<()> { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, self.version); writer.write_character_id(edit_text.id)?; writer.write_rectangle(&edit_text.bounds)?; let flags = if edit_text.initial_text.is_some() { 0b10000000 } else { 0 } | if edit_text.is_word_wrap { 0b1000000 } else { 0 } | if edit_text.is_multiline { 0b100000 } else { 0 } | if edit_text.is_password { 0b10000 } else { 0 } | if edit_text.is_read_only { 0b1000 } else { 0 } | if edit_text.color.is_some() { 0b100 } else { 0 } | if edit_text.max_length.is_some() { 0b10 } else { 0 } | if edit_text.font_id.is_some() { 0b1 } else { 0 }; let flags2 = if edit_text.font_class_name.is_some() { 0b10000000 } else { 0 } | if edit_text.is_auto_size { 0b1000000 } else { 0 } | if edit_text.layout.is_some() { 0b100000 } else { 0 } | if !edit_text.is_selectable { 0b10000 } else { 0 } | if edit_text.has_border { 0b1000 } else { 0 } | if edit_text.was_static { 0b100 } else { 0 } | if edit_text.is_html { 0b10 } else { 0 } | if !edit_text.is_device_font { 0b1 } else { 0 }; writer.write_u8(flags)?; writer.write_u8(flags2)?; if let Some(font_id) = edit_text.font_id { writer.write_character_id(font_id)?; } // TODO(Herschel): Check SWF version. if let Some(ref class) = edit_text.font_class_name { writer.write_c_string(class)?; } // TODO(Herschel): Height only exists iff HasFontId, maybe for HasFontClass too? if let Some(height) = edit_text.height { writer.write_u16(height.get() as u16)? } if let Some(ref color) = edit_text.color { writer.write_rgba(color)? } if let Some(len) = edit_text.max_length { writer.write_u16(len)?; } if let Some(ref layout) = edit_text.layout { writer.write_u8(match layout.align { TextAlign::Left => 0, TextAlign::Right => 1, TextAlign::Center => 2, TextAlign::Justify => 3, })?; writer.write_u16(layout.left_margin.get() as u16)?; // TODO: Handle overflow writer.write_u16(layout.right_margin.get() as u16)?; writer.write_u16(layout.indent.get() as u16)?; writer.write_i16(layout.leading.get() as i16)?; } writer.write_c_string(&edit_text.variable_name)?; if let Some(ref text) = edit_text.initial_text { writer.write_c_string(text)?; } } self.write_tag_header(TagCode::DefineEditText, buf.len() as u32)?; self.output.write_all(&buf)?; Ok(()) } fn write_define_video_stream(&mut self, video: &DefineVideoStream) -> Result<()> { self.write_tag_header(TagCode::DefineVideoStream, 10)?; self.write_character_id(video.id)?; self.write_u16(video.num_frames)?; self.write_u16(video.width)?; self.write_u16(video.height)?; self.write_u8( match video.deblocking { VideoDeblocking::UseVideoPacketValue => 0b000_0, VideoDeblocking::None => 0b001_0, VideoDeblocking::Level1 => 0b010_0, VideoDeblocking::Level2 => 0b011_0, VideoDeblocking::Level3 => 0b100_0, VideoDeblocking::Level4 => 0b101_0, } | if video.is_smoothed { 0b1 } else { 0 }, )?; self.write_u8(match video.codec { VideoCodec::H263 => 2, VideoCodec::ScreenVideo => 3, VideoCodec::VP6 => 4, VideoCodec::VP6WithAlpha => 5, })?; Ok(()) } fn write_product_info(&mut self, product_info: &ProductInfo) -> Result<()> { self.write_tag_header(TagCode::ProductInfo, 26)?; self.write_u32(product_info.product_id)?; self.write_u32(product_info.edition)?; self.write_u8(product_info.major_version)?; self.write_u8(product_info.minor_version)?; self.write_u64(product_info.build_number)?; self.write_u64(product_info.compilation_date)?; Ok(()) } fn write_debug_id(&mut self, debug_id: &DebugId) -> Result<()> { self.get_inner().write_all(debug_id)?; Ok(()) } fn write_tag_header(&mut self, tag_code: TagCode, length: u32) -> Result<()> { self.write_tag_code_and_length(tag_code as u16, length) } fn write_tag_code_and_length(&mut self, tag_code: u16, length: u32) -> Result<()> { // TODO: Test for tag code/length overflow. let mut tag_code_and_length: u16 = tag_code << 6; if length < 0b111111 { tag_code_and_length |= length as u16; self.write_u16(tag_code_and_length)?; } else { tag_code_and_length |= 0b111111; self.write_u16(tag_code_and_length)?; self.write_u32(length)?; } Ok(()) } fn write_tag_list(&mut self, tags: &[Tag]) -> Result<()> { // TODO: Better error handling. Can skip errored tags, unless EOF. for tag in tags { self.write_tag(tag)?; } // Implicit end tag. self.write_tag(&Tag::End)?; Ok(()) } } fn count_ubits(mut n: u32) -> u8 { let mut num_bits = 0; while n > 0 { n >>= 1; num_bits += 1; } num_bits } fn count_sbits(n: i32) -> u8 { if n == 0 { 0 } else if n == -1 { 1 } else if n < 0 { count_ubits((!n) as u32) + 1 } else { count_ubits(n as u32) + 1 } } fn count_sbits_twips(n: Twips) -> u8 { let n = n.get(); if n == 0 { 0 } else if n == -1 { 1 } else if n < 0 { count_ubits((!n) as u32) + 1 } else { count_ubits(n as u32) + 1 } } fn count_fbits(n: f32) -> u8 { count_sbits((n * 65536f32) as i32) } #[cfg(test)] mod tests { use super::Writer; use super::*; use crate::test_data; fn new_swf() -> Swf { Swf { header: Header { compression: Compression::Zlib, version: 13, uncompressed_length: 1024, stage_size: Rectangle { x_min: Twips::from_pixels(0.0), x_max: Twips::from_pixels(640.0), y_min: Twips::from_pixels(0.0), y_max: Twips::from_pixels(480.0), }, frame_rate: 60.0, num_frames: 1, }, tags: vec![], } } #[test] fn write_swfs() { fn write_dummy_swf(compression: Compression) -> Result<()> { let mut buf = Vec::new(); let mut swf = new_swf(); swf.header.compression = compression; write_swf(&swf, &mut buf)?; Ok(()) } assert!( write_dummy_swf(Compression::None).is_ok(), "Failed to write uncompressed SWF." ); assert!( write_dummy_swf(Compression::Zlib).is_ok(), "Failed to write zlib SWF." ); if cfg!(feature = "lzma") { assert!( write_dummy_swf(Compression::Lzma).is_ok(), "Failed to write LZMA SWF." ); } } #[test] fn write_fixed8() { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_fixed8(0f32).unwrap(); writer.write_fixed8(1f32).unwrap(); writer.write_fixed8(6.5f32).unwrap(); writer.write_fixed8(-20.75f32).unwrap(); } assert_eq!( buf, [ 0b00000000, 0b00000000, 0b00000000, 0b00000001, 0b10000000, 0b00000110, 0b01000000, 0b11101011 ] ); } #[test] fn write_encoded_u32() { fn write_to_buf(n: u32) -> Vec<u8> { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_encoded_u32(n).unwrap(); } buf } assert_eq!(write_to_buf(0), [0]); assert_eq!(write_to_buf(2), [2]); assert_eq!(write_to_buf(129), [0b1_0000001, 0b0_0000001]); assert_eq!( write_to_buf(0b1100111_0000001_0000001), [0b1_0000001, 0b1_0000001, 0b0_1100111] ); assert_eq!( write_to_buf(0b1111_0000000_0000000_0000000_0000000u32), [ 0b1_0000000, 0b1_0000000, 0b1_0000000, 0b1_0000000, 0b0000_1111 ] ); } #[test] fn write_bit() { let bits = [ false, true, false, true, false, true, false, true, false, false, true, false, false, true, false, true, ]; let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); for b in &bits { writer.write_bit(*b).unwrap(); } } assert_eq!(buf, [0b01010101, 0b00100101]); } #[test] fn write_ubits() { let num_bits = 2; let nums = [1, 1, 1, 1, 0, 2, 1, 1]; let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); for n in &nums { writer.write_ubits(num_bits, *n).unwrap(); } writer.flush_bits().unwrap(); } assert_eq!(buf, [0b01010101, 0b00100101]); } #[test] fn write_sbits() { let num_bits = 2; let nums = [1, 1, 1, 1, 0, -2, 1, 1]; let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); for n in &nums { writer.write_sbits(num_bits, *n).unwrap(); } writer.flush_bits().unwrap(); } assert_eq!(buf, [0b01010101, 0b00100101]); } #[test] fn write_fbits() { let num_bits = 18; let nums = [1f32, -1f32]; let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); for n in &nums { writer.write_fbits(num_bits, *n).unwrap(); } writer.flush_bits().unwrap(); } assert_eq!( buf, [ 0b01_000000, 0b00000000, 0b00_11_0000, 0b00000000, 0b0000_0000 ] ); } #[test] fn count_ubits() { assert_eq!(super::count_ubits(0), 0u8); assert_eq!(super::count_ubits(1u32), 1); assert_eq!(super::count_ubits(2u32), 2); assert_eq!(super::count_ubits(0b_00111101_00000000u32), 14); } #[test] fn count_sbits() { assert_eq!(super::count_sbits(0), 0u8); assert_eq!(super::count_sbits(1), 2u8); assert_eq!(super::count_sbits(2), 3u8); assert_eq!(super::count_sbits(0b_00111101_00000000), 15u8); assert_eq!(super::count_sbits(-1), 1u8); assert_eq!(super::count_sbits(-2), 2u8); assert_eq!(super::count_sbits(-0b_00110101_01010101), 15u8); } #[test] fn write_c_string() { { let mut buf = Vec::new(); { // TODO: What if I use a cursor instead of buf ? let mut writer = Writer::new(&mut buf, 1); writer.write_c_string("Hello!").unwrap(); } assert_eq!(buf, "Hello!\0".bytes().collect::<Vec<_>>()); } { let mut buf = Vec::new(); { // TODO: What if I use a cursor instead of buf ? let mut writer = Writer::new(&mut buf, 1); writer.write_c_string("😀😂!🐼").unwrap(); } assert_eq!(buf, "😀😂!🐼\0".bytes().collect::<Vec<_>>()); } } #[test] fn write_rectangle_zero() { let rect: Rectangle = Default::default(); let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_rectangle(&rect).unwrap(); writer.flush_bits().unwrap(); } assert_eq!(buf, [0]); } #[test] fn write_rectangle_signed() { let rect = Rectangle { x_min: Twips::from_pixels(-1.0), x_max: Twips::from_pixels(1.0), y_min: Twips::from_pixels(-1.0), y_max: Twips::from_pixels(1.0), }; let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_rectangle(&rect).unwrap(); writer.flush_bits().unwrap(); } assert_eq!(buf, [0b_00110_101, 0b100_01010, 0b0_101100_0, 0b_10100_000]); } #[test] fn write_color() { { let color = Color { r: 1, g: 128, b: 255, a: 255, }; let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_rgb(&color).unwrap(); } assert_eq!(buf, [1, 128, 255]); } { let color = Color { r: 1, g: 2, b: 3, a: 11, }; let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_rgba(&color).unwrap(); } assert_eq!(buf, [1, 2, 3, 11]); } } #[test] fn write_matrix() { fn write_to_buf(m: &Matrix) -> Vec<u8> { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_matrix(m).unwrap(); writer.flush_bits().unwrap(); } buf } let m = Matrix::identity(); assert_eq!(write_to_buf(&m), [0]); } #[test] fn write_tags() { for (swf_version, tag, expected_tag_bytes) in test_data::tag_tests() { let mut written_tag_bytes = Vec::new(); Writer::new(&mut written_tag_bytes, swf_version) .write_tag(&tag) .unwrap(); if written_tag_bytes != expected_tag_bytes { panic!( "Error reading tag.\nTag:\n{:?}\n\nWrote:\n{:?}\n\nExpected:\n{:?}", tag, written_tag_bytes, expected_tag_bytes ); } } } #[test] fn write_tag_to_buf_list() { { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_tag_list(&[]).unwrap(); } assert_eq!(buf, [0, 0]); } { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer.write_tag_list(&[Tag::ShowFrame]).unwrap(); } assert_eq!(buf, [0b01_000000, 0b00000000, 0, 0]); } { let mut buf = Vec::new(); { let mut writer = Writer::new(&mut buf, 1); writer .write_tag_list(&[ Tag::Unknown { tag_code: 512, data: vec![0; 100], }, Tag::ShowFrame, ]) .unwrap(); } let mut expected = vec![0b00_111111, 0b10000000, 100, 0, 0, 0]; expected.extend_from_slice(&[0; 100]); expected.extend_from_slice(&[0b01_000000, 0b00000000, 0, 0]); assert_eq!(buf, expected); } } }
36.340755
169
0.486681
1ca5689ff2eaea77a1024af2d29d91ccca326b24
660
//#![feature(nothreads)] #[macro_use] extern crate slog; use slog::{Fuse, Logger}; use std::cell::RefCell; use std::rc::Rc; mod common; #[derive(Clone)] struct NoThreadSafeObject { val: Rc<RefCell<usize>>, } fn main() { let log = Logger::root(Fuse(common::PrintlnDrain), o!("version" => "2")); let obj = NoThreadSafeObject { val: Rc::new(RefCell::new(4)), }; // Move obj2 into a closure. Since it's !Send, this only works // with nothreads feature. let obj2 = obj.clone(); let sublog = log.new(o!("obj.val" => slog::FnValue(move |_| { format!("{}", obj2.val.borrow()) }))); info!(sublog, "test"); }
22
77
0.593939
d9dc0f3038afab5ed1c544a56980e14f57872a82
23,099
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Substrate is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Substrate. If not, see <http://www.gnu.org/licenses/>. //! Peer Set Manager (PSM). Contains the strategy for choosing which nodes the network should be //! connected to. mod slots; use std::collections::VecDeque; use futures::{prelude::*, sync::mpsc, try_ready}; use libp2p::PeerId; use linked_hash_map::LinkedHashMap; use log::trace; use lru_cache::LruCache; use slots::{SlotType, SlotState, Slots}; pub use serde_json::Value; const PEERSET_SCORES_CACHE_SIZE: usize = 1000; /// FIFO-ordered list of nodes that we know exist, but we are not connected to. #[derive(Debug, Default)] struct Discovered { /// Nodes we should connect to first. reserved: LinkedHashMap<PeerId, ()>, /// All remaining nodes. common: LinkedHashMap<PeerId, ()>, } impl Discovered { /// Returns true if we already know given node. fn contains(&self, peer_id: &PeerId) -> bool { self.reserved.contains_key(peer_id) || self.common.contains_key(peer_id) } /// Returns true if given node is reserved. fn is_reserved(&self, peer_id: &PeerId) -> bool { self.reserved.contains_key(peer_id) } /// Adds new peer of a given type. fn add_peer(&mut self, peer_id: PeerId, slot_type: SlotType) { if !self.contains(&peer_id) { match slot_type { SlotType::Common => self.common.insert(peer_id, ()), SlotType::Reserved => self.reserved.insert(peer_id, ()), }; } } /// Pops the oldest peer from the list. fn pop_peer(&mut self, reserved_only: bool) -> Option<(PeerId, SlotType)> { if let Some((peer_id, _)) = self.reserved.pop_front() { return Some((peer_id, SlotType::Reserved)); } if reserved_only { return None; } self.common.pop_front() .map(|(peer_id, _)| (peer_id, SlotType::Common)) } /// Marks the node as not reserved. fn mark_not_reserved(&mut self, peer_id: &PeerId) { if let Some(_) = self.reserved.remove(peer_id) { self.common.insert(peer_id.clone(), ()); } } /// Removes the node from the list. fn remove_peer(&mut self, peer_id: &PeerId) { self.reserved.remove(peer_id); self.common.remove(peer_id); } } #[derive(Debug)] struct PeersetData { /// List of nodes that we know exist, but we are not connected to. /// Elements in this list must never be in `out_slots` or `in_slots`. discovered: Discovered, /// If true, we only accept reserved nodes. reserved_only: bool, /// Node slots for outgoing connections. out_slots: Slots, /// Node slots for incoming connections. in_slots: Slots, /// List of node scores. scores: LruCache<PeerId, i32>, } #[derive(Debug)] enum Action { AddReservedPeer(PeerId), RemoveReservedPeer(PeerId), SetReservedOnly(bool), ReportPeer(PeerId, i32), } /// Shared handle to the peer set manager (PSM). Distributed around the code. #[derive(Debug, Clone)] pub struct PeersetHandle { tx: mpsc::UnboundedSender<Action>, } impl PeersetHandle { /// Adds a new reserved peer. The peerset will make an effort to always remain connected to /// this peer. /// /// Has no effect if the node was already a reserved peer. /// /// > **Note**: Keep in mind that the networking has to know an address for this node, /// > otherwise it will not be able to connect to it. pub fn add_reserved_peer(&self, peer_id: PeerId) { let _ = self.tx.unbounded_send(Action::AddReservedPeer(peer_id)); } /// Remove a previously-added reserved peer. /// /// Has no effect if the node was not a reserved peer. pub fn remove_reserved_peer(&self, peer_id: PeerId) { let _ = self.tx.unbounded_send(Action::RemoveReservedPeer(peer_id)); } /// Sets whether or not the peerset only has connections . pub fn set_reserved_only(&self, reserved: bool) { let _ = self.tx.unbounded_send(Action::SetReservedOnly(reserved)); } /// Reports an adjustment to the reputation of the given peer. pub fn report_peer(&self, peer_id: PeerId, score_diff: i32) { let _ = self.tx.unbounded_send(Action::ReportPeer(peer_id, score_diff)); } } /// Message that can be sent by the peer set manager (PSM). #[derive(Debug, PartialEq)] pub enum Message { /// Request to open a connection to the given peer. From the point of view of the PSM, we are /// immediately connected. Connect(PeerId), /// Drop the connection to the given peer, or cancel the connection attempt after a `Connect`. Drop(PeerId), /// Equivalent to `Connect` for the peer corresponding to this incoming index. Accept(IncomingIndex), /// Equivalent to `Drop` for the peer corresponding to this incoming index. Reject(IncomingIndex), } /// Opaque identifier for an incoming connection. Allocated by the network. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct IncomingIndex(pub u64); impl From<u64> for IncomingIndex { fn from(val: u64) -> IncomingIndex { IncomingIndex(val) } } /// Configuration to pass when creating the peer set manager. #[derive(Debug)] pub struct PeersetConfig { /// Maximum number of ingoing links to peers. pub in_peers: u32, /// Maximum number of outgoing links to peers. pub out_peers: u32, /// List of bootstrap nodes to initialize the peer with. /// /// > **Note**: Keep in mind that the networking has to know an address for these nodes, /// > otherwise it will not be able to connect to them. pub bootnodes: Vec<PeerId>, /// If true, we only accept reserved nodes. pub reserved_only: bool, /// List of nodes that we should always be connected to. /// /// > **Note**: Keep in mind that the networking has to know an address for these nodes, /// > otherwise it will not be able to connect to them. pub reserved_nodes: Vec<PeerId>, } /// Side of the peer set manager owned by the network. In other words, the "receiving" side. /// /// Implements the `Stream` trait and can be polled for messages. The `Stream` never ends and never /// errors. #[derive(Debug)] pub struct Peerset { data: PeersetData, rx: mpsc::UnboundedReceiver<Action>, message_queue: VecDeque<Message>, } impl Peerset { /// Builds a new peerset from the given configuration. pub fn from_config(config: PeersetConfig) -> (Peerset, PeersetHandle) { let (tx, rx) = mpsc::unbounded(); let data = PeersetData { discovered: Default::default(), reserved_only: config.reserved_only, out_slots: Slots::new(config.out_peers), in_slots: Slots::new(config.in_peers), scores: LruCache::new(PEERSET_SCORES_CACHE_SIZE), }; let handle = PeersetHandle { tx, }; let mut peerset = Peerset { data, rx, message_queue: VecDeque::new(), }; for peer_id in config.reserved_nodes { peerset.data.discovered.add_peer(peer_id, SlotType::Reserved); } for peer_id in config.bootnodes { peerset.data.discovered.add_peer(peer_id, SlotType::Common); } peerset.alloc_slots(); (peerset, handle) } fn on_add_reserved_peer(&mut self, peer_id: PeerId) { // Nothing more to do if we're already connected. if self.data.in_slots.contains(&peer_id) { self.data.in_slots.mark_reserved(&peer_id); return; } match self.data.out_slots.add_peer(peer_id, SlotType::Reserved) { SlotState::Added(peer_id) => { // reserved node may have been previously stored as normal node in discovered list self.data.discovered.remove_peer(&peer_id); // notify that connection has been made trace!(target: "peerset", "Connecting to new reserved peer {}", peer_id); self.message_queue.push_back(Message::Connect(peer_id)); return; }, SlotState::Swaped { removed, added } => { // reserved node may have been previously stored as normal node in discovered list self.data.discovered.remove_peer(&added); // let's add the peer we disconnected from to the discovered list again self.data.discovered.add_peer(removed.clone(), SlotType::Common); // swap connections trace!(target: "peerset", "Connecting to new reserved peer {}, dropping {}", added, removed); self.message_queue.push_back(Message::Drop(removed)); self.message_queue.push_back(Message::Connect(added)); } SlotState::AlreadyConnected(_) | SlotState::Upgraded(_) => { return; } SlotState::MaxConnections(peer_id) => { self.data.discovered.add_peer(peer_id, SlotType::Reserved); return; } } } fn on_remove_reserved_peer(&mut self, peer_id: PeerId) { self.data.in_slots.mark_not_reserved(&peer_id); self.data.out_slots.mark_not_reserved(&peer_id); self.data.discovered.mark_not_reserved(&peer_id); if self.data.reserved_only { if self.data.in_slots.clear_slot(&peer_id) || self.data.out_slots.clear_slot(&peer_id) { // insert peer back into discovered list self.data.discovered.add_peer(peer_id.clone(), SlotType::Common); self.message_queue.push_back(Message::Drop(peer_id)); // call alloc_slots again, cause we may have some reserved peers in discovered list // waiting for the slot that was just cleared self.alloc_slots(); } } } fn on_set_reserved_only(&mut self, reserved_only: bool) { // Disconnect non-reserved nodes. self.data.reserved_only = reserved_only; if self.data.reserved_only { for peer_id in self.data.in_slots.clear_common_slots().into_iter().chain(self.data.out_slots.clear_common_slots().into_iter()) { // insert peer back into discovered list self.data.discovered.add_peer(peer_id.clone(), SlotType::Common); self.message_queue.push_back(Message::Drop(peer_id)); } } else { self.alloc_slots(); } } fn on_report_peer(&mut self, peer_id: PeerId, score_diff: i32) { let score = match self.data.scores.get_mut(&peer_id) { Some(score) => { *score = score.saturating_add(score_diff); *score }, None => { self.data.scores.insert(peer_id.clone(), score_diff); score_diff } }; if score < 0 { // peer will be removed from `in_slots` or `out_slots` in `on_dropped` method if self.data.in_slots.contains(&peer_id) || self.data.out_slots.contains(&peer_id) { self.data.in_slots.clear_slot(&peer_id); self.data.out_slots.clear_slot(&peer_id); self.message_queue.push_back(Message::Drop(peer_id)); } } } fn alloc_slots(&mut self) { while let Some((peer_id, slot_type)) = self.data.discovered.pop_peer(self.data.reserved_only) { match self.data.out_slots.add_peer(peer_id, slot_type) { SlotState::Added(peer_id) => { trace!(target: "peerset", "Connecting to new peer {}", peer_id); self.message_queue.push_back(Message::Connect(peer_id)); }, SlotState::Swaped { removed, added } => { // insert peer back into discovered list trace!(target: "peerset", "Connecting to new peer {}, dropping {}", added, removed); self.data.discovered.add_peer(removed.clone(), SlotType::Common); self.message_queue.push_back(Message::Drop(removed)); self.message_queue.push_back(Message::Connect(added)); } SlotState::Upgraded(_) | SlotState::AlreadyConnected(_) => { // TODO: we should never reach this point }, SlotState::MaxConnections(peer_id) => { self.data.discovered.add_peer(peer_id, slot_type); break; }, } } } /// Indicate that we received an incoming connection. Must be answered either with /// a corresponding `Accept` or `Reject`, except if we were already connected to this peer. /// /// Note that this mechanism is orthogonal to `Connect`/`Drop`. Accepting an incoming /// connection implicitely means `Accept`, but incoming connections aren't cancelled by /// `dropped`. /// /// Because of concurrency issues, it is acceptable to call `incoming` with a `PeerId` the /// peerset is already connected to, in which case it must not answer. pub fn incoming(&mut self, peer_id: PeerId, index: IncomingIndex) { trace!("Incoming {}\nin_slots={:?}\nout_slots={:?}", peer_id, self.data.in_slots, self.data.out_slots); // if `reserved_only` is set, but this peer is not a part of our discovered list, // a) it is not reserved, so we reject the connection // b) we are already connected to it, so we reject the connection if self.data.reserved_only && !self.data.discovered.is_reserved(&peer_id) { self.message_queue.push_back(Message::Reject(index)); return; } // check if we are already connected to this peer if self.data.out_slots.contains(&peer_id) { // we are already connected. in this case we do not answer return; } let slot_type = if self.data.reserved_only { SlotType::Reserved } else { SlotType::Common }; match self.data.in_slots.add_peer(peer_id, slot_type) { SlotState::Added(peer_id) => { // reserved node may have been previously stored as normal node in discovered list self.data.discovered.remove_peer(&peer_id); self.message_queue.push_back(Message::Accept(index)); return; }, SlotState::Swaped { removed, added } => { // reserved node may have been previously stored as normal node in discovered list self.data.discovered.remove_peer(&added); // swap connections. self.message_queue.push_back(Message::Drop(removed)); self.message_queue.push_back(Message::Accept(index)); }, SlotState::AlreadyConnected(_) | SlotState::Upgraded(_) => { // we are already connected. in this case we do not answer return; }, SlotState::MaxConnections(peer_id) => { self.data.discovered.add_peer(peer_id, slot_type); self.message_queue.push_back(Message::Reject(index)); return; }, } } /// Indicate that we dropped an active connection with a peer, or that we failed to connect. /// /// Must only be called after the PSM has either generated a `Connect` message with this /// `PeerId`, or accepted an incoming connection with this `PeerId`. pub fn dropped(&mut self, peer_id: PeerId) { trace!("Dropping {}\nin_slots={:?}\nout_slots={:?}", peer_id, self.data.in_slots, self.data.out_slots); // Automatically connect back if reserved. if self.data.in_slots.is_connected_and_reserved(&peer_id) || self.data.out_slots.is_connected_and_reserved(&peer_id) { self.message_queue.push_back(Message::Connect(peer_id)); return; } // Otherwise, free the slot. self.data.in_slots.clear_slot(&peer_id); self.data.out_slots.clear_slot(&peer_id); // Note: in this dummy implementation we consider that peers never expire. As soon as we // are disconnected from a peer, we try again. self.data.discovered.add_peer(peer_id, SlotType::Common); self.alloc_slots(); } /// Adds a discovered peer id to the PSM. /// /// > **Note**: There is no equivalent "expired" message, meaning that it is the responsibility /// > of the PSM to remove `PeerId`s that fail to dial too often. pub fn discovered(&mut self, peer_id: PeerId) { if self.data.in_slots.contains(&peer_id) || self.data.out_slots.contains(&peer_id) { return; } self.data.discovered.add_peer(peer_id, SlotType::Common); self.alloc_slots(); } /// Produces a JSON object containing the state of the peerset manager, for debugging purposes. pub fn debug_info(&self) -> serde_json::Value { serde_json::Value::Null } } impl Stream for Peerset { type Item = Message; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { loop { if let Some(message) = self.message_queue.pop_front() { return Ok(Async::Ready(Some(message))); } match try_ready!(self.rx.poll()) { None => return Ok(Async::Ready(None)), Some(action) => match action { Action::AddReservedPeer(peer_id) => self.on_add_reserved_peer(peer_id), Action::RemoveReservedPeer(peer_id) => self.on_remove_reserved_peer(peer_id), Action::SetReservedOnly(reserved) => self.on_set_reserved_only(reserved), Action::ReportPeer(peer_id, score_diff) => self.on_report_peer(peer_id, score_diff), } } } } } #[cfg(test)] mod tests { use libp2p::PeerId; use futures::prelude::*; use super::{PeersetConfig, Peerset, Message, IncomingIndex}; fn assert_messages(mut peerset: Peerset, messages: Vec<Message>) -> Peerset { for expected_message in messages { let (message, p) = next_message(peerset).expect("expected message"); assert_eq!(message, expected_message); peerset = p; } assert!(peerset.message_queue.is_empty()); peerset } fn next_message(peerset: Peerset) -> Result<(Message, Peerset), ()> { let (next, peerset) = peerset.into_future() .wait() .map_err(|_| ())?; let message = next.ok_or_else(|| ())?; Ok((message, peerset)) } #[test] fn test_peerset_from_config_with_bootnodes() { let bootnode = PeerId::random(); let bootnode2 = PeerId::random(); let config = PeersetConfig { in_peers: 0, out_peers: 2, bootnodes: vec![bootnode.clone(), bootnode2.clone()], reserved_only: false, reserved_nodes: Vec::new(), }; let (peerset, _handle) = Peerset::from_config(config); assert_messages(peerset, vec![ Message::Connect(bootnode), Message::Connect(bootnode2), ]); } #[test] fn test_peerset_from_config_with_reserved_nodes() { let bootnode = PeerId::random(); let bootnode2 = PeerId::random(); let reserved_peer = PeerId::random(); let reserved_peer2 = PeerId::random(); let config = PeersetConfig { in_peers: 0, out_peers: 3, bootnodes: vec![bootnode.clone(), bootnode2.clone()], reserved_only: false, reserved_nodes: vec![reserved_peer.clone(), reserved_peer2.clone()], }; let (peerset, _handle) = Peerset::from_config(config); assert_messages(peerset, vec![ Message::Connect(reserved_peer), Message::Connect(reserved_peer2), Message::Connect(bootnode) ]); } #[test] fn test_peerset_add_reserved_peer() { let bootnode = PeerId::random(); let reserved_peer = PeerId::random(); let reserved_peer2 = PeerId::random(); let config = PeersetConfig { in_peers: 0, out_peers: 2, bootnodes: vec![bootnode], reserved_only: true, reserved_nodes: Vec::new(), }; let (peerset, handle) = Peerset::from_config(config); handle.add_reserved_peer(reserved_peer.clone()); handle.add_reserved_peer(reserved_peer2.clone()); assert_messages(peerset, vec![ Message::Connect(reserved_peer), Message::Connect(reserved_peer2) ]); } #[test] fn test_peerset_remove_reserved_peer() { let reserved_peer = PeerId::random(); let reserved_peer2 = PeerId::random(); let config = PeersetConfig { in_peers: 0, out_peers: 2, bootnodes: vec![], reserved_only: false, reserved_nodes: vec![reserved_peer.clone(), reserved_peer2.clone()], }; let (peerset, handle) = Peerset::from_config(config); handle.remove_reserved_peer(reserved_peer.clone()); let peerset = assert_messages(peerset, vec![ Message::Connect(reserved_peer.clone()), Message::Connect(reserved_peer2.clone()), ]); handle.set_reserved_only(true); handle.remove_reserved_peer(reserved_peer2.clone()); assert_messages(peerset, vec![ Message::Drop(reserved_peer), Message::Drop(reserved_peer2), ]); } #[test] fn test_peerset_set_reserved_only() { let bootnode = PeerId::random(); let bootnode2 = PeerId::random(); let reserved_peer = PeerId::random(); let reserved_peer2 = PeerId::random(); let config = PeersetConfig { in_peers: 0, out_peers: 4, bootnodes: vec![bootnode.clone(), bootnode2.clone()], reserved_only: false, reserved_nodes: vec![reserved_peer.clone(), reserved_peer2.clone()], }; let (peerset, handle) = Peerset::from_config(config); handle.set_reserved_only(true); handle.set_reserved_only(false); assert_messages(peerset, vec![ Message::Connect(reserved_peer), Message::Connect(reserved_peer2), Message::Connect(bootnode.clone()), Message::Connect(bootnode2.clone()), Message::Drop(bootnode.clone()), Message::Drop(bootnode2.clone()), Message::Connect(bootnode), Message::Connect(bootnode2), ]); } #[test] fn test_peerset_report_peer() { let bootnode = PeerId::random(); let bootnode2 = PeerId::random(); let config = PeersetConfig { in_peers: 0, out_peers: 1, bootnodes: vec![bootnode.clone(), bootnode2.clone()], reserved_only: false, reserved_nodes: Vec::new(), }; let (peerset, handle) = Peerset::from_config(config); handle.report_peer(bootnode2, -1); handle.report_peer(bootnode.clone(), -1); assert_messages(peerset, vec![ Message::Connect(bootnode.clone()), Message::Drop(bootnode) ]); } #[test] fn test_peerset_incoming() { let bootnode = PeerId::random(); let incoming = PeerId::random(); let incoming2 = PeerId::random(); let incoming3 = PeerId::random(); let ii = IncomingIndex(1); let ii2 = IncomingIndex(2); let ii3 = IncomingIndex(3); let ii4 = IncomingIndex(3); let config = PeersetConfig { in_peers: 2, out_peers: 1, bootnodes: vec![bootnode.clone()], reserved_only: false, reserved_nodes: Vec::new(), }; let (mut peerset, _handle) = Peerset::from_config(config); peerset.incoming(incoming.clone(), ii); peerset.incoming(incoming.clone(), ii4); peerset.incoming(incoming2.clone(), ii2); peerset.incoming(incoming3.clone(), ii3); assert_messages(peerset, vec![ Message::Connect(bootnode.clone()), Message::Accept(ii), Message::Accept(ii2), Message::Reject(ii3), ]); } #[test] fn test_peerset_dropped() { let bootnode = PeerId::random(); let bootnode2 = PeerId::random(); let reserved_peer = PeerId::random(); let config = PeersetConfig { in_peers: 0, out_peers: 2, bootnodes: vec![bootnode.clone(), bootnode2.clone()], reserved_only: false, reserved_nodes: vec![reserved_peer.clone()], }; let (peerset, _handle) = Peerset::from_config(config); let mut peerset = assert_messages(peerset, vec![ Message::Connect(reserved_peer.clone()), Message::Connect(bootnode.clone()), ]); peerset.dropped(reserved_peer.clone()); peerset.dropped(bootnode); let _peerset = assert_messages(peerset, vec![ Message::Connect(reserved_peer), Message::Connect(bootnode2), ]); } #[test] fn test_peerset_discovered() { let bootnode = PeerId::random(); let discovered = PeerId::random(); let discovered2 = PeerId::random(); let config = PeersetConfig { in_peers: 0, out_peers: 2, bootnodes: vec![bootnode.clone()], reserved_only: false, reserved_nodes: vec![], }; let (mut peerset, _handle) = Peerset::from_config(config); peerset.discovered(discovered.clone()); peerset.discovered(discovered.clone()); peerset.discovered(discovered2); assert_messages(peerset, vec![ Message::Connect(bootnode), Message::Connect(discovered), ]); } }
31.299458
131
0.701069
691f6e4ec56cfb88778c0846eb5f399f27e0526b
27,238
//! Logical device //! //! # Device //! //! This module exposes the `Device` trait, which provides methods for creating //! and managing graphics resources such as buffers, images and memory. //! //! The `Adapter` and `Device` types are very similar to the Vulkan concept of //! "physical devices" vs. "logical devices"; an `Adapter` is single GPU //! (or CPU) that implements a backend, a `Device` is a //! handle to that physical device that has the requested capabilities //! and is used to actually do things. use std::any::Any; use std::borrow::Borrow; use std::ops::Range; use std::{iter, mem, slice}; use {buffer, format, image, mapping, pass, pso, query}; use {Backend, MemoryTypeId}; use error::HostExecutionError; use memory::Requirements; use pool::{CommandPool, CommandPoolCreateFlags}; use queue::{QueueFamilyId, QueueGroup}; use range::RangeArg; use window::{self, Backbuffer, SwapchainConfig}; /// Error occurred caused device to be lost. #[derive(Clone, Copy, Debug, Fail, PartialEq, Eq)] #[fail(display = "Device is lost")] pub struct DeviceLost; /// Error occurred caused surface to be lost. #[derive(Clone, Copy, Debug, Fail, PartialEq, Eq)] #[fail(display = "Surface is lost")] pub struct SurfaceLost; /// Native window is already in use by graphics API. #[derive(Clone, Copy, Debug, Fail, PartialEq, Eq)] #[fail(display = "Native window in use")] pub struct WindowInUse; /// Error allocating memory. #[derive(Clone, Copy, Debug, Fail, PartialEq, Eq)] pub enum OutOfMemory { /// Host memory exhausted. #[fail(display = "Out of host memory")] OutOfHostMemory, /// Device memory exhausted. #[fail(display = "Out of device memory")] OutOfDeviceMemory, } /// Error occurred caused device to be lost /// or out of memory error. #[derive(Clone, Copy, Debug, Fail, PartialEq, Eq)] pub enum OomOrDeviceLost { /// Out of either host or device memory. #[fail(display = "{}", _0)] OutOfMemory(OutOfMemory), /// Device is lost #[fail(display = "{}", _0)] DeviceLost(DeviceLost), } impl From<OutOfMemory> for OomOrDeviceLost { fn from(error: OutOfMemory) -> Self { OomOrDeviceLost::OutOfMemory(error) } } impl From<DeviceLost> for OomOrDeviceLost { fn from(error: DeviceLost) -> Self { OomOrDeviceLost::DeviceLost(error) } } /// Possible cause of allocation failure. #[derive(Clone, Copy, Debug, Fail, PartialEq, Eq)] pub enum AllocationError { /// Out of either host or device memory. #[fail(display = "{}", _0)] OutOfMemory(OutOfMemory), /// Vulkan implementation doesn't allow to create too many objects. #[fail(display = "Can't allocate more memory objects")] TooManyObjects, } impl From<OutOfMemory> for AllocationError { fn from(error: OutOfMemory) -> Self { AllocationError::OutOfMemory(error) } } /// Error binding a resource to memory allocation. #[derive(Clone, Copy, Debug, Fail, PartialEq, Eq)] pub enum BindError { /// Out of either host or device memory. #[fail(display = "{}", _0)] OutOfMemory(OutOfMemory), /// Requested binding to memory that doesn't support the required operations. #[fail(display = "Unsupported memory allocation for the requirements")] WrongMemory, /// Requested binding to an invalid memory. #[fail(display = "Not enough space in the memory allocation")] OutOfBounds, } impl From<OutOfMemory> for BindError { fn from(error: OutOfMemory) -> Self { BindError::OutOfMemory(error) } } /// Specifies the waiting targets. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WaitFor { /// Wait for any target. Any, /// Wait for all targets at once. All, } /// An error from creating a shader module. #[derive(Clone, Debug, Fail, PartialEq, Eq)] pub enum ShaderError { /// The shader failed to compile. #[fail(display = "shader compilation failed: {}", _0)] CompilationFailed(String), /// Missing entry point. #[fail(display = "shader is missing an entry point: {}", _0)] MissingEntryPoint(String), /// Mismatch of interface (e.g missing push constants). #[fail(display = "shader interface mismatch: {}", _0)] InterfaceMismatch(String), /// Shader stage is not supported. #[fail(display = "shader stage \"{}\" is unsupported", _0)] UnsupportedStage(pso::Stage), /// Out of either host or device memory. #[fail(display = "{}", _0)] OutOfMemory(OutOfMemory), } impl From<OutOfMemory> for ShaderError { fn from(error: OutOfMemory) -> Self { ShaderError::OutOfMemory(error) } } /// # Overview /// /// A `Device` is responsible for creating and managing resources for the physical device /// it was created from. /// /// ## Resource Construction and Handling /// /// This device structure can then be used to create and manage different resources, like buffers, /// shader programs and textures. See the individual methods for more information. /// /// ## Mutability /// /// All the methods get `&self`. Any internal mutability of the `Device` is hidden from the user. /// /// ## Synchronization /// /// `Device` should be usable concurrently from multiple threads. The `Send` and `Sync` bounds /// are not enforced at the HAL level due to OpenGL constraint (to be revised). Users can still /// benefit from the backends that support synchronization of the `Device`. /// pub trait Device<B: Backend>: Any + Send + Sync { /// Allocates a memory segment of a specified type. /// /// There is only a limited amount of allocations allowed depending on the implementation! /// /// # Arguments /// /// * `memory_type` - Index of the memory type in the memory properties of the associated physical device. /// * `size` - Size of the allocation. unsafe fn allocate_memory( &self, memory_type: MemoryTypeId, size: u64, ) -> Result<B::Memory, AllocationError>; /// Free device memory unsafe fn free_memory(&self, memory: B::Memory); /// Create a new command pool for a given queue family. /// /// *Note*: the family has to be associated by one as the `Gpu::queue_groups`. unsafe fn create_command_pool( &self, family: QueueFamilyId, create_flags: CommandPoolCreateFlags, ) -> Result<B::CommandPool, OutOfMemory>; /// Create a strongly typed command pool wrapper. unsafe fn create_command_pool_typed<C>( &self, group: &QueueGroup<B, C>, flags: CommandPoolCreateFlags, ) -> Result<CommandPool<B, C>, OutOfMemory> { let raw = self.create_command_pool(group.family(), flags)?; Ok(CommandPool::new(raw)) } /// Destroy a command pool. unsafe fn destroy_command_pool(&self, pool: B::CommandPool); /// Create a render pass with the given attachments and subpasses. /// /// A *render pass* represents a collection of attachments, subpasses, and dependencies between /// the subpasses, and describes how the attachments are used over the course of the subpasses. /// The use of a render pass in a command buffer is a *render pass* instance. unsafe fn create_render_pass<'a, IA, IS, ID>( &self, attachments: IA, subpasses: IS, dependencies: ID, ) -> Result<B::RenderPass, OutOfMemory> where IA: IntoIterator, IA::Item: Borrow<pass::Attachment>, IS: IntoIterator, IS::Item: Borrow<pass::SubpassDesc<'a>>, ID: IntoIterator, ID::Item: Borrow<pass::SubpassDependency>; /// Destroy a `RenderPass`. unsafe fn destroy_render_pass(&self, rp: B::RenderPass); /// Create a new pipeline layout object. /// /// # Arguments /// /// * `set_layouts` - Descriptor set layouts /// * `push_constants` - Ranges of push constants. A shader stage may only contain one push /// constant block. The length of the range indicates the number of u32 constants occupied /// by the push constant block. /// /// # PipelineLayout /// /// Access to descriptor sets from a pipeline is accomplished through a *pipeline layout*. /// Zero or more descriptor set layouts and zero or more push constant ranges are combined to /// form a pipeline layout object which describes the complete set of resources that **can** be /// accessed by a pipeline. The pipeline layout represents a sequence of descriptor sets with /// each having a specific layout. This sequence of layouts is used to determine the interface /// between shader stages and shader resources. Each pipeline is created using a pipeline layout. unsafe fn create_pipeline_layout<IS, IR>( &self, set_layouts: IS, push_constant: IR, ) -> Result<B::PipelineLayout, OutOfMemory> where IS: IntoIterator, IS::Item: Borrow<B::DescriptorSetLayout>, IR: IntoIterator, IR::Item: Borrow<(pso::ShaderStageFlags, Range<u32>)>; /// Destroy a pipeline layout object unsafe fn destroy_pipeline_layout(&self, layout: B::PipelineLayout); /// Create a pipeline cache object. //TODO: allow loading from disk fn create_pipeline_cache(&self) -> Result<B::PipelineCache, OutOfMemory>; /// Merge a number of source pipeline caches into the target one. unsafe fn merge_pipeline_caches<I>(&self, target: &B::PipelineCache, sources: I) -> Result<(), OutOfMemory> where I: IntoIterator, I::Item: Borrow<B::PipelineCache>; /// Destroy a pipeline cache object. unsafe fn destroy_pipeline_cache(&self, cache: B::PipelineCache); /// Create a graphics pipeline. unsafe fn create_graphics_pipeline<'a>( &self, desc: &pso::GraphicsPipelineDesc<'a, B>, cache: Option<&B::PipelineCache>, ) -> Result<B::GraphicsPipeline, pso::CreationError> { self.create_graphics_pipelines(iter::once(desc), cache) .remove(0) } /// Create graphics pipelines. unsafe fn create_graphics_pipelines<'a, I>( &self, descs: I, cache: Option<&B::PipelineCache>, ) -> Vec<Result<B::GraphicsPipeline, pso::CreationError>> where I: IntoIterator, I::Item: Borrow<pso::GraphicsPipelineDesc<'a, B>>, { descs .into_iter() .map(|desc| self.create_graphics_pipeline(desc.borrow(), cache)) .collect() } /// Destroy a graphics pipeline. /// /// The graphics pipeline shouldn't be destroyed before any submitted command buffer, /// which references the graphics pipeline, has finished execution. unsafe fn destroy_graphics_pipeline(&self, pipeline: B::GraphicsPipeline); /// Create a compute pipeline. unsafe fn create_compute_pipeline<'a>( &self, desc: &pso::ComputePipelineDesc<'a, B>, cache: Option<&B::PipelineCache>, ) -> Result<B::ComputePipeline, pso::CreationError> { self.create_compute_pipelines(iter::once(desc), cache) .remove(0) } /// Create compute pipelines. unsafe fn create_compute_pipelines<'a, I>( &self, descs: I, cache: Option<&B::PipelineCache>, ) -> Vec<Result<B::ComputePipeline, pso::CreationError>> where I: IntoIterator, I::Item: Borrow<pso::ComputePipelineDesc<'a, B>>, { descs .into_iter() .map(|desc| self.create_compute_pipeline(desc.borrow(), cache)) .collect() } /// Destroy a compute pipeline. /// /// The compute pipeline shouldn't be destroyed before any submitted command buffer, /// which references the compute pipeline, has finished execution. unsafe fn destroy_compute_pipeline(&self, pipeline: B::ComputePipeline); /// Create a new framebuffer object unsafe fn create_framebuffer<I>( &self, pass: &B::RenderPass, attachments: I, extent: image::Extent, ) -> Result<B::Framebuffer, OutOfMemory> where I: IntoIterator, I::Item: Borrow<B::ImageView>; /// Destroy a framebuffer. /// /// The framebuffer shouldn't be destroy before any submitted command buffer, /// which references the framebuffer, has finished execution. unsafe fn destroy_framebuffer(&self, buf: B::Framebuffer); /// Create a new shader module object through the SPIR-V binary data. /// /// Once a shader module has been created, any entry points it contains can be used in pipeline /// shader stages as described in *Compute Pipelines* and *Graphics Pipelines*. unsafe fn create_shader_module(&self, spirv_data: &[u8]) -> Result<B::ShaderModule, ShaderError>; /// Destroy a shader module module /// /// A shader module can be destroyed while pipelines created using its shaders are still in use. unsafe fn destroy_shader_module(&self, shader: B::ShaderModule); /// Create a new buffer (unbound). /// /// The created buffer won't have associated memory until `bind_buffer_memory` is called. unsafe fn create_buffer( &self, size: u64, usage: buffer::Usage, ) -> Result<B::Buffer, buffer::CreationError>; /// Get memory requirements for the buffer unsafe fn get_buffer_requirements(&self, buf: &B::Buffer) -> Requirements; /// Bind memory to a buffer. /// /// Be sure to check that there is enough memory available for the buffer. /// Use `get_buffer_requirements` to acquire the memory requirements. unsafe fn bind_buffer_memory( &self, memory: &B::Memory, offset: u64, buf: &mut B::Buffer, ) -> Result<(), BindError>; /// Destroy a buffer. /// /// The buffer shouldn't be destroyed before any submitted command buffer, /// which references the images, has finished execution. unsafe fn destroy_buffer(&self, buffer: B::Buffer); /// Create a new buffer view object unsafe fn create_buffer_view<R: RangeArg<u64>>( &self, buf: &B::Buffer, fmt: Option<format::Format>, range: R, ) -> Result<B::BufferView, buffer::ViewCreationError>; /// Destroy a buffer view object unsafe fn destroy_buffer_view(&self, view: B::BufferView); /// Create a new image object unsafe fn create_image( &self, kind: image::Kind, mip_levels: image::Level, format: format::Format, tiling: image::Tiling, usage: image::Usage, view_caps: image::ViewCapabilities, ) -> Result<B::Image, image::CreationError>; /// Get memory requirements for the Image unsafe fn get_image_requirements(&self, image: &B::Image) -> Requirements; /// unsafe fn get_image_subresource_footprint( &self, image: &B::Image, subresource: image::Subresource, ) -> image::SubresourceFootprint; /// Bind device memory to an image object unsafe fn bind_image_memory( &self, memory: &B::Memory, offset: u64, image: &mut B::Image, ) -> Result<(), BindError>; /// Destroy an image. /// /// The image shouldn't be destroyed before any submitted command buffer, /// which references the images, has finished execution. unsafe fn destroy_image(&self, image: B::Image); /// Create an image view from an existing image unsafe fn create_image_view( &self, image: &B::Image, view_kind: image::ViewKind, format: format::Format, swizzle: format::Swizzle, range: image::SubresourceRange, ) -> Result<B::ImageView, image::ViewError>; /// Destroy an image view object unsafe fn destroy_image_view(&self, view: B::ImageView); /// Create a new sampler object unsafe fn create_sampler(&self, info: image::SamplerInfo) -> Result<B::Sampler, AllocationError>; /// Destroy a sampler object unsafe fn destroy_sampler(&self, sampler: B::Sampler); /// Create a descriptor pool. /// /// Descriptor pools allow allocation of descriptor sets. /// The pool can't be modified directly, only through updating descriptor sets. unsafe fn create_descriptor_pool<I>(&self, max_sets: usize, descriptor_ranges: I) -> Result<B::DescriptorPool, OutOfMemory> where I: IntoIterator, I::Item: Borrow<pso::DescriptorRangeDesc>; /// Destroy a descriptor pool object /// /// When a pool is destroyed, all descriptor sets allocated from the pool are implicitly freed /// and become invalid. Descriptor sets allocated from a given pool do not need to be freed /// before destroying that descriptor pool. unsafe fn destroy_descriptor_pool(&self, pool: B::DescriptorPool); /// Create a descriptor set layout. /// /// A descriptor set layout object is defined by an array of zero or more descriptor bindings. /// Each individual descriptor binding is specified by a descriptor type, a count (array size) /// of the number of descriptors in the binding, a set of shader stages that **can** access the /// binding, and (if using immutable samplers) an array of sampler descriptors. unsafe fn create_descriptor_set_layout<I, J>( &self, bindings: I, immutable_samplers: J, ) -> Result<B::DescriptorSetLayout, OutOfMemory> where I: IntoIterator, I::Item: Borrow<pso::DescriptorSetLayoutBinding>, J: IntoIterator, J::Item: Borrow<B::Sampler>; /// Destroy a descriptor set layout object unsafe fn destroy_descriptor_set_layout(&self, layout: B::DescriptorSetLayout); /// Specifying the parameters of a descriptor set write operation unsafe fn write_descriptor_sets<'a, I, J>(&self, write_iter: I) where I: IntoIterator<Item = pso::DescriptorSetWrite<'a, B, J>>, J: IntoIterator, J::Item: Borrow<pso::Descriptor<'a, B>>; /// Structure specifying a copy descriptor set operation unsafe fn copy_descriptor_sets<'a, I>(&self, copy_iter: I) where I: IntoIterator, I::Item: Borrow<pso::DescriptorSetCopy<'a, B>>; /// Map a memory object into application address space /// /// Call `map_memory()` to retrieve a host virtual address pointer to a region of a mappable memory object unsafe fn map_memory<R>(&self, memory: &B::Memory, range: R) -> Result<*mut u8, mapping::Error> where R: RangeArg<u64>; /// Flush mapped memory ranges unsafe fn flush_mapped_memory_ranges<'a, I, R>(&self, ranges: I) -> Result<(), OutOfMemory> where I: IntoIterator, I::Item: Borrow<(&'a B::Memory, R)>, R: RangeArg<u64>; /// Invalidate ranges of non-coherent memory from the host caches unsafe fn invalidate_mapped_memory_ranges<'a, I, R>(&self, ranges: I) -> Result<(), OutOfMemory> where I: IntoIterator, I::Item: Borrow<(&'a B::Memory, R)>, R: RangeArg<u64>; /// Unmap a memory object once host access to it is no longer needed by the application unsafe fn unmap_memory(&self, memory: &B::Memory); /// Acquire a mapping Reader. /// /// The accessible slice will correspond to the specified range (in bytes). unsafe fn acquire_mapping_reader<'a, T>( &self, memory: &'a B::Memory, range: Range<u64>, ) -> Result<mapping::Reader<'a, B, T>, mapping::Error> where T: Copy, { let len = range.end - range.start; let count = len as usize / mem::size_of::<T>(); self.map_memory(memory, range.clone()).and_then(|ptr| { let start_ptr = ptr as *const _; self.invalidate_mapped_memory_ranges(iter::once((memory, range.clone())))?; Ok(mapping::Reader { slice: slice::from_raw_parts(start_ptr, count), memory, released: false, }) }) } /// Release a mapping Reader. unsafe fn release_mapping_reader<'a, T>(&self, mut reader: mapping::Reader<'a, B, T>) { reader.released = true; self.unmap_memory(reader.memory); } /// Acquire a mapping Writer. /// /// The accessible slice will correspond to the specified range (in bytes). unsafe fn acquire_mapping_writer<'a, T>( &self, memory: &'a B::Memory, range: Range<u64>, ) -> Result<mapping::Writer<'a, B, T>, mapping::Error> where T: Copy, { let count = (range.end - range.start) as usize / mem::size_of::<T>(); self.map_memory(memory, range.clone()).map(|ptr| { let start_ptr = ptr as *mut _; mapping::Writer { slice: slice::from_raw_parts_mut(start_ptr, count), memory, range, released: false, } }) } /// Release a mapping Writer. unsafe fn release_mapping_writer<'a, T>(&self, mut writer: mapping::Writer<'a, B, T>) -> Result<(), OutOfMemory> { writer.released = true; self.flush_mapped_memory_ranges(iter::once((writer.memory, writer.range.clone())))?; self.unmap_memory(writer.memory); Ok(()) } /// Create a new semaphore object fn create_semaphore(&self) -> Result<B::Semaphore, OutOfMemory>; /// Destroy a semaphore object unsafe fn destroy_semaphore(&self, semaphore: B::Semaphore); /// Create a new fence object /// /// Fences are a synchronization primitive that **can** be used to insert a dependency from /// a queue to the host. Fences have two states - signaled and unsignaled. A fence **can** be /// signaled as part of the execution of a *queue submission* command. Fences **can** be unsignaled /// on the host with *reset_fences*. Fences **can** be waited on by the host with the /// *wait_for_fences* command, and the current state **can** be queried with *get_fence_status*. fn create_fence(&self, signaled: bool) -> Result<B::Fence, OutOfMemory>; /// unsafe fn reset_fence(&self, fence: &B::Fence) -> Result<(), OutOfMemory> { self.reset_fences(iter::once(fence)) } /// unsafe fn reset_fences<I>(&self, fences: I) -> Result<(), OutOfMemory> where I: IntoIterator, I::Item: Borrow<B::Fence>, { for fence in fences { self.reset_fence(fence.borrow())?; } Ok(()) } /// Blocks until the given fence is signaled. /// Returns true if the fence was signaled before the timeout. unsafe fn wait_for_fence(&self, fence: &B::Fence, timeout_ns: u64) -> Result<bool, OomOrDeviceLost> { self.wait_for_fences(iter::once(fence), WaitFor::All, timeout_ns) } /// Blocks until all or one of the given fences are signaled. /// Returns true if fences were signaled before the timeout. unsafe fn wait_for_fences<I>(&self, fences: I, wait: WaitFor, timeout_ns: u64) -> Result<bool, OomOrDeviceLost> where I: IntoIterator, I::Item: Borrow<B::Fence>, { use std::{thread, time}; fn to_ns(duration: time::Duration) -> u64 { duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64 } let start = time::Instant::now(); match wait { WaitFor::All => { for fence in fences { if !self.wait_for_fence(fence.borrow(), 0)? { let elapsed_ns = to_ns(start.elapsed()); if elapsed_ns > timeout_ns { return Ok(false); } if !self.wait_for_fence(fence.borrow(), timeout_ns - elapsed_ns)? { return Ok(false); } } } Ok(true) } WaitFor::Any => { let fences: Vec<_> = fences.into_iter().collect(); loop { for fence in &fences { if self.wait_for_fence(fence.borrow(), 0)? { return Ok(true); } } if to_ns(start.elapsed()) >= timeout_ns { return Ok(false); } thread::sleep(time::Duration::from_millis(1)); } } } } /// true for signaled, false for not ready unsafe fn get_fence_status(&self, fence: &B::Fence) -> Result<bool, DeviceLost>; /// Destroy a fence object unsafe fn destroy_fence(&self, fence: B::Fence); /// Create a new query pool object /// /// Queries are managed using query pool objects. Each query pool is a collection of a specific /// number of queries of a particular type. unsafe fn create_query_pool( &self, ty: query::Type, count: query::Id, ) -> Result<B::QueryPool, query::CreationError>; /// Destroy a query pool object unsafe fn destroy_query_pool(&self, pool: B::QueryPool); /// Get query pool results into the specified CPU memory. /// Returns `Ok(false)` if the results are not ready yet and neither of `WAIT` or `PARTIAL` flags are set. unsafe fn get_query_pool_results( &self, pool: &B::QueryPool, queries: Range<query::Id>, data: &mut [u8], stride: buffer::Offset, flags: query::ResultFlags, ) -> Result<bool, OomOrDeviceLost>; /// Create a new swapchain from a surface and a queue family, optionally providing the old /// swapchain to aid in resource reuse and rendering continuity. /// /// *Note*: The number of exposed images in the back buffer might differ /// from number of internally used buffers. /// /// # Safety /// /// The queue family _must_ support surface presentation. /// This can be checked by calling [`supports_queue_family`](trait.Surface.html#tymethod.supports_queue_family) /// on this surface. /// /// # Examples /// /// ```no_run /// # extern crate gfx_backend_empty as empty; /// # extern crate gfx_hal; /// # fn main() { /// use gfx_hal::{Device, SwapchainConfig}; /// use gfx_hal::format::Format; /// # use gfx_hal::{CommandQueue, Graphics}; /// /// # let mut surface: empty::Surface = return; /// # let device: empty::Device = return; /// # unsafe { /// let swapchain_config = SwapchainConfig::new(100, 100, Format::Rgba8Srgb, 2); /// device.create_swapchain(&mut surface, swapchain_config, None); /// # }} /// ``` unsafe fn create_swapchain( &self, surface: &mut B::Surface, config: SwapchainConfig, old_swapchain: Option<B::Swapchain>, ) -> Result<(B::Swapchain, Backbuffer<B>), window::CreationError>; /// unsafe fn destroy_swapchain(&self, swapchain: B::Swapchain); /// Wait for all queues associated with this device to idle. /// /// Host access to all queues needs to be **externally** sycnhronized! fn wait_idle(&self) -> Result<(), HostExecutionError>; }
35.934037
127
0.630076
f7f34beccb40c907d2615d1e10cee79917e68fa2
26,025
extern crate vulkan_tutorial_rust; use vulkan_tutorial_rust::{ utility, // the mod define some fixed functions that have been learned before. utility::share, utility::debug::*, utility::structures::*, utility::constants::*, }; extern crate winit; extern crate ash; #[macro_use] extern crate memoffset; use winit::{ Event, EventsLoop, WindowEvent, ControlFlow, VirtualKeyCode }; use ash::vk; use ash::version::{ V1_0, InstanceV1_0 }; use ash::version::DeviceV1_0; type EntryV1 = ash::Entry<V1_0>; use std::path::Path; use std::ptr; use std::ffi::CString; // Constants const WINDOW_TITLE: &'static str = "17.Vertex Input"; struct Vertex { pos: [f32; 2], color: [f32; 4], } impl Vertex { fn get_binding_descriptions() -> [vk::VertexInputBindingDescription; 1] { [ vk::VertexInputBindingDescription { binding : 0, stride : std::mem::size_of::<Self>() as u32, input_rate : vk::VertexInputRate::Vertex, }, ] } fn get_attribute_descriptions() -> [vk::VertexInputAttributeDescription; 2] { [ vk::VertexInputAttributeDescription { location : 0, binding : 0, format : vk::Format::R32g32Sfloat, offset : offset_of!(Self, pos) as u32, }, vk::VertexInputAttributeDescription { binding : 0, location : 1, format : vk::Format::R32g32b32a32Sfloat, offset : offset_of!(Self, color) as u32, } ] } } const _VERTICES_DATA: [Vertex; 3] = [ Vertex { pos: [ 0.0, -0.5], color: [1.0, 0.0, 0.0, 0.0], }, Vertex { pos: [ 0.5, 0.5], color: [0.0, 1.0, 0.0, 0.0], }, Vertex { pos: [-0.5, -0.5], color: [0.0, 0.0, 1.0, 0.0], }, ]; struct VulkanApp { window : winit::Window, // vulkan stuff _entry : EntryV1, instance : ash::Instance<V1_0>, surface_loader : ash::extensions::Surface, surface : vk::SurfaceKHR, debug_report_loader : ash::extensions::DebugReport, debug_callback : vk::DebugReportCallbackEXT, physical_device : vk::PhysicalDevice, device : ash::Device<V1_0>, queue_family : QueueFamilyIndices, graphics_queue : vk::Queue, present_queue : vk::Queue, swapchain_loader : ash::extensions::Swapchain, swapchain : vk::SwapchainKHR, swapchain_images : Vec<vk::Image>, swapchain_format : vk::Format, swapchain_extent : vk::Extent2D, swapchain_imageviews : Vec<vk::ImageView>, swapchain_framebuffers : Vec<vk::Framebuffer>, render_pass : vk::RenderPass, pipeline_layout : vk::PipelineLayout, graphics_pipeline : vk::Pipeline, command_pool : vk::CommandPool, command_buffers : Vec<vk::CommandBuffer>, image_available_semaphores : Vec<vk::Semaphore>, render_finished_semaphores : Vec<vk::Semaphore>, in_flight_fences : Vec<vk::Fence>, current_frame : usize, is_framebuffer_resized : bool, } impl VulkanApp { pub fn new(event_loop: &winit::EventsLoop) -> VulkanApp { let window = utility::window::init_window(&event_loop, WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT); // init vulkan stuff let entry = EntryV1::new().unwrap(); let instance = share::create_instance(&entry, WINDOW_TITLE, VALIDATION.is_enable, &VALIDATION.required_validation_layers.to_vec()); let surface_stuff = share::create_surface(&entry, &instance, &window, WINDOW_WIDTH, WINDOW_HEIGHT); let (debug_report_loader, debug_callback) = setup_debug_callback( VALIDATION.is_enable, &entry, &instance); let physical_device = share::pick_physical_device(&instance, &surface_stuff, &DEVICE_EXTENSIONS); let (device, queue_family) = share::create_logical_device(&instance, physical_device, &VALIDATION, &DEVICE_EXTENSIONS, &surface_stuff); let graphics_queue = unsafe { device.get_device_queue(queue_family.graphics_family as u32, 0) }; let present_queue = unsafe { device.get_device_queue(queue_family.present_family as u32, 0) }; let swapchain_stuff = share::create_swapchain(&instance, &device, physical_device, &window, &surface_stuff, &queue_family); let swapchain_imageviews = share::v1::create_image_views(&device, swapchain_stuff.swapchain_format, &swapchain_stuff.swapchain_images); let render_pass = share::v1::create_render_pass(&device, swapchain_stuff.swapchain_format); let (graphics_pipeline, pipeline_layout) = VulkanApp::create_graphics_pipeline(&device, render_pass, swapchain_stuff.swapchain_extent); let swapchain_framebuffers = share::v1::create_framebuffers(&device, render_pass, &swapchain_imageviews, swapchain_stuff.swapchain_extent); let command_pool = share::v1::create_command_pool(&device, &queue_family); let command_buffers = share::v1::create_command_buffers(&device, command_pool, graphics_pipeline, &swapchain_framebuffers, render_pass, swapchain_stuff.swapchain_extent); let sync_ojbects = share::v1::create_sync_objects(&device, MAX_FRAMES_IN_FLIGHT); // cleanup(); the 'drop' function will take care of it. VulkanApp { // winit stuff window, // vulkan stuff _entry: entry, instance, surface: surface_stuff.surface, surface_loader: surface_stuff.surface_loader, debug_report_loader, debug_callback, physical_device, device, queue_family, graphics_queue, present_queue, swapchain_loader: swapchain_stuff.swapchain_loader, swapchain: swapchain_stuff.swapchain, swapchain_format: swapchain_stuff.swapchain_format, swapchain_images: swapchain_stuff.swapchain_images, swapchain_extent: swapchain_stuff.swapchain_extent, swapchain_imageviews, swapchain_framebuffers, pipeline_layout, render_pass, graphics_pipeline, command_pool, command_buffers, image_available_semaphores: sync_ojbects.image_available_semaphores, render_finished_semaphores: sync_ojbects.render_finished_semaphores, in_flight_fences : sync_ojbects.inflight_fences, current_frame: 0, is_framebuffer_resized: false, } } fn create_graphics_pipeline(device: &ash::Device<V1_0>, render_pass: vk::RenderPass, swapchain_extent: vk::Extent2D) -> (vk::Pipeline, vk::PipelineLayout) { let vert_shader_code = utility::tools::read_shader_code(Path::new("shaders/spv/17-shader-vertexbuffer.vert.spv")); let frag_shader_code = utility::tools::read_shader_code(Path::new("shaders/spv/17-shader-vertexbuffer.frag.spv")); let vert_shader_module = share::create_shader_module(device, vert_shader_code); let frag_shader_module = share::create_shader_module(device, frag_shader_code); let main_function_name = CString::new("main").unwrap(); // the beginning function name in shader code. let shader_stages = [ vk::PipelineShaderStageCreateInfo { // Vertex Shader s_type : vk::StructureType::PipelineShaderStageCreateInfo, p_next : ptr::null(), flags : vk::PipelineShaderStageCreateFlags::empty(), module : vert_shader_module, p_name : main_function_name.as_ptr(), p_specialization_info : ptr::null(), stage : vk::SHADER_STAGE_VERTEX_BIT, }, vk::PipelineShaderStageCreateInfo { // Fragment Shader s_type : vk::StructureType::PipelineShaderStageCreateInfo, p_next : ptr::null(), flags : vk::PipelineShaderStageCreateFlags::empty(), module : frag_shader_module, p_name : main_function_name.as_ptr(), p_specialization_info : ptr::null(), stage : vk::SHADER_STAGE_FRAGMENT_BIT, }, ]; let binding_description = Vertex::get_binding_descriptions(); let attribute_description = Vertex::get_attribute_descriptions(); let vertex_input_state_create_info = vk::PipelineVertexInputStateCreateInfo { s_type : vk::StructureType::PipelineVertexInputStateCreateInfo, p_next : ptr::null(), flags : vk::PipelineVertexInputStateCreateFlags::empty(), vertex_attribute_description_count : attribute_description.len() as u32, p_vertex_attribute_descriptions : attribute_description.as_ptr(), vertex_binding_description_count : binding_description.len() as u32, p_vertex_binding_descriptions : binding_description.as_ptr(), }; let vertex_input_assembly_state_info = vk::PipelineInputAssemblyStateCreateInfo { s_type : vk::StructureType::PipelineInputAssemblyStateCreateInfo, flags : vk::PipelineInputAssemblyStateCreateFlags::empty(), p_next : ptr::null(), primitive_restart_enable : vk::VK_FALSE, topology : vk::PrimitiveTopology::TriangleList, }; let viewports = [ vk::Viewport { x : 0.0, y : 0.0, width : swapchain_extent.width as f32, height : swapchain_extent.height as f32, min_depth : 0.0, max_depth : 1.0, }, ]; let scissors = [ vk::Rect2D { offset: vk::Offset2D { x: 0, y: 0 }, extent: swapchain_extent, }, ]; let viewport_state_create_info = vk::PipelineViewportStateCreateInfo { s_type : vk::StructureType::PipelineViewportStateCreateInfo, p_next : ptr::null(), flags : vk::PipelineViewportStateCreateFlags::empty(), scissor_count : scissors.len() as u32, p_scissors : scissors.as_ptr(), viewport_count : viewports.len() as u32, p_viewports : viewports.as_ptr(), }; let rasterization_statue_create_info = vk::PipelineRasterizationStateCreateInfo { s_type : vk::StructureType::PipelineRasterizationStateCreateInfo, p_next : ptr::null(), flags : vk::PipelineRasterizationStateCreateFlags::empty(), depth_clamp_enable : vk::VK_FALSE, cull_mode : vk::CULL_MODE_BACK_BIT, front_face : vk::FrontFace::Clockwise, line_width : 1.0, polygon_mode : vk::PolygonMode::Fill, rasterizer_discard_enable : vk::VK_FALSE, depth_bias_clamp : 0.0, depth_bias_constant_factor : 0.0, depth_bias_enable : vk::VK_FALSE, depth_bias_slope_factor : 0.0, }; let multisample_state_create_info = vk::PipelineMultisampleStateCreateInfo { s_type : vk::StructureType::PipelineMultisampleStateCreateInfo, flags : vk::PipelineMultisampleStateCreateFlags::empty(), p_next : ptr::null(), rasterization_samples : vk::SAMPLE_COUNT_1_BIT, sample_shading_enable : vk::VK_FALSE, min_sample_shading : 0.0, p_sample_mask : ptr::null(), alpha_to_one_enable : vk::VK_FALSE, alpha_to_coverage_enable : vk::VK_FALSE, }; let stencil_state = vk::StencilOpState { fail_op : vk::StencilOp::Keep, pass_op : vk::StencilOp::Keep, depth_fail_op : vk::StencilOp::Keep, compare_op : vk::CompareOp::Always, compare_mask : 0, write_mask : 0, reference : 0, }; let depth_state_create_info = vk::PipelineDepthStencilStateCreateInfo { s_type : vk::StructureType::PipelineDepthStencilStateCreateInfo, p_next : ptr::null(), flags : vk::PipelineDepthStencilStateCreateFlags::empty(), depth_test_enable : vk::VK_FALSE, depth_write_enable : vk::VK_FALSE, depth_compare_op : vk::CompareOp::LessOrEqual, depth_bounds_test_enable : vk::VK_FALSE, stencil_test_enable : vk::VK_FALSE, front : stencil_state, back : stencil_state, max_depth_bounds : 1.0, min_depth_bounds : 0.0, }; let color_blend_attachment_states = [ vk::PipelineColorBlendAttachmentState { blend_enable : vk::VK_FALSE, color_write_mask : vk::ColorComponentFlags::all(), src_color_blend_factor : vk::BlendFactor::One, dst_color_blend_factor : vk::BlendFactor::Zero, color_blend_op : vk::BlendOp::Add, src_alpha_blend_factor : vk::BlendFactor::One, dst_alpha_blend_factor : vk::BlendFactor::Zero, alpha_blend_op : vk::BlendOp::Add, }, ]; let color_blend_state = vk::PipelineColorBlendStateCreateInfo { s_type : vk::StructureType::PipelineColorBlendStateCreateInfo, p_next : ptr::null(), flags : vk::PipelineColorBlendStateCreateFlags::empty(), logic_op_enable : vk::VK_FALSE, logic_op : vk::LogicOp::Copy, attachment_count : color_blend_attachment_states.len() as u32, p_attachments : color_blend_attachment_states.as_ptr(), blend_constants : [0.0, 0.0, 0.0, 0.0], }; let pipeline_layout_create_info = vk::PipelineLayoutCreateInfo { s_type : vk::StructureType::PipelineLayoutCreateInfo, p_next : ptr::null(), flags : vk::PipelineLayoutCreateFlags::empty(), set_layout_count : 0, p_set_layouts : ptr::null(), push_constant_range_count : 0, p_push_constant_ranges : ptr::null(), }; let pipeline_layout = unsafe { device.create_pipeline_layout(&pipeline_layout_create_info, None) .expect("Failed to create pipeline layout!") }; let graphic_pipeline_create_infos = [ vk::GraphicsPipelineCreateInfo { s_type : vk::StructureType::GraphicsPipelineCreateInfo, p_next : ptr::null(), flags : vk::PipelineCreateFlags::empty(), stage_count : shader_stages.len() as u32, p_stages : shader_stages.as_ptr(), p_vertex_input_state : &vertex_input_state_create_info, p_input_assembly_state : &vertex_input_assembly_state_info, p_tessellation_state : ptr::null(), p_viewport_state : &viewport_state_create_info, p_rasterization_state : &rasterization_statue_create_info, p_multisample_state : &multisample_state_create_info, p_depth_stencil_state : &depth_state_create_info, p_color_blend_state : &color_blend_state, p_dynamic_state : ptr::null(), layout : pipeline_layout, render_pass, subpass : 0, base_pipeline_handle : vk::Pipeline::null(), base_pipeline_index : -1, }, ]; let graphics_pipelines = unsafe { device.create_graphics_pipelines(vk::PipelineCache::null(), &graphic_pipeline_create_infos, None) .expect("Failed to create Graphics Pipeline!.") }; unsafe { device.destroy_shader_module(vert_shader_module, None); device.destroy_shader_module(frag_shader_module, None); } (graphics_pipelines[0], pipeline_layout) } } // Fix content ------------------------------------------------------------------------------- impl VulkanApp { fn draw_frame(&mut self) { let wait_fences = [ self.in_flight_fences[self.current_frame] ]; unsafe { self.device.wait_for_fences(&wait_fences, true, std::u64::MAX) .expect("Failed to wait for Fence!"); } let image_index = unsafe { let result = self.swapchain_loader.acquire_next_image_khr(self.swapchain, std::u64::MAX, self.image_available_semaphores[self.current_frame], vk::Fence::null()); match result { | Ok(image_index) => image_index, | Err(vk_result) => match vk_result { | vk::types::Result::ErrorOutOfDateKhr => { self.recreate_swapchain(); return }, | _ => panic!("Failed to acquire Swap Chain Image!") } } }; let wait_semaphores = [ self.image_available_semaphores[self.current_frame], ]; let wait_stages = [ vk::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, ]; let signal_semaphores = [ self.render_finished_semaphores[self.current_frame], ]; let submit_infos = [ vk::SubmitInfo { s_type : vk::StructureType::SubmitInfo, p_next : ptr::null(), wait_semaphore_count : wait_semaphores.len() as u32, p_wait_semaphores : wait_semaphores.as_ptr(), p_wait_dst_stage_mask : wait_stages.as_ptr(), command_buffer_count : 1, p_command_buffers : &self.command_buffers[image_index as usize], signal_semaphore_count : signal_semaphores.len() as u32, p_signal_semaphores : signal_semaphores.as_ptr(), } ]; unsafe { self.device.reset_fences(&wait_fences) .expect("Failed to reset Fence!"); self.device.queue_submit(self.graphics_queue, &submit_infos, self.in_flight_fences[self.current_frame]) .expect("Failed to execute queue submit."); } let swapchains = [ self.swapchain ]; let present_info = vk::PresentInfoKHR { s_type : vk::StructureType::PresentInfoKhr, p_next : ptr::null(), wait_semaphore_count : 1, p_wait_semaphores : signal_semaphores.as_ptr(), swapchain_count : 1, p_swapchains : swapchains.as_ptr(), p_image_indices : &image_index, p_results : ptr::null_mut(), }; let result = unsafe { self.swapchain_loader.queue_present_khr(self.present_queue, &present_info) }; let is_resized = match result { Ok(_) => self.is_framebuffer_resized, Err(vk_result) => match vk_result { | vk::Result::ErrorOutOfDateKhr | vk::Result::SuboptimalKhr => { true } | _ => panic!("Failed to execute queue present.") } }; if is_resized { self.is_framebuffer_resized = false; self.recreate_swapchain(); } self.current_frame = (self.current_frame + 1) % MAX_FRAMES_IN_FLIGHT; } fn recreate_swapchain(&mut self) { // parameters ------------- let surface_suff = SurfaceStuff { surface_loader: self.surface_loader.clone(), surface: self.surface, screen_width: WINDOW_WIDTH, screen_height: WINDOW_HEIGHT, }; // ------------------------ self.device.device_wait_idle() .expect("Failed to wait device idle!"); self.cleanup_swapchain(); let swapchain_stuff = share::create_swapchain(&self.instance, &self.device, self.physical_device, &self.window, &surface_suff, &self.queue_family); self.swapchain_loader = swapchain_stuff.swapchain_loader; self.swapchain = swapchain_stuff.swapchain; self.swapchain_images = swapchain_stuff.swapchain_images; self.swapchain_format = swapchain_stuff.swapchain_format; self.swapchain_extent = swapchain_stuff.swapchain_extent; self.swapchain_imageviews = share::v1::create_image_views(&self.device, self.swapchain_format, &self.swapchain_images); self.render_pass = share::v1::create_render_pass(&self.device, self.swapchain_format); let (graphics_pipeline, pipeline_layout) = VulkanApp::create_graphics_pipeline(&self.device, self.render_pass, swapchain_stuff.swapchain_extent); self.graphics_pipeline = graphics_pipeline; self.pipeline_layout = pipeline_layout; self.swapchain_framebuffers = share::v1::create_framebuffers(&self.device, self.render_pass, &self.swapchain_imageviews, self.swapchain_extent); self.command_buffers = share::v1::create_command_buffers(&self.device, self.command_pool, self.graphics_pipeline, &self.swapchain_framebuffers, self.render_pass, self.swapchain_extent); } fn cleanup_swapchain(&self) { unsafe { self.device.free_command_buffers(self.command_pool, &self.command_buffers); for &framebuffer in self.swapchain_framebuffers.iter() { self.device.destroy_framebuffer(framebuffer, None); } self.device.destroy_pipeline(self.graphics_pipeline, None); self.device.destroy_pipeline_layout(self.pipeline_layout, None); self.device.destroy_render_pass(self.render_pass, None); for &image_view in self.swapchain_imageviews.iter() { self.device.destroy_image_view(image_view, None); } self.swapchain_loader.destroy_swapchain_khr(self.swapchain, None); } } } impl Drop for VulkanApp { fn drop(&mut self) { unsafe { for i in 0..MAX_FRAMES_IN_FLIGHT { self.device.destroy_semaphore(self.image_available_semaphores[i], None); self.device.destroy_semaphore(self.render_finished_semaphores[i], None); self.device.destroy_fence(self.in_flight_fences[i], None); } self.cleanup_swapchain(); self.device.destroy_command_pool(self.command_pool, None); self.device.destroy_device(None); self.surface_loader.destroy_surface_khr(self.surface, None); if VALIDATION.is_enable { self.debug_report_loader.destroy_debug_report_callback_ext(self.debug_callback, None); } self.instance.destroy_instance(None); } } } struct ProgramProc { events_loop: EventsLoop, } impl ProgramProc { fn new() -> ProgramProc { // init window stuff let events_loop = EventsLoop::new(); ProgramProc { events_loop, } } fn main_loop(&mut self, vulkan_app: &mut VulkanApp) { let mut is_first_toggle_resize = true; self.events_loop.run_forever(|event| { match event { | Event::WindowEvent { event, .. } => match event { | WindowEvent::KeyboardInput { input, .. } => { // keyboard events if let Some(VirtualKeyCode::Escape) = input.virtual_keycode { return ControlFlow::Break } } | WindowEvent::Resized(_) => { if is_first_toggle_resize == false { vulkan_app.is_framebuffer_resized = true; } else { is_first_toggle_resize = false; } }, | WindowEvent::CloseRequested => return ControlFlow::Break, | _ => (), }, | _ => (), } vulkan_app.draw_frame(); ControlFlow::Continue }); vulkan_app.device.device_wait_idle() .expect("Failed to wait device idle!"); } } fn main() { let mut program_proc = ProgramProc::new(); let mut vulkan_app = VulkanApp::new(&program_proc.events_loop); program_proc.main_loop(&mut vulkan_app); } // -------------------------------------------------------------------------------------------
41.908213
193
0.568415
8702c4abdc606fc824f464ee1019a361344c892a
614
#[macro_use] extern crate criterion; use aoclib::Solvable; use criterion::Criterion; fn part_one_benchmark(c: &mut Criterion) { c.bench_function("2019 day 12 part one", |b| { let input = aoclib::reader(2019, 12, "input.txt").unwrap(); b.iter(|| aoc201912::PartOne::solve(&input).unwrap()) }); } fn part_two_benchmark(c: &mut Criterion) { c.bench_function("2019 day 12 part two", |b| { let input = aoclib::reader(2019, 12, "input.txt").unwrap(); b.iter(|| aoc201912::PartTwo::solve(&input).unwrap()) }); } criterion_group!(benches, part_one_benchmark, part_two_benchmark); criterion_main!(benches);
26.695652
66
0.700326
385621bf99de7db4371cb5c438b35d092b8c757c
1,929
use crate::codegen::config_extractor::ConfigExtractor; use crate::errors::CoreResult; use crate::parser::code_map::Span; use crate::parser::{Located, Token}; use codespan_reporting::diagnostic::Diagnostic; use itertools::Itertools; use std::collections::HashSet; pub struct ConfigValidator { required: HashSet<String>, allowed: HashSet<String>, } impl ConfigValidator { pub fn new() -> Self { Self { required: HashSet::new(), allowed: HashSet::new(), } } pub fn required(mut self, key: &str) -> Self { self.required.insert(key.into()); self } pub fn allowed(mut self, key: &str) -> Self { self.allowed.insert(key.into()); self } pub fn extract<'a>( self, config_span: Span, kvps: &'a [(&'a Located<String>, &'a Located<Token>)], ) -> CoreResult<ConfigExtractor<'a>> { let mut errors = vec![]; let mut req = self.required.clone(); for (key, _) in kvps.iter().sorted_by_key(|(k, _)| &k.data) { if req.contains(&key.data) { req.remove(&key.data); } else if !self.allowed.contains(&key.data) { errors.push((Some(key.span), format!("field not allowed: {}", key.data))); } } if !req.is_empty() { let r = req.iter().sorted().join(", "); errors.push((None, format!("missing required fields: {}", r))); } let errors = errors .into_iter() .map(|(span, message)| { Diagnostic::error() .with_message(message) .with_labels(vec![span.unwrap_or(config_span).to_label()]) }) .collect_vec(); match errors.is_empty() { true => Ok(ConfigExtractor::new(config_span, kvps)), false => Err(errors.into()), } } }
28.791045
90
0.531363
4addeb1c58a52f6ef7aff1b1408e7cdc7a52d971
4,448
use std::boxed::Box; use std::fmt::Display; use std::fs::File; use std::fs::OpenOptions; use std::io::prelude::*; use std::io::Result; use std::path::Path; use std::str; use std::string::String; trait Writable { fn write(&self) -> Vec<u8>; } trait Readable { fn read() -> Self; } trait Document: Writable + Display {} struct Stock { name: String, value: u8, } impl Document for Stock {} impl Display for Stock { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { write!(f, "{}", self.name) } } impl Writable for Stock { fn write(&self) -> Vec<u8> { let name = self.name.as_bytes(); return [ &[self.value], &transform_u32_to_array_of_u8(name.len() as u32)[..], &name[..], ] .concat(); } } impl Stock { fn read(file: &mut impl Read) -> Self { let mut value = [0; 1]; file.read_exact(&mut value).expect("could not read value"); let name_size = read_u32(file).expect("Could not read size of name"); let mut name = vec![0; name_size as usize]; file.read_exact(&mut name) .expect("Could not read name or wrong size"); return Stock { name: String::from_utf8(name).expect("invalid UTF-8"), value: value[0], }; } } fn read_u32(r: &mut impl Read) -> Result<u32> { let mut buf = [0; 4]; r.read_exact(&mut buf)?; Ok(u32::from_be_bytes(buf)) } struct Node { id: u8, name: String, data: Box<dyn Document>, } impl Node { fn new() -> Node { let stock = Box::new(Stock { name: "tesla".to_string(), value: 2, }); return Node { id: 1, name: "portfolio".to_string(), data: stock, }; } fn to_buffer(&mut self) -> Vec<u8> { let data = self.data.write(); let name = self.name.as_bytes(); return [ &[self.id], &transform_u32_to_array_of_u8(name.len() as u32)[..], &name[..], &data[..], ] .concat(); } fn read(r: &mut impl Read) -> Self { let mut id = [0; 1]; r.read_exact(&mut id).expect("Cannot read id"); let name_size = read_u32(r).expect("Could not read the size of the name"); let mut name = vec![0; name_size as usize]; r.read_exact(&mut name) .expect("Could not read name or wrong size"); let stock = Box::new(Stock::read(r)); return Node { id: id[0], name: String::from_utf8(name).expect("invalid UTF-8"), data: stock, }; } } fn transform_u32_to_array_of_u8(x: u32) -> [u8; 4] { let b1: u8 = ((x >> 24) & 0xff) as u8; let b2: u8 = ((x >> 16) & 0xff) as u8; let b3: u8 = ((x >> 8) & 0xff) as u8; let b4: u8 = (x & 0xff) as u8; return [b1, b2, b3, b4]; } struct M2DB { data: File, relations: File, index: File, } impl M2DB { fn open_database(path: &str) -> M2DB { if !Path::new(&format!("{}/data.m2db", path)).exists() { File::create(format!("{}/data.m2db", path)); } if !Path::new(&format!("{}/index.m2db", path)).exists() { File::create(format!("{}/index.m2db", path)); } if !Path::new(&format!("{}/relations.m2db", path)).exists() { File::create(format!("{}/relations.m2db", path)); } let m2db = M2DB { data: OpenOptions::new() .read(true) .write(true) .open(format!("{}/data.m2db", path)) .unwrap(), relations: OpenOptions::new() .read(true) .write(true) .open(format!("{}/relations.m2db", path)) .unwrap(), index: OpenOptions::new() .read(true) .write(true) .open(format!("{}/index.m2db", path)) .unwrap(), }; return m2db; } } fn main() -> std::io::Result<()> { let mut f = File::create("./test.m2db")?; let buf = Node::new().to_buffer(); f.write_all(&buf)?; f = OpenOptions::new() .read(true) .write(true) .open("./test.m2db")?; let n = Node::read(&mut f); println!("id {} name {} data {}", n.id, n.name, n.data); Ok(()) }
25.563218
96
0.492131
9c25f1aa07cd2058398327f5b3dbeaa3ec68caee
13,548
// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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. use arrayvec::ArrayVec; pub const SIGMA: [[usize; 16]; 10] = [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], [ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], [ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], [ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], [ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0], ]; macro_rules! blake2_impl { ($state:ident, $result:ident, $func:ident, $word:ident, $vec:ident, $bytes:expr, $R1:expr, $R2:expr, $R3:expr, $R4:expr, $IV:expr) => { use core::cmp; #[cfg(feature = "std")] use std::io; use $crate::as_bytes::AsBytes; use $crate::bytes::BytesExt; use $crate::constant_time_eq::constant_time_eq; use $crate::simd::{Vector4, $vec}; /// Container for a hash result. /// /// This container uses a constant-time comparison for equality. /// If a constant-time comparison is not necessary, the hash /// result can be extracted with the `as_bytes` method. #[derive(Clone, Copy, Debug)] pub struct $result { h: [$vec; 2], nn: usize, } #[cfg_attr(feature = "cargo-clippy", allow(len_without_is_empty))] impl $result { /// Returns the contained hash result as a byte string. #[inline] pub fn as_bytes(&self) -> &[u8] { &self.h.as_bytes()[..self.nn] } /// Returns the length of the hash result. /// /// This is the same value that was used to create the hash /// context. #[inline] pub fn len(&self) -> usize { self.nn } } impl AsRef<[u8]> for $result { #[inline] fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl Eq for $result { } impl PartialEq for $result { #[inline] fn eq(&self, other: &Self) -> bool { constant_time_eq(self.as_bytes(), other.as_bytes()) } } impl PartialEq<[u8]> for $result { #[inline] fn eq(&self, other: &[u8]) -> bool { constant_time_eq(self.as_bytes(), other) } } /// State context. #[derive(Clone, Debug)] pub struct $state { m: [$word; 16], h: [$vec; 2], t: u64, nn: usize, } const IV: [$word; 8] = $IV; #[inline(always)] fn iv0() -> $vec { $vec::new(IV[0], IV[1], IV[2], IV[3]) } #[inline(always)] fn iv1() -> $vec { $vec::new(IV[4], IV[5], IV[6], IV[7]) } /// Convenience function for all-in-one computation. pub fn $func(nn: usize, k: &[u8], data: &[u8]) -> $result { let mut state = $state::with_key(nn, k); state.update(data); state.finalize() } impl $state { /// Creates a new hashing context without a key. pub fn new(nn: usize) -> Self { Self::with_key(nn, &[]) } /// Creates a new hashing context with a key. #[cfg_attr(feature = "cargo-clippy", allow(cast_possible_truncation))] pub fn with_key(nn: usize, k: &[u8]) -> Self { let kk = k.len(); assert!(nn >= 1 && nn <= $bytes && kk <= $bytes); let p0 = 0x01010000 ^ ((kk as $word) << 8) ^ (nn as $word); let mut state = $state { m: [0; 16], h: [iv0() ^ $vec::new(p0, 0, 0, 0), iv1()], t: 0, nn: nn, }; if kk > 0 { state.m.as_mut_bytes().copy_bytes_from(k); state.t = $bytes * 2; } state } #[doc(hidden)] #[cfg_attr(feature = "cargo-clippy", allow(cast_possible_truncation))] pub fn with_parameter_block(p: &[$word; 8]) -> Self { let nn = p[0] as u8 as usize; let kk = (p[0] >> 8) as u8 as usize; assert!(nn >= 1 && nn <= $bytes && kk <= $bytes); $state { m: [0; 16], h: [iv0() ^ $vec::new(p[0], p[1], p[2], p[3]), iv1() ^ $vec::new(p[4], p[5], p[6], p[7])], t: 0, nn: nn, } } /// Updates the hashing context with more data. #[cfg_attr(feature = "cargo-clippy", allow(cast_possible_truncation))] pub fn update(&mut self, data: &[u8]) { let mut rest = data; let off = (self.t % ($bytes * 2)) as usize; if off != 0 || self.t == 0 { let len = cmp::min(($bytes * 2) - off, rest.len()); let part = &rest[..len]; rest = &rest[part.len()..]; self.m.as_mut_bytes()[off..].copy_bytes_from(part); self.t = self.t.checked_add(part.len() as u64) .expect("hash data length overflow"); } while rest.len() >= $bytes * 2 { self.compress(0, 0); let part = &rest[..($bytes * 2)]; rest = &rest[part.len()..]; self.m.as_mut_bytes().copy_bytes_from(part); self.t = self.t.checked_add(part.len() as u64) .expect("hash data length overflow"); } if rest.len() > 0 { self.compress(0, 0); self.m.as_mut_bytes().copy_bytes_from(rest); self.t = self.t.checked_add(rest.len() as u64) .expect("hash data length overflow"); } } #[cfg_attr(feature = "cargo-clippy", allow(cast_possible_truncation))] fn finalize_with_flag(&mut self, f1: $word) { let off = (self.t % ($bytes * 2)) as usize; if off != 0 { self.m.as_mut_bytes()[off..].set_bytes(0); } self.compress(!0, f1); } /// Consumes the hashing context and returns the resulting hash. #[inline] pub fn finalize(mut self) -> $result { self.finalize_with_flag(0); self.into_result() } #[doc(hidden)] #[inline] pub fn finalize_last_node(mut self) -> $result { self.finalize_with_flag(!0); self.into_result() } #[doc(hidden)] pub fn finalize_inplace(&mut self) -> &[u8] { self.finalize_with_flag(0); self.result_inplace() } #[doc(hidden)] pub fn finalize_last_node_inplace(&mut self) -> &[u8] { self.finalize_with_flag(!0); self.result_inplace() } #[inline] fn into_result(self) -> $result { $result { h: [self.h[0].to_le(), self.h[1].to_le()], nn: self.nn, } } fn result_inplace(&mut self) -> &[u8] { self.h[0] = self.h[0].to_le(); self.h[1] = self.h[1].to_le(); let result = &self.h.as_bytes()[..self.nn]; self.nn = 0; // poison self result } #[inline(always)] fn quarter_round(v: &mut [$vec; 4], rd: u32, rb: u32, m: $vec) { v[0] = v[0].wrapping_add(v[1]).wrapping_add(m.from_le()); v[3] = (v[3] ^ v[0]).rotate_right_const(rd); v[2] = v[2].wrapping_add(v[3]); v[1] = (v[1] ^ v[2]).rotate_right_const(rb); } #[inline(always)] fn shuffle(v: &mut [$vec; 4]) { v[1] = v[1].shuffle_left_1(); v[2] = v[2].shuffle_left_2(); v[3] = v[3].shuffle_left_3(); } #[inline(always)] fn unshuffle(v: &mut [$vec; 4]) { v[1] = v[1].shuffle_right_1(); v[2] = v[2].shuffle_right_2(); v[3] = v[3].shuffle_right_3(); } #[inline(always)] fn round(v: &mut [$vec; 4], m: &[$word; 16], s: &[usize; 16]) { $state::quarter_round(v, $R1, $R2, $vec::gather(m, s[ 0], s[ 2], s[ 4], s[ 6])); $state::quarter_round(v, $R3, $R4, $vec::gather(m, s[ 1], s[ 3], s[ 5], s[ 7])); $state::shuffle(v); $state::quarter_round(v, $R1, $R2, $vec::gather(m, s[ 8], s[10], s[12], s[14])); $state::quarter_round(v, $R3, $R4, $vec::gather(m, s[ 9], s[11], s[13], s[15])); $state::unshuffle(v); } #[cfg_attr(feature = "cargo-clippy", allow(cast_possible_truncation, eq_op))] fn compress(&mut self, f0: $word, f1: $word) { use $crate::blake2::SIGMA; let m = &self.m; let h = &mut self.h; let t0 = self.t as $word; let t1 = match $bytes { 64 => 0, 32 => (self.t >> 32) as $word, _ => unreachable!(), }; let mut v = [ h[0], h[1], iv0(), iv1() ^ $vec::new(t0, t1, f0, f1), ]; $state::round(&mut v, m, &SIGMA[0]); $state::round(&mut v, m, &SIGMA[1]); $state::round(&mut v, m, &SIGMA[2]); $state::round(&mut v, m, &SIGMA[3]); $state::round(&mut v, m, &SIGMA[4]); $state::round(&mut v, m, &SIGMA[5]); $state::round(&mut v, m, &SIGMA[6]); $state::round(&mut v, m, &SIGMA[7]); $state::round(&mut v, m, &SIGMA[8]); $state::round(&mut v, m, &SIGMA[9]); if $bytes > 32 { $state::round(&mut v, m, &SIGMA[0]); $state::round(&mut v, m, &SIGMA[1]); } h[0] = h[0] ^ (v[0] ^ v[2]); h[1] = h[1] ^ (v[1] ^ v[3]); } } impl Default for $state { fn default() -> Self { Self::new($bytes) } } #[cfg(feature = "std")] impl io::Write for $state { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { if self.t.checked_add(buf.len() as u64).is_none() { return Err(io::Error::new(io::ErrorKind::WriteZero, "counter overflow")); } self.update(buf); Ok(buf.len()) } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } } } #[cfg_attr(feature = "cargo-clippy", allow(cast_possible_truncation, unreadable_literal))] #[cold] #[doc(hidden)] pub fn selftest_seq(len: usize) -> ArrayVec<u8, 1024> { use core::num::Wrapping; let seed = Wrapping(len as u32); let mut out = ArrayVec::new(); let mut a = Wrapping(0xDEAD4BAD) * seed; let mut b = Wrapping(1); for _ in 0..len { let t = a + b; a = b; b = t; out.push((t >> 24).0 as u8); } out } macro_rules! blake2_selftest_impl { ($state:ident, $func:ident, $res:expr, $md_len:expr, $in_len:expr) => { /// Runs the self-test for this hash function. #[cold] pub fn selftest() { use $crate::blake2::selftest_seq; const BLAKE2_RES: [u8; 32] = $res; const B2_MD_LEN: [usize; 4] = $md_len; const B2_IN_LEN: [usize; 6] = $in_len; let mut state = $state::new(32); for &outlen in &B2_MD_LEN { for &inlen in &B2_IN_LEN { let data = selftest_seq(inlen); let md = $func(outlen, &[], &data); state.update(md.as_bytes()); let key = selftest_seq(outlen); let md = $func(outlen, &key, &data); state.update(md.as_bytes()); } } assert_eq!(&state.finalize(), &BLAKE2_RES[..]); } } }
34.738462
90
0.418438
f5f689389ad35c2d1b7ce2d0b43bef21bce49e10
3,386
use crate::MercuryError; use crate::address::{Address, AddressPayload, CodeHashIndex}; use crate::NetworkType; use anyhow::Result; use ckb_types::{packed, H160, U256}; use derive_more::Display; use num_bigint::BigUint; use std::convert::TryInto; use std::str::FromStr; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ScriptInfo { pub script: packed::Script, pub cell_dep: packed::CellDep, } #[derive(Clone, Debug, Display)] enum UtilsError { #[display(fmt = "Already a short CKB address")] _AlreadyShortCKBAddress, #[display(fmt = "Parse CKB address error {}", _0)] ParseCKBAddressError(String), } // Convert to short address, use as universal identity pub fn parse_address(input: &str) -> Result<Address> { match Address::from_str(input) { Ok(addr) => Ok(addr), Err(e) => Err(MercuryError::utils(UtilsError::ParseCKBAddressError(e)).into()), } } pub fn to_universal_identity(net_ty: NetworkType, input: &Address, is_new: bool) -> Address { Address::new( input.network(), AddressPayload::new_short( net_ty, CodeHashIndex::Sighash, H160::from_slice(input.payload().args().as_ref()).unwrap(), ), is_new, ) } pub fn to_fixed_array<const LEN: usize>(input: &[u8]) -> [u8; LEN] { assert_eq!(input.len(), LEN); let mut list = [0; LEN]; list.copy_from_slice(input); list } pub fn find<T: Eq>(key: &T, from: &[T]) -> Option<usize> { for (index, item) in from.iter().enumerate() { if item == key { return Some(index); } } None } pub fn remove_item<T: Eq>(list: &mut Vec<T>, key: &T) { let mut index = usize::MAX; for (idx, item) in list.iter().enumerate() { if item == key { index = idx; break; } } list.remove(index); } #[allow(dead_code)] pub fn u64_sub(a: u64, b: BigUint) -> u64 { let b: u64 = b.try_into().unwrap(); a.saturating_sub(b) } pub fn u128_sub(a: u128, b: BigUint) -> u128 { let b: u128 = b.try_into().unwrap(); a.saturating_sub(b) } pub fn unwrap_only_one<T: Clone>(vec: &[T]) -> T { assert!(vec.len() == 1); vec[0].clone() } pub fn decode_udt_amount(data: &[u8]) -> u128 { if data.len() < 16 { return 0u128; } u128::from_le_bytes(to_fixed_array(&data[0..16])) } pub fn encode_udt_amount(amount: u128) -> Vec<u8> { amount.to_le_bytes().to_vec() } pub fn decode_nonce(data: &[u8]) -> u128 { u128::from_be_bytes(to_fixed_array(&data[0..16])) } pub fn decode_dao_block_number(data: &[u8]) -> u64 { u64::from_le_bytes(to_fixed_array(&data[0..8])) } pub fn decode_u64(data: &[u8]) -> u64 { u64::from_le_bytes(to_fixed_array(&data[0..8])) } pub fn u256_low_u64(u: U256) -> u64 { u.0[0] } #[cfg(test)] mod test { use super::*; use rand::random; fn rand_bytes(len: usize) -> Vec<u8> { (0..len).map(|_| random::<u8>()).collect::<Vec<_>>() } #[test] fn test_to_fixed_array() { let bytes = rand_bytes(3); let a = to_fixed_array::<3>(&bytes); let mut b = [0u8; 3]; b.copy_from_slice(&bytes); assert_eq!(a, b); } #[test] fn test_find() { let test = (0..10).collect::<Vec<_>>(); test.iter() .for_each(|i| assert_eq!(find(i, &test), Some(*i))); } }
23.034014
93
0.586533
622d3aeb9b8681f2d91556cec157a70191e39b85
3,651
use crate::schema::MongoSchema; use datamodel::common::preview_features::PreviewFeature; use enumflags2::BitFlags; use futures::stream::TryStreamExt; use migration_connector::{ConnectorError, ConnectorResult}; use mongodb::{ bson::{Bson, Document}, error::Error as MongoError, options::{ClientOptions, WriteConcern}, }; use url::Url; /// The indexes MongoDB automatically creates for the object id in each collection. const AUTOMATIC_ID_INDEX_NAME: &str = "_id_"; /// Abstraction over a mongodb connection (exposed for tests). pub struct Client { inner: mongodb::Client, db_name: String, } impl Client { pub async fn connect(connection_str: &str) -> ConnectorResult<Client> { let url = Url::parse(connection_str).map_err(ConnectorError::url_parse_error)?; let db_name = url.path().trim_start_matches('/').to_string(); let client_options = ClientOptions::parse(connection_str) .await .map_err(mongo_error_to_connector_error)?; let inner = mongodb::Client::with_options(client_options).map_err(mongo_error_to_connector_error)?; Ok(Client { inner, db_name }) } pub(crate) fn database(&self) -> mongodb::Database { self.inner.database(&self.db_name) } pub(crate) async fn describe(&self, preview_features: BitFlags<PreviewFeature>) -> ConnectorResult<MongoSchema> { let mut schema = MongoSchema::default(); let database = self.database(); let mut cursor = database .list_collections(None, None) .await .map_err(mongo_error_to_connector_error)?; while let Some(collection) = cursor.try_next().await.map_err(mongo_error_to_connector_error)? { let collection_name = collection.name; let collection = database.collection::<Document>(&collection_name); let collection_id = schema.push_collection(collection_name); let mut indexes_cursor = collection .list_indexes(None) .await .map_err(mongo_error_to_connector_error)?; while let Some(index) = indexes_cursor .try_next() .await .map_err(mongo_error_to_connector_error)? { let options = index.options.unwrap(); let name = options.name.unwrap(); let is_unique = options.unique.unwrap_or(false); // 3-valued boolean where null means false if name == AUTOMATIC_ID_INDEX_NAME { continue; // do not introspect or diff these } let path = if preview_features.contains(PreviewFeature::ExtendedIndexes) { index.keys } else { index.keys.iter().fold(Document::new(), |mut acc, (k, _)| { acc.insert(k, Bson::Int32(1)); acc }) }; schema.push_index(collection_id, name, is_unique, dbg!(path)); } } Ok(schema) } pub(crate) async fn drop_database(&self) -> ConnectorResult<()> { self.database() .drop(Some( mongodb::options::DropDatabaseOptions::builder() .write_concern(WriteConcern::builder().journal(true).build()) .build(), )) .await .map_err(mongo_error_to_connector_error) } } pub(crate) fn mongo_error_to_connector_error(mongo_error: MongoError) -> ConnectorError { ConnectorError::from_source(mongo_error, "MongoDB error") }
35.446602
117
0.60504
76ca7410fb3460e5fe698922e834e96f0bf3c3c4
19,279
//! Moves HVM Terms to runtime, and building dynamic functions. // TODO: "dups" still needs to be moved out on `alloc_body` etc. use crate::language as lang; use crate::readback as rd; use crate::rulebook as rb; use crate::runtime as rt; use std::collections::HashMap; use std::iter; use std::time::Instant; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[derive(Debug)] pub enum DynTerm { Var { bidx: u64 }, Glo { glob: u64 }, Dup { eras: (bool, bool), expr: Box<DynTerm>, body: Box<DynTerm> }, Let { expr: Box<DynTerm>, body: Box<DynTerm> }, Lam { eras: bool, glob: u64, body: Box<DynTerm> }, App { func: Box<DynTerm>, argm: Box<DynTerm> }, Cal { func: u64, args: Vec<DynTerm> }, Ctr { func: u64, args: Vec<DynTerm> }, U32 { numb: u32 }, Op2 { oper: u64, val0: Box<DynTerm>, val1: Box<DynTerm> }, } // The right-hand side of a rule, "digested" or "pre-filled" in a way that is almost ready to be // pasted into the runtime's memory, except for some minor adjustments: internal links need to be // adjusted taking in account the index where each node is actually allocated, and external // variables must be linked. This structure helps moving as much computation from the interpreter // to the static time (i.e., when generating the dynfun closure) as possible. pub type Body = (Elem, Vec<Node>); // The pre-filled body (TODO: can the Node Vec be unboxed?) pub type Node = Vec<Elem>; // A node on the pre-filled body #[derive(Copy, Clone, Debug)] pub enum Elem { // An element of a node Fix { value: u64 }, // Fixed value, doesn't require adjustment Loc { value: u64, targ: u64, slot: u64 }, // Local link, requires adjustment Ext { index: u64 }, // Link to an external variable } #[derive(Debug)] pub struct DynVar { pub param: u64, pub field: Option<u64>, pub erase: bool, } #[derive(Debug)] pub struct DynRule { pub cond: Vec<rt::Lnk>, pub vars: Vec<DynVar>, pub term: DynTerm, pub body: Body, pub free: Vec<(u64, u64)>, } #[derive(Debug)] pub struct DynFun { pub redex: Vec<bool>, pub rules: Vec<DynRule>, } pub fn build_dynfun(comp: &rb::RuleBook, rules: &[lang::Rule]) -> DynFun { let mut redex = if let lang::Term::Ctr { name: _, ref args } = *rules[0].lhs { vec![false; args.len()] } else { panic!("Invalid left-hand side: {}", rules[0].lhs); }; let dynrules = rules .iter() .filter_map(|rule| { if let lang::Term::Ctr { ref name, ref args } = *rule.lhs { let mut cond = Vec::new(); let mut vars = Vec::new(); let mut free = Vec::new(); if args.len() != redex.len() { panic!("Inconsistent length of left-hand side on equation for '{}'.", name); } for ((i, arg), redex) in args.iter().enumerate().zip(redex.iter_mut()) { match &**arg { lang::Term::Ctr { name, args } => { *redex = true; cond.push(rt::Ctr(args.len() as u64, *comp.name_to_id.get(&*name).unwrap_or(&0), 0)); free.push((i as u64, args.len() as u64)); for (j, arg) in args.iter().enumerate() { if let lang::Term::Var { ref name } = **arg { vars.push(DynVar { param: i as u64, field: Some(j as u64), erase: name == "*" }); } else { panic!("Sorry, left-hand sides can't have nested constructors yet."); } } } lang::Term::U32 { numb } => { *redex = true; cond.push(rt::U_32(*numb as u64)); } lang::Term::Var { name } => { cond.push(0); vars.push(DynVar { param: i as u64, field: None, erase: name == "*" }); } _ => { panic!("Invalid left-hand side."); } } } let term = term_to_dynterm(comp, &rule.rhs, vars.len() as u64); let body = build_body(&term, vars.len() as u64); Some(DynRule { cond, vars, term, body, free }) } else { None } }) .collect(); DynFun { redex, rules: dynrules } } pub fn get_var(mem: &rt::Worker, term: rt::Lnk, var: &DynVar) -> rt::Lnk { let DynVar { param, field, erase: _ } = var; match field { Some(i) => rt::ask_arg(mem, rt::ask_arg(mem, term, *param), *i), None => rt::ask_arg(mem, term, *param), } } pub fn hash<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } pub fn build_runtime_functions(comp: &rb::RuleBook) -> Vec<Option<rt::Function>> { //let mut dups_count = DupsCount::new(); let mut funcs: Vec<Option<rt::Function>> = iter::repeat_with(|| None).take(65535).collect(); for (name, rules_info) in &comp.rule_group { let fnid = comp.name_to_id.get(name).unwrap_or(&0); let func = build_runtime_function(comp, &rules_info.1); funcs[*fnid as usize] = Some(func); } funcs } pub fn build_runtime_function(comp: &rb::RuleBook, rules: &[lang::Rule]) -> rt::Function { let dynfun = build_dynfun(comp, rules); let arity = dynfun.redex.len() as u64; let mut stricts = Vec::new(); for (i, is_redex) in dynfun.redex.iter().enumerate() { if *is_redex { stricts.push(i as u64); } } let rewriter: rt::Rewriter = Box::new(move |mem, dups, host, term| { // For each argument, if it is a redex and a PAR, apply the cal_par rule for (i, redex) in dynfun.redex.iter().enumerate() { let i = i as u64; if *redex && rt::get_tag(rt::ask_arg(mem, term, i)) == rt::PAR { rt::cal_par(mem, host, term, rt::ask_arg(mem, term, i), i); return true; } } // For each rule condition vector for dynrule in &dynfun.rules { // Check if the rule matches let mut matched = true; // Tests each rule condition (ex: `get_tag(args[0]) == SUCC`) for (i, cond) in dynrule.cond.iter().enumerate() { let i = i as u64; match rt::get_tag(*cond) { rt::U32 => { //println!("Didn't match because of U32. i={} {} {}", i, rt::get_val(rt::ask_arg(mem, term, i)), rt::get_val(*cond)); let same_tag = rt::get_tag(rt::ask_arg(mem, term, i)) == rt::U32; let same_val = rt::get_val(rt::ask_arg(mem, term, i)) == rt::get_val(*cond); matched = matched && same_tag && same_val; } rt::CTR => { //println!("Didn't match because of CTR. i={} {} {}", i, rt::get_tag(rt::ask_arg(mem, term, i)), rt::get_val(*cond)); let same_tag = rt::get_tag(rt::ask_arg(mem, term, i)) == rt::CTR; let same_ext = rt::get_ext(rt::ask_arg(mem, term, i)) == rt::get_ext(*cond); matched = matched && same_tag && same_ext; } _ => {} } } // If all conditions are satisfied, the rule matched, so we must apply it if matched { // Increments the gas count rt::inc_cost(mem); // Builds the right-hand side term (ex: `(Succ (Add a b))`) let done = alloc_body(mem, term, &dynrule.vars, dups, &dynrule.body); // Links the host location to it rt::link(mem, host, done); // Clears the matched ctrs (the `(Succ ...)` and the `(Add ...)` ctrs) rt::clear(mem, rt::get_loc(term, 0), dynfun.redex.len() as u64); for (i, arity) in &dynrule.free { let i = *i as u64; rt::clear(mem, rt::get_loc(rt::ask_arg(mem, term, i), 0), *arity); } // Collects unused variables (none in this example) for dynvar @ DynVar { param: _, field: _, erase } in dynrule.vars.iter() { if *erase { rt::collect(mem, get_var(mem, term, dynvar)); } } return true; } } false }); rt::Function { arity, stricts, rewriter } } /// Converts a language Term to a runtime Term pub fn term_to_dynterm(comp: &rb::RuleBook, term: &lang::Term, free_vars: u64) -> DynTerm { fn convert_oper(oper: &lang::Oper) -> u64 { match oper { lang::Oper::Add => rt::ADD, lang::Oper::Sub => rt::SUB, lang::Oper::Mul => rt::MUL, lang::Oper::Div => rt::DIV, lang::Oper::Mod => rt::MOD, lang::Oper::And => rt::AND, lang::Oper::Or => rt::OR, lang::Oper::Xor => rt::XOR, lang::Oper::Shl => rt::SHL, lang::Oper::Shr => rt::SHR, lang::Oper::Ltn => rt::LTN, lang::Oper::Lte => rt::LTE, lang::Oper::Eql => rt::EQL, lang::Oper::Gte => rt::GTE, lang::Oper::Gtn => rt::GTN, lang::Oper::Neq => rt::NEQ, } } #[allow(clippy::identity_op)] fn convert_term( term: &lang::Term, comp: &rb::RuleBook, depth: u64, vars: &mut Vec<String>, ) -> DynTerm { match term { lang::Term::Var { name } => { if let Some((idx, _)) = vars.iter().enumerate().rev().find(|(_, var)| var == &name) { DynTerm::Var { bidx: idx as u64 } } else { DynTerm::Glo { glob: hash(name) } } } lang::Term::Dup { nam0, nam1, expr, body } => { let eras = (nam0 == "*", nam1 == "*"); let expr = Box::new(convert_term(expr, comp, depth + 0, vars)); vars.push(nam0.clone()); vars.push(nam1.clone()); let body = Box::new(convert_term(body, comp, depth + 2, vars)); vars.pop(); vars.pop(); DynTerm::Dup { eras, expr, body } } lang::Term::Lam { name, body } => { let glob = if rb::is_global_name(name) { hash(name) } else { 0 }; let eras = name == "*"; vars.push(name.clone()); let body = Box::new(convert_term(body, comp, depth + 1, vars)); vars.pop(); DynTerm::Lam { eras, glob, body } } lang::Term::Let { name, expr, body } => { let expr = Box::new(convert_term(expr, comp, depth + 0, vars)); vars.push(name.clone()); let body = Box::new(convert_term(body, comp, depth + 1, vars)); vars.pop(); DynTerm::Let { expr, body } } lang::Term::App { func, argm } => { let func = Box::new(convert_term(func, comp, depth + 0, vars)); let argm = Box::new(convert_term(argm, comp, depth + 0, vars)); DynTerm::App { func, argm } } lang::Term::Ctr { name, args } => { let term_func = *comp.name_to_id.get(name).unwrap_or_else(|| panic!("Unbound symbol: {}", name)); let term_args = args.iter().map(|arg| convert_term(arg, comp, depth + 0, vars)).collect(); if *comp.ctr_is_cal.get(name).unwrap_or(&false) { DynTerm::Cal { func: term_func, args: term_args } } else { DynTerm::Ctr { func: term_func, args: term_args } } } lang::Term::U32 { numb } => DynTerm::U32 { numb: *numb }, lang::Term::Op2 { oper, val0, val1 } => { let oper = convert_oper(oper); let val0 = Box::new(convert_term(val0, comp, depth + 0, vars)); let val1 = Box::new(convert_term(val1, comp, depth + 1, vars)); DynTerm::Op2 { oper, val0, val1 } } } } let mut vars = (0..free_vars).map(|i| format!("x{}", i)).collect(); convert_term(term, comp, 0, &mut vars) } pub fn build_body(term: &DynTerm, free_vars: u64) -> Body { fn link(nodes: &mut [Node], targ: u64, slot: u64, elem: Elem) { nodes[targ as usize][slot as usize] = elem; if let Elem::Loc { value, targ: var_targ, slot: var_slot } = elem { let tag = rt::get_tag(value); if tag <= rt::VAR { nodes[var_targ as usize][(var_slot + (tag & 0x01)) as usize] = Elem::Loc { value: rt::Arg(0), targ, slot }; } } } fn alloc_lam(globs: &mut HashMap<u64, u64>, nodes: &mut Vec<Node>, glob: u64) -> u64 { if let Some(targ) = globs.get(&glob) { *targ } else { let targ = nodes.len() as u64; nodes.push(vec![Elem::Fix { value: 0 }; 2]); link(nodes, targ, 0, Elem::Fix { value: rt::Era() }); if glob != 0 { globs.insert(glob, targ); } targ } } fn gen_elems( term: &DynTerm, vars: &mut Vec<Elem>, globs: &mut HashMap<u64, u64>, nodes: &mut Vec<Node>, links: &mut Vec<(u64, u64, Elem)>, ) -> Elem { match term { DynTerm::Var { bidx } => { if *bidx < vars.len() as u64 { vars[*bidx as usize] } else { panic!("Unbound variable."); } } DynTerm::Glo { glob } => { let targ = alloc_lam(globs, nodes, *glob); Elem::Loc { value: rt::Var(0), targ, slot: 0 } } DynTerm::Dup { eras: _, expr, body } => { let targ = nodes.len() as u64; nodes.push(vec![Elem::Fix { value: 0 }; 3]); //let dupk = dups_count.next(); links.push((targ, 0, Elem::Fix { value: rt::Era() })); links.push((targ, 1, Elem::Fix { value: rt::Era() })); let expr = gen_elems(expr, vars, globs, nodes, links); links.push((targ, 2, expr)); vars.push(Elem::Loc { value: rt::Dp0(0, 0), targ, slot: 0 }); vars.push(Elem::Loc { value: rt::Dp1(0, 0), targ, slot: 0 }); let body = gen_elems(body, vars, globs, nodes, links); vars.pop(); vars.pop(); body } DynTerm::Let { expr, body } => { let expr = gen_elems(expr, vars, globs, nodes, links); vars.push(expr); let body = gen_elems(body, vars, globs, nodes, links); vars.pop(); body } DynTerm::Lam { eras: _, glob, body } => { let targ = alloc_lam(globs, nodes, *glob); let var = Elem::Loc { value: rt::Var(0), targ, slot: 0 }; vars.push(var); let body = gen_elems(body, vars, globs, nodes, links); links.push((targ, 1, body)); vars.pop(); Elem::Loc { value: rt::Lam(0), targ, slot: 0 } } DynTerm::App { func, argm } => { let targ = nodes.len() as u64; nodes.push(vec![Elem::Fix { value: 0 }; 2]); let func = gen_elems(func, vars, globs, nodes, links); links.push((targ, 0, func)); let argm = gen_elems(argm, vars, globs, nodes, links); links.push((targ, 1, argm)); Elem::Loc { value: rt::App(0), targ, slot: 0 } } DynTerm::Cal { func, args } => { if !args.is_empty() { let targ = nodes.len() as u64; nodes.push(vec![Elem::Fix { value: 0 }; args.len() as usize]); for (i, arg) in args.iter().enumerate() { let arg = gen_elems(arg, vars, globs, nodes, links); links.push((targ, i as u64, arg)); } Elem::Loc { value: rt::Cal(args.len() as u64, *func, 0), targ, slot: 0 } } else { Elem::Fix { value: rt::Cal(0, *func, 0) } } } DynTerm::Ctr { func, args } => { if !args.is_empty() { let targ = nodes.len() as u64; nodes.push(vec![Elem::Fix { value: 0 }; args.len() as usize]); for (i, arg) in args.iter().enumerate() { let arg = gen_elems(arg, vars, globs, nodes, links); links.push((targ, i as u64, arg)); } Elem::Loc { value: rt::Ctr(args.len() as u64, *func, 0), targ, slot: 0 } } else { Elem::Fix { value: rt::Ctr(0, *func, 0) } } } DynTerm::U32 { numb } => Elem::Fix { value: rt::U_32(*numb as u64) }, DynTerm::Op2 { oper, val0, val1 } => { let targ = nodes.len() as u64; nodes.push(vec![Elem::Fix { value: 0 }; 2]); let val0 = gen_elems(val0, vars, globs, nodes, links); links.push((targ, 0, val0)); let val1 = gen_elems(val1, vars, globs, nodes, links); links.push((targ, 1, val1)); Elem::Loc { value: rt::Op2(*oper, 0), targ, slot: 0 } } } } let mut links: Vec<(u64, u64, Elem)> = Vec::new(); let mut nodes: Vec<Node> = Vec::new(); let mut globs: HashMap<u64, u64> = HashMap::new(); let mut vars: Vec<Elem> = (0..free_vars).map(|i| Elem::Ext { index: i }).collect(); let elem = gen_elems(term, &mut vars, &mut globs, &mut nodes, &mut links); for (targ, slot, elem) in links { link(&mut nodes, targ, slot, elem); } (elem, nodes) } static mut ALLOC_BODY_WORKSPACE: &mut [u64] = &mut [0; 256 * 256 * 256]; // to avoid dynamic allocations pub fn alloc_body( mem: &mut rt::Worker, term: rt::Lnk, vars: &[DynVar], dups: &mut u64, body: &Body, ) -> rt::Lnk { unsafe { let hosts = &mut ALLOC_BODY_WORKSPACE; let (elem, nodes) = body; fn elem_to_lnk( mem: &mut rt::Worker, term: rt::Lnk, vars: &[DynVar], dups: &mut u64, elem: &Elem, ) -> rt::Lnk { unsafe { let hosts = &mut ALLOC_BODY_WORKSPACE; match elem { Elem::Fix { value } => *value, Elem::Ext { index } => get_var(mem, term, &vars[*index as usize]), Elem::Loc { value, targ, slot } => { let mut val = value + hosts[*targ as usize] + slot; // should be changed if the pointer format changes if rt::get_tag(*value) == rt::DP0 { val += (*dups & 0xFFFFFF) * rt::EXT; } if rt::get_tag(*value) == rt::DP1 { val += (*dups & 0xFFFFFF) * rt::EXT; *dups += 1; } val } } } } nodes.iter().enumerate().for_each(|(i, node)| { hosts[i] = rt::alloc(mem, node.len() as u64); }); nodes.iter().enumerate().for_each(|(i, node)| { let host = hosts[i] as usize; node.iter().enumerate().for_each(|(j, elem)| { let lnk = elem_to_lnk(mem, term, vars, dups, elem); if let Elem::Ext { .. } = elem { rt::link(mem, (host + j) as u64, lnk); } else { mem.node[host + j] = lnk; } }); }); elem_to_lnk(mem, term, vars, dups, elem) } } pub fn alloc_closed_dynterm(mem: &mut rt::Worker, term: &DynTerm) -> u64 { let mut dups = 0; let host = rt::alloc(mem, 1); let body = build_body(term, 0); let term = alloc_body(mem, 0, &[], &mut dups, &body); rt::link(mem, host, term); host } pub fn alloc_term(mem: &mut rt::Worker, comp: &rb::RuleBook, term: &lang::Term) -> u64 { alloc_closed_dynterm(mem, &term_to_dynterm(comp, term, 0)) } // Evaluates a HVM term to normal form pub fn eval_code( call: &lang::Term, code: &str, debug: bool, ) -> Result<(String, u64, u64, u64), String> { let mut worker = rt::new_worker(); // Parses and reads the input file let file = lang::read_file(code)?; // Converts the HVM "file" to a Rulebook let book = rb::gen_rulebook(&file); // Builds dynamic functions let functions = build_runtime_functions(&book); // Allocates the main term let host = alloc_term(&mut worker, &book, call); // Normalizes it let init = Instant::now(); rt::normal(&mut worker, host, &functions, Some(&book.id_to_name), debug); let time = init.elapsed().as_millis() as u64; // Reads it back to a Lambolt string let book = Some(book); let code = match rd::as_term(&worker, &book, host) { Ok(x) => format!("{}", x), Err(..) => rd::as_code(&worker, &book, host), }; // Returns the normal form and the gas cost Ok((code, worker.cost, worker.size, time)) }
34.426786
129
0.542767
e6491697c1586c37cc6b6757f2516561f71f9f24
15,865
//! Command parsers. //! //! You can either create an `enum` with derived [`BotCommands`], containing //! commands of your bot, or use functions, which split input text into a string //! command with its arguments. //! //! # Using BotCommands //! //! ``` //! # #[cfg(feature = "macros")] { //! use teloxide::utils::command::BotCommands; //! //! type UnitOfTime = u8; //! //! #[derive(BotCommands, PartialEq, Debug)] //! #[command(rename = "lowercase", parse_with = "split")] //! enum AdminCommand { //! Mute(UnitOfTime, char), //! Ban(UnitOfTime, char), //! } //! //! let command = AdminCommand::parse("/ban 5 h", "bot_name").unwrap(); //! assert_eq!(command, AdminCommand::Ban(5, 'h')); //! # } //! ``` //! //! # Using parse_command //! //! ``` //! use teloxide::utils::command::parse_command; //! //! let (command, args) = parse_command("/ban@MyBotName 3 hours", "MyBotName").unwrap(); //! assert_eq!(command, "ban"); //! assert_eq!(args, vec!["3", "hours"]); //! ``` //! //! # Using parse_command_with_prefix //! //! ``` //! use teloxide::utils::command::parse_command_with_prefix; //! //! let text = "!ban 3 hours"; //! let (command, args) = parse_command_with_prefix("!", text, "").unwrap(); //! assert_eq!(command, "ban"); //! assert_eq!(args, vec!["3", "hours"]); //! ``` //! //! See [examples/admin_bot] as a more complicated examples. //! //! [examples/admin_bot]: https://github.com/teloxide/teloxide/blob/master/examples/admin_bot/ use core::fmt; use std::{ error::Error, fmt::{Display, Formatter, Write}, }; use std::marker::PhantomData; use teloxide_core::types::{BotCommand, Me}; #[cfg(feature = "macros")] pub use teloxide_macros::BotCommands; /// An enumeration of bot's commands. /// /// # Example /// ``` /// # #[cfg(feature = "macros")] { /// use teloxide::utils::command::BotCommands; /// /// type UnitOfTime = u8; /// /// #[derive(BotCommands, PartialEq, Debug)] /// #[command(rename = "lowercase", parse_with = "split")] /// enum AdminCommand { /// Mute(UnitOfTime, char), /// Ban(UnitOfTime, char), /// } /// /// let command = AdminCommand::parse("/ban 5 h", "bot_name").unwrap(); /// assert_eq!(command, AdminCommand::Ban(5, 'h')); /// # } /// ``` /// /// # Enum attributes /// 1. `#[command(rename = "rule")]` /// Rename all commands by `rule`. If you will not use this attribute, commands /// will be parsed by their original names. Allowed rules are `lowercase`, /// `UPPERCASE`, `PascalCase`, `camelCase`, `snake_case`, /// `SCREAMING_SNAKE_CASE`, `kebab-case`, and `SCREAMING-KEBAB-CASE`. /// /// 2. `#[command(prefix = "prefix")]` /// Change a prefix for all commands (the default is `/`). /// /// 3. `#[command(description = "description")]` /// Add a sumary description of commands before all commands. /// /// 4. `#[command(parse_with = "parser")]` /// Change the parser of arguments. Possible values: /// - `default` - the same as the unspecified parser. It only puts all text /// after the first space into the first argument, which must implement /// [`FromStr`]. /// /// ## Example /// ``` /// # #[cfg(feature = "macros")] { /// use teloxide::utils::command::BotCommands; /// /// #[derive(BotCommands, PartialEq, Debug)] /// #[command(rename = "lowercase")] /// enum Command { /// Text(String), /// } /// /// let command = Command::parse("/text hello my dear friend!", "").unwrap(); /// assert_eq!(command, Command::Text("hello my dear friend!".to_string())); /// # } /// ``` /// /// - `split` - separates a messsage by a given separator (the default is the /// space character) and parses each part into the corresponding arguments, /// which must implement [`FromStr`]. /// /// ## Example /// ``` /// # #[cfg(feature = "macros")] { /// use teloxide::utils::command::BotCommands; /// /// #[derive(BotCommands, PartialEq, Debug)] /// #[command(rename = "lowercase", parse_with = "split")] /// enum Command { /// Nums(u8, u16, i32), /// } /// /// let command = Command::parse("/nums 1 32 -5", "").unwrap(); /// assert_eq!(command, Command::Nums(1, 32, -5)); /// # } /// ``` /// /// 5. `#[command(separator = "sep")]` /// Specify separator used by the `split` parser. It will be ignored when /// accompanied by another type of parsers. /// /// ## Example /// ``` /// # #[cfg(feature = "macros")] { /// use teloxide::utils::command::BotCommands; /// /// #[derive(BotCommands, PartialEq, Debug)] /// #[command(rename = "lowercase", parse_with = "split", separator = "|")] /// enum Command { /// Nums(u8, u16, i32), /// } /// /// let command = Command::parse("/nums 1|32|5", "").unwrap(); /// assert_eq!(command, Command::Nums(1, 32, 5)); /// # } /// ``` /// /// # Variant attributes /// All variant attributes override the corresponding `enum` attributes. /// /// 1. `#[command(rename = "rule")]` /// Rename one command by a rule. Allowed rules are `lowercase`, `%some_name%`, /// where `%some_name%` is any string, a new name. /// /// 2. `#[command(description = "description")]` /// Give your command a description. Write `"off"` for `"description"` to hide a /// command. /// /// 3. `#[command(parse_with = "parser")]` /// One more option is available for variants. /// - `custom_parser` - your own parser of the signature `fn(String) -> /// Result<Tuple, ParseError>`, where `Tuple` corresponds to the variant's /// arguments. /// /// ## Example /// ``` /// # #[cfg(feature = "macros")] { /// use teloxide::utils::command::{BotCommands, ParseError}; /// /// fn accept_two_digits(input: String) -> Result<(u8,), ParseError> { /// match input.len() { /// 2 => { /// let num = input.parse::<u8>().map_err(|e| ParseError::IncorrectFormat(e.into()))?; /// Ok((num,)) /// } /// len => Err(ParseError::Custom(format!("Only 2 digits allowed, not {}", len).into())), /// } /// } /// /// #[derive(BotCommands, PartialEq, Debug)] /// #[command(rename = "lowercase")] /// enum Command { /// #[command(parse_with = "accept_two_digits")] /// Num(u8), /// } /// /// let command = Command::parse("/num 12", "").unwrap(); /// assert_eq!(command, Command::Num(12)); /// let command = Command::parse("/num 333", ""); /// assert!(command.is_err()); /// # } /// ``` /// /// 4. `#[command(prefix = "prefix")]` /// 5. `#[command(separator = "sep")]` /// /// These attributes just override the corresponding `enum` attributes for a /// specific variant. /// /// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html /// [`BotCommands`]: crate::utils::command::BotCommands pub trait BotCommands: Sized { /// Parses a command. /// /// `bot_username` is required to parse commands like /// `/cmd@username_of_the_bot`. fn parse<N>(s: &str, bot_username: N) -> Result<Self, ParseError> where N: Into<String>; /// Returns descriptions of the commands suitable to be shown to the user /// (for example when `/help` command is used). fn descriptions() -> CommandDescriptions<'static>; /// Returns a vector of [`BotCommand`] that can be used with /// [`set_my_commands`]. /// /// [`BotCommand`]: crate::types::BotCommand /// [`set_my_commands`]: crate::requests::Requester::set_my_commands fn bot_commands() -> Vec<BotCommand>; /// Returns `PhantomData<Self>` that is used as a param of [`commands_repl`] /// /// [`commands_repl`]: (crate::repls2::commands_repl) fn ty() -> PhantomData<Self> { PhantomData } } pub type PrefixedBotCommand = String; pub type BotName = String; /// Errors returned from [`BotCommands::parse`]. /// /// [`BotCommands::parse`]: BotCommands::parse #[derive(Debug)] pub enum ParseError { TooFewArguments { expected: usize, found: usize, message: String, }, TooManyArguments { expected: usize, found: usize, message: String, }, /// Redirected from [`FromStr::from_str`]. /// /// [`FromStr::from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str IncorrectFormat(Box<dyn Error + Send + Sync + 'static>), UnknownCommand(PrefixedBotCommand), WrongBotName(BotName), /// A custom error which you can return from your custom parser. Custom(Box<dyn Error + Send + Sync + 'static>), } /// Command descriptions that can be shown to the user (e.g. as a part of /// `/help` message) /// /// Most of the time you don't need to create this struct yourself as it's /// returned from [`BotCommands::descriptions`]. #[derive(Debug, Clone)] pub struct CommandDescriptions<'a> { global_description: Option<&'a str>, descriptions: &'a [CommandDescription<'a>], bot_username: Option<&'a str>, } /// Description of a particular command, used in [`CommandDescriptions`]. #[derive(Debug, Clone)] pub struct CommandDescription<'a> { /// Prefix of the command, usually `/`. pub prefix: &'a str, /// The command itself, e.g. `start`. pub command: &'a str, /// Human-readable description of the command. pub description: &'a str, } impl<'a> CommandDescriptions<'a> { /// Creates new [`CommandDescriptions`] from a list of command descriptions. pub fn new(descriptions: &'a [CommandDescription<'a>]) -> Self { Self { global_description: None, descriptions, bot_username: None } } /// Sets the global description of these commands. pub fn global_description(self, global_description: &'a str) -> Self { Self { global_description: Some(global_description), ..self } } /// Sets the username of the bot. /// /// After this method is called, returned instance of /// [`CommandDescriptions`] will append `@bot_username` to all commands. /// This is useful in groups, to disambiguate commands for different bots. /// /// ## Examples /// /// ``` /// use teloxide::utils::command::{CommandDescription, CommandDescriptions}; /// /// let descriptions = CommandDescriptions::new(&[ /// CommandDescription { prefix: "/", command: "start", description: "start this bot" }, /// CommandDescription { prefix: "/", command: "help", description: "show this message" }, /// ]); /// /// assert_eq!(descriptions.to_string(), "/start — start this bot\n/help — show this message"); /// assert_eq!( /// descriptions.username("username_of_the_bot").to_string(), /// "/start@username_of_the_bot — start this bot\n/help@username_of_the_bot — show this \ /// message" /// ); /// ``` pub fn username(self, bot_username: &'a str) -> Self { Self { bot_username: Some(bot_username), ..self } } /// Sets the username of the bot. /// /// This is the same as [`username`], but uses value returned from `get_me` /// method to get the username. /// /// [`username`]: self::CommandDescriptions::username pub fn username_from_me(self, me: &'a Me) -> CommandDescriptions<'a> { self.username(me.user.username.as_deref().expect("Bots must have usernames")) } } /// Parses a string into a command with args. /// /// This function is just a shortcut for calling [`parse_command_with_prefix`] /// with the default prefix `/`. /// /// ## Example /// ``` /// use teloxide::utils::command::parse_command; /// /// let text = "/mute@my_admin_bot 5 hours"; /// let (command, args) = parse_command(text, "my_admin_bot").unwrap(); /// assert_eq!(command, "mute"); /// assert_eq!(args, vec!["5", "hours"]); /// ``` /// /// If the name of a bot does not match, it will return `None`: /// ``` /// use teloxide::utils::command::parse_command; /// /// let result = parse_command("/ban@MyNameBot1 3 hours", "MyNameBot2"); /// assert!(result.is_none()); /// ``` /// /// [`parse_command_with_prefix`]: /// crate::utils::command::parse_command_with_prefix pub fn parse_command<N>(text: &str, bot_name: N) -> Option<(&str, Vec<&str>)> where N: AsRef<str>, { parse_command_with_prefix("/", text, bot_name) } /// Parses a string into a command with args (custom prefix). /// /// `prefix`: symbols, which denote start of a command. /// /// ## Example /// ``` /// use teloxide::utils::command::parse_command_with_prefix; /// /// let text = "!mute 5 hours"; /// let (command, args) = parse_command_with_prefix("!", text, "").unwrap(); /// assert_eq!(command, "mute"); /// assert_eq!(args, vec!["5", "hours"]); /// ``` /// /// If the name of a bot does not match, it will return `None`: /// ``` /// use teloxide::utils::command::parse_command_with_prefix; /// /// let result = parse_command_with_prefix("!", "!ban@MyNameBot1 3 hours", "MyNameBot2"); /// assert!(result.is_none()); /// ``` pub fn parse_command_with_prefix<'a, N>( prefix: &str, text: &'a str, bot_name: N, ) -> Option<(&'a str, Vec<&'a str>)> where N: AsRef<str>, { if !text.starts_with(prefix) { return None; } let mut words = text.split_whitespace(); let mut splited = words.next()?[prefix.len()..].split('@'); let command = splited.next()?; let bot = splited.next(); match bot { Some(name) if name.eq_ignore_ascii_case(bot_name.as_ref()) => {} None => {} _ => return None, } Some((command, words.collect())) } impl Display for ParseError { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { match self { ParseError::TooFewArguments { expected, found, message } => write!( f, "Too few arguments (expected {}, found {}, message = '{}')", expected, found, message ), ParseError::TooManyArguments { expected, found, message } => write!( f, "Too many arguments (expected {}, found {}, message = '{}')", expected, found, message ), ParseError::IncorrectFormat(e) => write!(f, "Incorrect format of command args: {}", e), ParseError::UnknownCommand(e) => write!(f, "Unknown command: {}", e), ParseError::WrongBotName(n) => write!(f, "Wrong bot name: {}", n), ParseError::Custom(e) => write!(f, "{}", e), } } } impl std::error::Error for ParseError {} impl Display for CommandDescriptions<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(global_description) = self.global_description { f.write_str(global_description)?; f.write_str("\n\n")?; } let mut write = |&CommandDescription { prefix, command, description }, nls| { if nls { f.write_char('\n')?; } f.write_str(prefix)?; f.write_str(command)?; if let Some(username) = self.bot_username { f.write_char('@')?; f.write_str(username)?; } if !description.is_empty() { f.write_str(" — ")?; f.write_str(description)?; } fmt::Result::Ok(()) }; if let Some(descr) = self.descriptions.first() { write(descr, false)?; for descr in &self.descriptions[1..] { write(descr, true)?; } } Ok(()) } } // The rest of tests are integrational due to problems with macro expansion in // unit tests. #[cfg(test)] mod tests { use super::*; #[test] fn parse_command_with_args_() { let data = "/command arg1 arg2"; let expected = Some(("command", vec!["arg1", "arg2"])); let actual = parse_command(data, ""); assert_eq!(actual, expected) } #[test] fn parse_command_with_args_without_args() { let data = "/command"; let expected = Some(("command", vec![])); let actual = parse_command(data, ""); assert_eq!(actual, expected) } }
31.478175
101
0.595147
f5364fc83752d4cf0eebe982b7c8086b7bd8e63a
410
use auxiliary_macros::add_pin_attr; use pin_project::pin_project; use std::marker::PhantomPinned; #[pin_project] #[add_pin_attr(struct)] //~ ERROR duplicate #[pin] attribute struct Foo { #[pin] field: PhantomPinned, } #[add_pin_attr(struct)] //~ ERROR #[pin] attribute may only be used on fields of structs or variants #[pin_project] struct Bar { #[pin] field: PhantomPinned, } fn main() {}
20.5
100
0.702439
f71f4d56aebd87daf24c0a09bed1d6e45569850a
3,524
mod builder; mod compression_method; mod content_type; pub use self::{ builder::Builder, compression_method::CompressionMethod, content_type::ContentType, }; use std::{ borrow::Cow, io::{self, Read}, mem, }; use bzip2::read::BzDecoder; use flate2::read::GzDecoder; use xz2::read::XzDecoder; use crate::{ num::{itf8, Itf8}, rans::rans_decode, }; // § 9 End of file container (2020-06-22) const EOF_DATA: [u8; 6] = [0x01, 0x00, 0x01, 0x00, 0x01, 0x00]; const EOF_CRC32: u32 = 0x4b_01_63_ee; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Block { compression_method: CompressionMethod, content_type: ContentType, content_id: Itf8, uncompressed_len: Itf8, data: Vec<u8>, crc32: u32, } #[allow(clippy::len_without_is_empty)] impl Block { pub fn builder() -> Builder { Builder::default() } /// Creates a block used in the EOF container. pub fn eof() -> Self { Self::builder() .set_content_type(ContentType::CompressionHeader) .set_uncompressed_len(EOF_DATA.len() as Itf8) .set_data(EOF_DATA.to_vec()) .set_crc32(EOF_CRC32) .build() } pub fn compression_method(&self) -> CompressionMethod { self.compression_method } pub fn content_type(&self) -> ContentType { self.content_type } pub fn content_id(&self) -> Itf8 { self.content_id } pub fn uncompressed_len(&self) -> Itf8 { self.uncompressed_len } pub fn data(&self) -> &[u8] { &self.data } pub fn decompressed_data(&self) -> io::Result<Cow<'_, [u8]>> { match self.compression_method { CompressionMethod::None => Ok(Cow::from(self.data())), CompressionMethod::Gzip => { let mut reader = GzDecoder::new(self.data()); let mut buf = Vec::with_capacity(self.uncompressed_len as usize); reader.read_to_end(&mut buf)?; Ok(Cow::from(buf)) } CompressionMethod::Bzip2 => { let mut reader = BzDecoder::new(self.data()); let mut buf = Vec::with_capacity(self.uncompressed_len as usize); reader.read_to_end(&mut buf)?; Ok(Cow::from(buf)) } CompressionMethod::Lzma => { let mut reader = XzDecoder::new(self.data()); let mut buf = Vec::with_capacity(self.uncompressed_len as usize); reader.read_to_end(&mut buf)?; Ok(Cow::from(buf)) } CompressionMethod::Rans => { let mut buf = self.data(); rans_decode(&mut buf).map(Cow::from) } } } pub fn len(&self) -> usize { // method mem::size_of::<u8>() // block content type ID + mem::size_of::<u8>() + itf8::size_of(self.content_id()) + itf8::size_of(self.data.len() as Itf8) + itf8::size_of(self.uncompressed_len()) + self.data.len() // crc32 + mem::size_of::<u32>() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_len() { let data = b"noodles".to_vec(); let block = Block::builder() .set_content_type(ContentType::ExternalData) .set_uncompressed_len(data.len() as Itf8) .set_data(data) .build(); assert_eq!(block.len(), 16); } }
26.496241
87
0.548524
715b9a3bd269233706cc2ab6f1480b7800e91e3c
46,682
use std::char; use std::collections::{ BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque, }; use std::env; use std::ffi::OsString; use std::hash::{BuildHasher, Hash}; use std::iter::{empty, once}; use std::net::{ IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, }; use std::num::Wrapping; use std::num::{ NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, }; use std::ops::{ Bound, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, }; use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use rand::seq::SliceRandom; use rand::{self, Rng, RngCore}; /// `Gen` wraps a `rand::RngCore` with parameters to control the range of /// random values. /// /// A value with type satisfying the `Gen` trait can be constructed with the /// `gen` function in this crate. pub trait Gen: RngCore { /// Controls the range of values of certain types created with this Gen. /// For an explaination of which types behave how, see `Arbitrary` fn size(&self) -> usize; } /// StdGen is the default implementation of `Gen`. /// /// Values of type `StdGen` can be created with the `gen` function in this /// crate. pub struct StdGen<R> { rng: R, size: usize, } impl<R: RngCore> StdGen<R> { /// Returns a `StdGen` with the given configuration using any random number /// generator. /// /// The `size` parameter controls the size of random values generated. For /// example, it specifies the maximum length of a randomly generated /// vector, but not the maximum magnitude of a randomly generated number. /// For further explaination, see Arbitrary. pub fn new(rng: R, size: usize) -> StdGen<R> { StdGen { rng: rng, size: size } } } impl<R: RngCore> RngCore for StdGen<R> { fn next_u32(&mut self) -> u32 { self.rng.next_u32() } // some RNGs implement these more efficiently than the default, so // we might as well defer to them. fn next_u64(&mut self) -> u64 { self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.rng.fill_bytes(dest) } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { self.rng.try_fill_bytes(dest) } } impl<R: RngCore> Gen for StdGen<R> { fn size(&self) -> usize { self.size } } /// StdThreadGen is an RNG in thread-local memory. /// /// This is the default RNG used by quickcheck. pub struct StdThreadGen(StdGen<rand::rngs::ThreadRng>); impl StdThreadGen { /// Returns a new thread-local RNG. /// /// The `size` parameter controls the size of random values generated. For /// example, it specifies the maximum length of a randomly generated /// vector, but not the maximum magnitude of a randomly generated number. /// For further explaination, see Arbitrary. pub fn new(size: usize) -> StdThreadGen { StdThreadGen(StdGen { rng: rand::thread_rng(), size: size }) } } impl RngCore for StdThreadGen { fn next_u32(&mut self) -> u32 { self.0.next_u32() } // some RNGs implement these more efficiently than the default, so // we might as well defer to them. fn next_u64(&mut self) -> u64 { self.0.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.0.fill_bytes(dest) } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { self.0.try_fill_bytes(dest) } } impl Gen for StdThreadGen { fn size(&self) -> usize { self.0.size } } /// Creates a shrinker with zero elements. pub fn empty_shrinker<A: 'static>() -> Box<dyn Iterator<Item = A>> { Box::new(empty()) } /// Creates a shrinker with a single element. pub fn single_shrinker<A: 'static>(value: A) -> Box<dyn Iterator<Item = A>> { Box::new(once(value)) } /// `Arbitrary` describes types whose values can be randomly generated and /// shrunk. /// /// Aside from shrinking, `Arbitrary` is different from the `std::Rand` trait /// in that it respects `Gen::size()` for certain types. For example, /// `Vec::arbitrary()` respects `Gen::size()` to decide the maximum `len()` /// of the vector. This behavior is necessary due to practical speed and size /// limitations. Conversely, `i32::arbitrary()` ignores `size()`, as all `i32` /// values require `O(1)` memory and operations between `i32`s require `O(1)` /// time (with the exception of exponentiation). /// /// As of now, all types that implement `Arbitrary` must also implement /// `Clone`. (I'm not sure if this is a permanent restriction.) /// /// They must also be sendable and static since every test is run in its own /// thread using `thread::Builder::spawn`, which requires the `Send + 'static` /// bounds. pub trait Arbitrary: Clone + Send + 'static { fn arbitrary<G: Gen>(g: &mut G) -> Self; fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { empty_shrinker() } } impl Arbitrary for () { fn arbitrary<G: Gen>(_: &mut G) -> () { () } } impl Arbitrary for bool { fn arbitrary<G: Gen>(g: &mut G) -> bool { g.gen() } fn shrink(&self) -> Box<dyn Iterator<Item = bool>> { if *self { single_shrinker(false) } else { empty_shrinker() } } } impl<A: Arbitrary> Arbitrary for Option<A> { fn arbitrary<G: Gen>(g: &mut G) -> Option<A> { if g.gen() { None } else { Some(Arbitrary::arbitrary(g)) } } fn shrink(&self) -> Box<dyn Iterator<Item = Option<A>>> { match *self { None => empty_shrinker(), Some(ref x) => { let chain = single_shrinker(None).chain(x.shrink().map(Some)); Box::new(chain) } } } } impl<A: Arbitrary, B: Arbitrary> Arbitrary for Result<A, B> { fn arbitrary<G: Gen>(g: &mut G) -> Result<A, B> { if g.gen() { Ok(Arbitrary::arbitrary(g)) } else { Err(Arbitrary::arbitrary(g)) } } fn shrink(&self) -> Box<dyn Iterator<Item = Result<A, B>>> { match *self { Ok(ref x) => { let xs = x.shrink(); let tagged = xs.map(Ok); Box::new(tagged) } Err(ref x) => { let xs = x.shrink(); let tagged = xs.map(Err); Box::new(tagged) } } } } macro_rules! impl_arb_for_single_tuple { ($(($type_param:ident, $tuple_index:tt),)*) => { impl<$($type_param),*> Arbitrary for ($($type_param,)*) where $($type_param: Arbitrary,)* { fn arbitrary<GEN: Gen>(g: &mut GEN) -> ($($type_param,)*) { ( $( $type_param::arbitrary(g), )* ) } fn shrink(&self) -> Box<dyn Iterator<Item=($($type_param,)*)>> { let iter = ::std::iter::empty(); $( let cloned = self.clone(); let iter = iter.chain(self.$tuple_index.shrink().map(move |shr_value| { let mut result = cloned.clone(); result.$tuple_index = shr_value; result })); )* Box::new(iter) } } }; } macro_rules! impl_arb_for_tuples { (@internal [$($acc:tt,)*]) => { }; (@internal [$($acc:tt,)*] ($type_param:ident, $tuple_index:tt), $($rest:tt,)*) => { impl_arb_for_single_tuple!($($acc,)* ($type_param, $tuple_index),); impl_arb_for_tuples!(@internal [$($acc,)* ($type_param, $tuple_index),] $($rest,)*); }; ($(($type_param:ident, $tuple_index:tt),)*) => { impl_arb_for_tuples!(@internal [] $(($type_param, $tuple_index),)*); }; } impl_arb_for_tuples! { (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), } impl<A: Arbitrary> Arbitrary for Vec<A> { fn arbitrary<G: Gen>(g: &mut G) -> Vec<A> { let size = { let s = g.size(); g.gen_range(0, s) }; (0..size).map(|_| Arbitrary::arbitrary(g)).collect() } fn shrink(&self) -> Box<dyn Iterator<Item = Vec<A>>> { VecShrinker::new(self.clone()) } } ///Iterator which returns successive attempts to shrink the vector `seed` struct VecShrinker<A> { seed: Vec<A>, /// How much which is removed when trying with smaller vectors size: usize, /// The end of the removed elements offset: usize, /// The shrinker for the element at `offset` once shrinking of individual /// elements are attempted element_shrinker: Box<dyn Iterator<Item = A>>, } impl<A: Arbitrary> VecShrinker<A> { fn new(seed: Vec<A>) -> Box<dyn Iterator<Item = Vec<A>>> { let es = match seed.get(0) { Some(e) => e.shrink(), None => return empty_shrinker(), }; let size = seed.len(); Box::new(VecShrinker { seed: seed, size: size, offset: size, element_shrinker: es, }) } /// Returns the next shrunk element if any, `offset` points to the index /// after the returned element after the function returns fn next_element(&mut self) -> Option<A> { loop { match self.element_shrinker.next() { Some(e) => return Some(e), None => match self.seed.get(self.offset) { Some(e) => { self.element_shrinker = e.shrink(); self.offset += 1; } None => return None, }, } } } } impl<A> Iterator for VecShrinker<A> where A: Arbitrary, { type Item = Vec<A>; fn next(&mut self) -> Option<Vec<A>> { // Try with an empty vector first if self.size == self.seed.len() { self.size /= 2; self.offset = self.size; return Some(vec![]); } if self.size != 0 { // Generate a smaller vector by removing the elements between // (offset - size) and offset let xs1 = self.seed[..(self.offset - self.size)] .iter() .chain(&self.seed[self.offset..]) .cloned() .collect(); self.offset += self.size; // Try to reduce the amount removed from the vector once all // previous sizes tried if self.offset > self.seed.len() { self.size /= 2; self.offset = self.size; } Some(xs1) } else { // A smaller vector did not work so try to shrink each element of // the vector instead Reuse `offset` as the index determining which // element to shrink // The first element shrinker is already created so skip the first // offset (self.offset == 0 only on first entry to this part of the // iterator) if self.offset == 0 { self.offset = 1 } match self.next_element() { Some(e) => Some( self.seed[..self.offset - 1] .iter() .cloned() .chain(Some(e).into_iter()) .chain(self.seed[self.offset..].iter().cloned()) .collect(), ), None => None, } } } } impl<K: Arbitrary + Ord, V: Arbitrary> Arbitrary for BTreeMap<K, V> { fn arbitrary<G: Gen>(g: &mut G) -> BTreeMap<K, V> { let vec: Vec<(K, V)> = Arbitrary::arbitrary(g); vec.into_iter().collect() } fn shrink(&self) -> Box<dyn Iterator<Item = BTreeMap<K, V>>> { let vec: Vec<(K, V)> = self.clone().into_iter().collect(); Box::new( vec.shrink().map(|v| v.into_iter().collect::<BTreeMap<K, V>>()), ) } } impl< K: Arbitrary + Eq + Hash, V: Arbitrary, S: BuildHasher + Default + Clone + Send + 'static, > Arbitrary for HashMap<K, V, S> { fn arbitrary<G: Gen>(g: &mut G) -> Self { let vec: Vec<(K, V)> = Arbitrary::arbitrary(g); vec.into_iter().collect() } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let vec: Vec<(K, V)> = self.clone().into_iter().collect(); Box::new(vec.shrink().map(|v| v.into_iter().collect::<Self>())) } } impl<T: Arbitrary + Ord> Arbitrary for BTreeSet<T> { fn arbitrary<G: Gen>(g: &mut G) -> BTreeSet<T> { let vec: Vec<T> = Arbitrary::arbitrary(g); vec.into_iter().collect() } fn shrink(&self) -> Box<dyn Iterator<Item = BTreeSet<T>>> { let vec: Vec<T> = self.clone().into_iter().collect(); Box::new(vec.shrink().map(|v| v.into_iter().collect::<BTreeSet<T>>())) } } impl<T: Arbitrary + Ord> Arbitrary for BinaryHeap<T> { fn arbitrary<G: Gen>(g: &mut G) -> BinaryHeap<T> { let vec: Vec<T> = Arbitrary::arbitrary(g); vec.into_iter().collect() } fn shrink(&self) -> Box<dyn Iterator<Item = BinaryHeap<T>>> { let vec: Vec<T> = self.clone().into_iter().collect(); Box::new( vec.shrink().map(|v| v.into_iter().collect::<BinaryHeap<T>>()), ) } } impl< T: Arbitrary + Eq + Hash, S: BuildHasher + Default + Clone + Send + 'static, > Arbitrary for HashSet<T, S> { fn arbitrary<G: Gen>(g: &mut G) -> Self { let vec: Vec<T> = Arbitrary::arbitrary(g); vec.into_iter().collect() } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let vec: Vec<T> = self.clone().into_iter().collect(); Box::new(vec.shrink().map(|v| v.into_iter().collect::<Self>())) } } impl<T: Arbitrary> Arbitrary for LinkedList<T> { fn arbitrary<G: Gen>(g: &mut G) -> LinkedList<T> { let vec: Vec<T> = Arbitrary::arbitrary(g); vec.into_iter().collect() } fn shrink(&self) -> Box<dyn Iterator<Item = LinkedList<T>>> { let vec: Vec<T> = self.clone().into_iter().collect(); Box::new( vec.shrink().map(|v| v.into_iter().collect::<LinkedList<T>>()), ) } } impl<T: Arbitrary> Arbitrary for VecDeque<T> { fn arbitrary<G: Gen>(g: &mut G) -> VecDeque<T> { let vec: Vec<T> = Arbitrary::arbitrary(g); vec.into_iter().collect() } fn shrink(&self) -> Box<dyn Iterator<Item = VecDeque<T>>> { let vec: Vec<T> = self.clone().into_iter().collect(); Box::new(vec.shrink().map(|v| v.into_iter().collect::<VecDeque<T>>())) } } impl Arbitrary for IpAddr { fn arbitrary<G: Gen>(g: &mut G) -> IpAddr { let ipv4: bool = g.gen(); if ipv4 { IpAddr::V4(Arbitrary::arbitrary(g)) } else { IpAddr::V6(Arbitrary::arbitrary(g)) } } } impl Arbitrary for Ipv4Addr { fn arbitrary<G: Gen>(g: &mut G) -> Ipv4Addr { Ipv4Addr::new(g.gen(), g.gen(), g.gen(), g.gen()) } } impl Arbitrary for Ipv6Addr { fn arbitrary<G: Gen>(g: &mut G) -> Ipv6Addr { Ipv6Addr::new( g.gen(), g.gen(), g.gen(), g.gen(), g.gen(), g.gen(), g.gen(), g.gen(), ) } } impl Arbitrary for SocketAddr { fn arbitrary<G: Gen>(g: &mut G) -> SocketAddr { SocketAddr::new(Arbitrary::arbitrary(g), g.gen()) } } impl Arbitrary for SocketAddrV4 { fn arbitrary<G: Gen>(g: &mut G) -> SocketAddrV4 { SocketAddrV4::new(Arbitrary::arbitrary(g), g.gen()) } } impl Arbitrary for SocketAddrV6 { fn arbitrary<G: Gen>(g: &mut G) -> SocketAddrV6 { SocketAddrV6::new(Arbitrary::arbitrary(g), g.gen(), g.gen(), g.gen()) } } impl Arbitrary for PathBuf { fn arbitrary<G: Gen>(g: &mut G) -> PathBuf { // use some real directories as guesses, so we may end up with // actual working directories in case that is relevant. let here = env::current_dir().unwrap_or(PathBuf::from("/test/directory")); let temp = env::temp_dir(); #[allow(deprecated)] let home = env::home_dir().unwrap_or(PathBuf::from("/home/user")); let choices = &[ here, temp, home, PathBuf::from("."), PathBuf::from(".."), PathBuf::from("../../.."), PathBuf::new(), ]; let mut p = choices.choose(g).unwrap().clone(); p.extend(Vec::<OsString>::arbitrary(g).iter()); p } fn shrink(&self) -> Box<dyn Iterator<Item = PathBuf>> { let mut shrunk = vec![]; let mut popped = self.clone(); if popped.pop() { shrunk.push(popped); } // Iterating over a Path performs a small amount of normalization. let normalized = self.iter().collect::<PathBuf>(); if normalized.as_os_str() != self.as_os_str() { shrunk.push(normalized); } // Add the canonicalized variant only if canonicalizing the path // actually does something, making it (hopefully) smaller. Also, ignore // canonicalization if canonicalization errors. if let Ok(canonicalized) = self.canonicalize() { if canonicalized.as_os_str() != self.as_os_str() { shrunk.push(canonicalized); } } Box::new(shrunk.into_iter()) } } impl Arbitrary for OsString { fn arbitrary<G: Gen>(g: &mut G) -> OsString { OsString::from(String::arbitrary(g)) } fn shrink(&self) -> Box<dyn Iterator<Item = OsString>> { let mystring: String = self.clone().into_string().unwrap(); Box::new(mystring.shrink().map(|s| OsString::from(s))) } } impl Arbitrary for String { fn arbitrary<G: Gen>(g: &mut G) -> String { let size = { let s = g.size(); g.gen_range(0, s) }; let mut s = String::with_capacity(size); for _ in 0..size { s.push(char::arbitrary(g)); } s } fn shrink(&self) -> Box<dyn Iterator<Item = String>> { // Shrink a string by shrinking a vector of its characters. let chars: Vec<char> = self.chars().collect(); Box::new(chars.shrink().map(|x| x.into_iter().collect::<String>())) } } impl Arbitrary for char { fn arbitrary<G: Gen>(g: &mut G) -> char { let mode = g.gen_range(0, 100); match mode { 0..=49 => { // ASCII + some control characters g.gen_range(0, 0xB0) as u8 as char } 50..=59 => { // Unicode BMP characters loop { if let Some(x) = char::from_u32(g.gen_range(0, 0x10000)) { return x; } // ignore surrogate pairs } } 60..=84 => { // Characters often used in programming languages [ ' ', ' ', ' ', '\t', '\n', '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '=', '+', '[', ']', '{', '}', ':', ';', '\'', '"', '\\', '|', ',', '<', '>', '.', '/', '?', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ] .choose(g) .unwrap() .to_owned() } 85..=89 => { // Tricky Unicode, part 1 [ '\u{0149}', // a deprecated character '\u{fff0}', // some of "Other, format" category: '\u{fff1}', '\u{fff2}', '\u{fff3}', '\u{fff4}', '\u{fff5}', '\u{fff6}', '\u{fff7}', '\u{fff8}', '\u{fff9}', '\u{fffA}', '\u{fffB}', '\u{fffC}', '\u{fffD}', '\u{fffE}', '\u{fffF}', '\u{0600}', '\u{0601}', '\u{0602}', '\u{0603}', '\u{0604}', '\u{0605}', '\u{061C}', '\u{06DD}', '\u{070F}', '\u{180E}', '\u{110BD}', '\u{1D173}', '\u{e0001}', // tag '\u{e0020}', // tag space '\u{e000}', '\u{e001}', '\u{ef8ff}', // private use '\u{f0000}', '\u{ffffd}', '\u{ffffe}', '\u{fffff}', '\u{100000}', '\u{10FFFD}', '\u{10FFFE}', '\u{10FFFF}', // "Other, surrogate" characters are so that very special // that they are not even allowed in safe Rust, //so omitted here '\u{3000}', // ideographic space '\u{1680}', // other space characters are already covered by two next // branches ] .choose(g) .unwrap() .to_owned() } 90..=94 => { // Tricky unicode, part 2 char::from_u32(g.gen_range(0x2000, 0x2070)).unwrap() } 95..=99 => { // Completely arbitrary characters g.gen() } _ => unreachable!(), } } fn shrink(&self) -> Box<dyn Iterator<Item = char>> { Box::new((*self as u32).shrink().filter_map(char::from_u32)) } } macro_rules! unsigned_shrinker { ($ty:ty) => { mod shrinker { pub struct UnsignedShrinker { x: $ty, i: $ty, } impl UnsignedShrinker { pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> { if x == 0 { super::empty_shrinker() } else { Box::new( vec![0] .into_iter() .chain(UnsignedShrinker { x: x, i: x / 2 }), ) } } } impl Iterator for UnsignedShrinker { type Item = $ty; fn next(&mut self) -> Option<$ty> { if self.x - self.i < self.x { let result = Some(self.x - self.i); self.i = self.i / 2; result } else { None } } } } }; } macro_rules! unsigned_problem_values { ($t:ty) => { [<$t>::min_value(), 1, <$t>::max_value()] }; } macro_rules! unsigned_arbitrary { ($($ty:tt),*) => { $( impl Arbitrary for $ty { fn arbitrary<G: Gen>(g: &mut G) -> $ty { match g.gen_range(0,10) { 0 => { *unsigned_problem_values!($ty).choose(g).unwrap() }, _ => g.gen() } } fn shrink(&self) -> Box<dyn Iterator<Item=$ty>> { unsigned_shrinker!($ty); shrinker::UnsignedShrinker::new(*self) } } )* } } unsigned_arbitrary! { usize, u8, u16, u32, u64, u128 } macro_rules! signed_shrinker { ($ty:ty) => { mod shrinker { pub struct SignedShrinker { x: $ty, i: $ty, } impl SignedShrinker { pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> { if x == 0 { super::empty_shrinker() } else { let shrinker = SignedShrinker { x: x, i: x / 2 }; let mut items = vec![0]; if shrinker.i < 0 { items.push(shrinker.x.abs()); } Box::new(items.into_iter().chain(shrinker)) } } } impl Iterator for SignedShrinker { type Item = $ty; fn next(&mut self) -> Option<$ty> { if (self.x - self.i).abs() < self.x.abs() { let result = Some(self.x - self.i); self.i = self.i / 2; result } else { None } } } } }; } macro_rules! signed_problem_values { ($t:ty) => { [<$t>::min_value(), 0, <$t>::max_value()] }; } macro_rules! signed_arbitrary { ($($ty:tt),*) => { $( impl Arbitrary for $ty { fn arbitrary<G: Gen>(g: &mut G) -> $ty { match g.gen_range(0,10) { 0 => { *signed_problem_values!($ty).choose(g).unwrap() }, _ => g.gen() } } fn shrink(&self) -> Box<dyn Iterator<Item=$ty>> { signed_shrinker!($ty); shrinker::SignedShrinker::new(*self) } } )* } } signed_arbitrary! { isize, i8, i16, i32, i64, i128 } macro_rules! float_problem_values { ($path:path) => {{ // hack. see: https://github.com/rust-lang/rust/issues/48067 use $path as p; [p::NAN, p::NEG_INFINITY, p::MIN, -0., 0., p::MAX, p::INFINITY] }}; } macro_rules! float_arbitrary { ($($t:ty, $path:path, $shrinkable:ty),+) => {$( impl Arbitrary for $t { fn arbitrary<G: Gen>(g: &mut G) -> $t { match g.gen_range(0,10) { 0 => *float_problem_values!($path).choose(g).unwrap(), _ => { use $path as p; let exp = g.gen_range(0., p::MAX_EXP as i16 as $t); let mantissa = g.gen_range(1., 2.); let sign = *[-1., 1.].choose(g).unwrap(); sign * mantissa * exp.exp2() } } } fn shrink(&self) -> Box<dyn Iterator<Item = $t>> { signed_shrinker!($shrinkable); let it = shrinker::SignedShrinker::new(*self as $shrinkable); Box::new(it.map(|x| x as $t)) } } )*}; } float_arbitrary!(f32, std::f32, i32, f64, std::f64, i64); macro_rules! unsigned_non_zero_shrinker { ($ty:tt) => { mod shrinker { pub struct UnsignedNonZeroShrinker { x: $ty, i: $ty, } impl UnsignedNonZeroShrinker { pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> { debug_assert!(x > 0); if x == 1 { super::empty_shrinker() } else { Box::new( std::iter::once(1).chain( UnsignedNonZeroShrinker { x: x, i: x / 2 }, ), ) } } } impl Iterator for UnsignedNonZeroShrinker { type Item = $ty; fn next(&mut self) -> Option<$ty> { if self.x - self.i < self.x { let result = Some(self.x - self.i); self.i = self.i / 2; result } else { None } } } } }; } macro_rules! unsigned_non_zero_arbitrary { ($($ty:tt => $inner:tt),*) => { $( impl Arbitrary for $ty { fn arbitrary<G: Gen>(g: &mut G) -> $ty { #![allow(trivial_numeric_casts)] let s = g.size() as $inner; use std::cmp::{min, max}; let non_zero = g.gen_range(1, max(2, min(s, $inner::max_value()))); debug_assert!(non_zero != 0); $ty::new(non_zero).expect("non-zero value contsturction failed") } fn shrink(&self) -> Box<dyn Iterator<Item = $ty>> { unsigned_non_zero_shrinker!($inner); Box::new(shrinker::UnsignedNonZeroShrinker::new(self.get()) .map($ty::new) .map(Option::unwrap)) } } )* } } unsigned_non_zero_arbitrary! { NonZeroUsize => usize, NonZeroU8 => u8, NonZeroU16 => u16, NonZeroU32 => u32, NonZeroU64 => u64, NonZeroU128 => u128 } impl<T: Arbitrary> Arbitrary for Wrapping<T> { fn arbitrary<G: Gen>(g: &mut G) -> Wrapping<T> { Wrapping(T::arbitrary(g)) } fn shrink(&self) -> Box<dyn Iterator<Item = Wrapping<T>>> { Box::new(self.0.shrink().map(|inner| Wrapping(inner))) } } impl<T: Arbitrary> Arbitrary for Bound<T> { fn arbitrary<G: Gen>(g: &mut G) -> Bound<T> { match g.gen_range(0, 3) { 0 => Bound::Included(T::arbitrary(g)), 1 => Bound::Excluded(T::arbitrary(g)), _ => Bound::Unbounded, } } fn shrink(&self) -> Box<dyn Iterator<Item = Bound<T>>> { match *self { Bound::Included(ref x) => { Box::new(x.shrink().map(Bound::Included)) } Bound::Excluded(ref x) => { Box::new(x.shrink().map(Bound::Excluded)) } Bound::Unbounded => empty_shrinker(), } } } impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for Range<T> { fn arbitrary<G: Gen>(g: &mut G) -> Range<T> { Arbitrary::arbitrary(g)..Arbitrary::arbitrary(g) } fn shrink(&self) -> Box<dyn Iterator<Item = Range<T>>> { Box::new( (self.start.clone(), self.end.clone()).shrink().map(|(s, e)| s..e), ) } } impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for RangeInclusive<T> { fn arbitrary<G: Gen>(g: &mut G) -> RangeInclusive<T> { Arbitrary::arbitrary(g)..=Arbitrary::arbitrary(g) } fn shrink(&self) -> Box<dyn Iterator<Item = RangeInclusive<T>>> { Box::new( (self.start().clone(), self.end().clone()) .shrink() .map(|(s, e)| s..=e), ) } } impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for RangeFrom<T> { fn arbitrary<G: Gen>(g: &mut G) -> RangeFrom<T> { Arbitrary::arbitrary(g).. } fn shrink(&self) -> Box<dyn Iterator<Item = RangeFrom<T>>> { Box::new(self.start.clone().shrink().map(|start| start..)) } } impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for RangeTo<T> { fn arbitrary<G: Gen>(g: &mut G) -> RangeTo<T> { ..Arbitrary::arbitrary(g) } fn shrink(&self) -> Box<dyn Iterator<Item = RangeTo<T>>> { Box::new(self.end.clone().shrink().map(|end| ..end)) } } impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for RangeToInclusive<T> { fn arbitrary<G: Gen>(g: &mut G) -> RangeToInclusive<T> { ..=Arbitrary::arbitrary(g) } fn shrink(&self) -> Box<dyn Iterator<Item = RangeToInclusive<T>>> { Box::new(self.end.clone().shrink().map(|end| ..=end)) } } impl Arbitrary for RangeFull { fn arbitrary<G: Gen>(_: &mut G) -> RangeFull { .. } } impl Arbitrary for Duration { fn arbitrary<G: Gen>(gen: &mut G) -> Self { let seconds = gen.gen_range(0, gen.size() as u64); let nanoseconds = gen.gen_range(0, 1_000_000); Duration::new(seconds, nanoseconds) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new( (self.as_secs(), self.subsec_nanos()) .shrink() .map(|(secs, nanos)| Duration::new(secs, nanos % 1_000_000)), ) } } impl<A: Arbitrary> Arbitrary for Box<A> { fn arbitrary<G: Gen>(g: &mut G) -> Box<A> { Box::new(A::arbitrary(g)) } fn shrink(&self) -> Box<dyn Iterator<Item = Box<A>>> { Box::new((**self).shrink().map(Box::new)) } } impl<A: Arbitrary + Sync> Arbitrary for Arc<A> { fn arbitrary<G: Gen>(g: &mut G) -> Arc<A> { Arc::new(A::arbitrary(g)) } fn shrink(&self) -> Box<dyn Iterator<Item = Arc<A>>> { Box::new((**self).shrink().map(Arc::new)) } } impl Arbitrary for SystemTime { fn arbitrary<G: Gen>(gen: &mut G) -> Self { let after_epoch = bool::arbitrary(gen); let duration = Duration::arbitrary(gen); if after_epoch { UNIX_EPOCH + duration } else { UNIX_EPOCH - duration } } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let duration = match self.duration_since(UNIX_EPOCH) { Ok(duration) => duration, Err(e) => e.duration(), }; Box::new( duration .shrink() .flat_map(|d| vec![UNIX_EPOCH + d, UNIX_EPOCH - d]), ) } } #[cfg(test)] mod test { use super::Arbitrary; use super::StdGen; use rand; use std::collections::{ BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque, }; use std::fmt::Debug; use std::hash::Hash; use std::num::Wrapping; use std::path::PathBuf; #[test] fn arby_unit() { assert_eq!(arby::<()>(), ()); } macro_rules! arby_int { ( $signed:expr, $($t:ty),+) => {$( let mut arbys = (0..1_000_000).map(|_| arby::<$t>()); let mut problems = if $signed { signed_problem_values!($t).iter() } else { unsigned_problem_values!($t).iter() }; assert!(problems.all(|p| arbys.any(|arby| arby == *p)), "Arbitrary does not generate all problematic values"); let max = <$t>::max_value(); let mid = (max + <$t>::min_value()) / 2; // split full range of $t into chunks // Arbitrary must return some value in each chunk let double_chunks: $t = 9; let chunks = double_chunks * 2; // chunks must be even let lim: Box<dyn Iterator<Item=$t>> = if $signed { Box::new((0..=chunks) .map(|idx| idx - chunks / 2) .map(|x| mid + max / (chunks / 2) * x)) } else { Box::new((0..=chunks).map(|idx| max / chunks * idx)) }; let mut lim = lim.peekable(); while let (Some(low), Some(&high)) = (lim.next(), lim.peek()) { assert!(arbys.any(|arby| low <= arby && arby <= high), "Arbitrary doesn't generate numbers in {}..={}", low, high) } )*}; } #[test] fn arby_int() { arby_int!(true, i8, i16, i32, i64, isize, i128); } #[test] fn arby_uint() { arby_int!(false, u8, u16, u32, u64, usize, u128); } macro_rules! arby_float { ($($t:ty, $path:path),+) => {$({ use $path as p; let mut arbys = (0..1_000_000).map(|_| arby::<$t>()); //NaN != NaN assert!(arbys.any(|f| f.is_nan()), "Arbitrary does not generate the problematic value NaN" ); for p in float_problem_values!($path).iter().filter(|f| !f.is_nan()) { assert!(arbys.any(|arby| arby == *p), "Arbitrary does not generate the problematic value {}", p ); } // split full range of $t into chunks // Arbitrary must return some value in each chunk let double_chunks: i8 = 9; let chunks = double_chunks * 2; // chunks must be even let lim = (-double_chunks..=double_chunks) .map(|idx| <$t>::from(idx)) .map(|idx| p::MAX/(<$t>::from(chunks/2)) * idx); let mut lim = lim.peekable(); while let (Some(low), Some(&high)) = (lim.next(), lim.peek()) { assert!(arbys.any(|arby| low <= arby && arby <= high), "Arbitrary doesn't generate numbers in {:e}..={:e}", low, high) } })*}; } #[test] fn arby_float() { arby_float!(f32, std::f32, f64, std::f64); } fn arby<A: Arbitrary>() -> A { Arbitrary::arbitrary(&mut StdGen::new(rand::thread_rng(), 5)) } // Shrink testing. #[test] fn unit() { eq((), vec![]); } #[test] fn bools() { eq(false, vec![]); eq(true, vec![false]); } #[test] fn options() { eq(None::<()>, vec![]); eq(Some(false), vec![None]); eq(Some(true), vec![None, Some(false)]); } #[test] fn results() { // Result<A, B> doesn't implement the Hash trait, so these tests // depends on the order of shrunk results. Ug. // TODO: Fix this. ordered_eq(Ok::<bool, ()>(true), vec![Ok(false)]); ordered_eq(Err::<(), bool>(true), vec![Err(false)]); } #[test] fn tuples() { eq((false, false), vec![]); eq((true, false), vec![(false, false)]); eq((true, true), vec![(false, true), (true, false)]); } #[test] fn triples() { eq((false, false, false), vec![]); eq((true, false, false), vec![(false, false, false)]); eq( (true, true, false), vec![(false, true, false), (true, false, false)], ); } #[test] fn quads() { eq((false, false, false, false), vec![]); eq((true, false, false, false), vec![(false, false, false, false)]); eq( (true, true, false, false), vec![(false, true, false, false), (true, false, false, false)], ); } #[test] fn ints() { // TODO: Test overflow? eq(5isize, vec![0, 3, 4]); eq(-5isize, vec![5, 0, -3, -4]); eq(0isize, vec![]); } #[test] fn ints8() { eq(5i8, vec![0, 3, 4]); eq(-5i8, vec![5, 0, -3, -4]); eq(0i8, vec![]); } #[test] fn ints16() { eq(5i16, vec![0, 3, 4]); eq(-5i16, vec![5, 0, -3, -4]); eq(0i16, vec![]); } #[test] fn ints32() { eq(5i32, vec![0, 3, 4]); eq(-5i32, vec![5, 0, -3, -4]); eq(0i32, vec![]); } #[test] fn ints64() { eq(5i64, vec![0, 3, 4]); eq(-5i64, vec![5, 0, -3, -4]); eq(0i64, vec![]); } #[test] fn ints128() { eq(5i128, vec![0, 3, 4]); eq(-5i128, vec![5, 0, -3, -4]); eq(0i128, vec![]); } #[test] fn uints() { eq(5usize, vec![0, 3, 4]); eq(0usize, vec![]); } #[test] fn uints8() { eq(5u8, vec![0, 3, 4]); eq(0u8, vec![]); } #[test] fn uints16() { eq(5u16, vec![0, 3, 4]); eq(0u16, vec![]); } #[test] fn uints32() { eq(5u32, vec![0, 3, 4]); eq(0u32, vec![]); } #[test] fn uints64() { eq(5u64, vec![0, 3, 4]); eq(0u64, vec![]); } #[test] fn uints128() { eq(5u128, vec![0, 3, 4]); eq(0u128, vec![]); } macro_rules! define_float_eq { ($ty:ty) => { fn eq(s: $ty, v: Vec<$ty>) { let shrunk: Vec<$ty> = s.shrink().collect(); for n in v { let found = shrunk.iter().any(|&i| i == n); if !found { panic!(format!( "Element {:?} was not found \ in shrink results {:?}", n, shrunk )); } } } }; } #[test] fn floats32() { define_float_eq!(f32); eq(0.0, vec![]); eq(-0.0, vec![]); eq(1.0, vec![0.0]); eq(2.0, vec![0.0, 1.0]); eq(-2.0, vec![0.0, 2.0, -1.0]); eq(1.5, vec![0.0]); } #[test] fn floats64() { define_float_eq!(f64); eq(0.0, vec![]); eq(-0.0, vec![]); eq(1.0, vec![0.0]); eq(2.0, vec![0.0, 1.0]); eq(-2.0, vec![0.0, 2.0, -1.0]); eq(1.5, vec![0.0]); } #[test] fn wrapping_ints32() { eq(Wrapping(5i32), vec![Wrapping(0), Wrapping(3), Wrapping(4)]); eq( Wrapping(-5i32), vec![Wrapping(5), Wrapping(0), Wrapping(-3), Wrapping(-4)], ); eq(Wrapping(0i32), vec![]); } #[test] fn vecs() { eq( { let it: Vec<isize> = vec![]; it }, vec![], ); eq( { let it: Vec<Vec<isize>> = vec![vec![]]; it }, vec![vec![]], ); eq(vec![1isize], vec![vec![], vec![0]]); eq(vec![11isize], vec![vec![], vec![0], vec![6], vec![9], vec![10]]); eq( vec![3isize, 5], vec![ vec![], vec![5], vec![3], vec![0, 5], vec![2, 5], vec![3, 0], vec![3, 3], vec![3, 4], ], ); } macro_rules! map_tests { ($name:ident, $ctor:expr) => { #[test] fn $name() { ordered_eq($ctor, vec![]); { let mut map = $ctor; map.insert(1usize, 1isize); let shrinks = vec![ $ctor, { let mut m = $ctor; m.insert(0, 1); m }, { let mut m = $ctor; m.insert(1, 0); m }, ]; ordered_eq(map, shrinks); } } }; } map_tests!(btreemap, BTreeMap::<usize, isize>::new()); map_tests!(hashmap, HashMap::<usize, isize>::new()); macro_rules! list_tests { ($name:ident, $ctor:expr, $push:ident) => { #[test] fn $name() { ordered_eq($ctor, vec![]); { let mut list = $ctor; list.$push(2usize); let shrinks = vec![ $ctor, { let mut m = $ctor; m.$push(0); m }, { let mut m = $ctor; m.$push(1); m }, ]; ordered_eq(list, shrinks); } } }; } list_tests!(btreesets, BTreeSet::<usize>::new(), insert); list_tests!(hashsets, HashSet::<usize>::new(), insert); list_tests!(linkedlists, LinkedList::<usize>::new(), push_back); list_tests!(vecdeques, VecDeque::<usize>::new(), push_back); #[test] fn binaryheaps() { ordered_eq( BinaryHeap::<usize>::new().into_iter().collect::<Vec<_>>(), vec![], ); { let mut heap = BinaryHeap::<usize>::new(); heap.push(2usize); let shrinks = vec![vec![], vec![0], vec![1]]; ordered_eq(heap.into_iter().collect::<Vec<_>>(), shrinks); } } #[test] fn chars() { eq('\x00', vec![]); } // All this jazz is for testing set equality on the results of a shrinker. fn eq<A: Arbitrary + Eq + Debug + Hash>(s: A, v: Vec<A>) { let (left, right) = (shrunk(s), set(v)); assert_eq!(left, right); } fn shrunk<A: Arbitrary + Eq + Hash>(s: A) -> HashSet<A> { set(s.shrink()) } fn set<A: Hash + Eq, I: IntoIterator<Item = A>>(xs: I) -> HashSet<A> { xs.into_iter().collect() } fn ordered_eq<A: Arbitrary + Eq + Debug>(s: A, v: Vec<A>) { let (left, right) = (s.shrink().collect::<Vec<A>>(), v); assert_eq!(left, right); } #[test] fn bounds() { use std::ops::Bound::*; for i in -5..=5 { ordered_eq(Included(i), i.shrink().map(Included).collect()); ordered_eq(Excluded(i), i.shrink().map(Excluded).collect()); } eq(Unbounded::<i32>, vec![]); } #[test] fn ranges() { ordered_eq(0..0, vec![]); ordered_eq(1..1, vec![0..1, 1..0]); ordered_eq(3..5, vec![0..5, 2..5, 3..0, 3..3, 3..4]); ordered_eq(5..3, vec![0..3, 3..3, 4..3, 5..0, 5..2]); ordered_eq(3.., vec![0.., 2..]); ordered_eq(..3, vec![..0, ..2]); ordered_eq(.., vec![]); ordered_eq(3..=5, vec![0..=5, 2..=5, 3..=0, 3..=3, 3..=4]); ordered_eq(..=3, vec![..=0, ..=2]); } #[test] fn pathbuf() { ordered_eq( PathBuf::from("/home/foo//.././bar"), vec![ PathBuf::from("/home/foo//.."), PathBuf::from("/home/foo/../bar"), ], ); } }
29.658196
92
0.451437
d63ae249edc1aad8247007b58e81ed55a7975bf9
19,287
#![cfg(feature = "rustls")] use std::{ io, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket}, str, sync::Arc, }; use bytes::Bytes; use futures::{future, StreamExt}; use rand::{rngs::StdRng, RngCore, SeedableRng}; use tokio::{ runtime::{Builder, Runtime}, time::{Duration, Instant}, }; use tracing::{info, info_span}; use tracing_futures::Instrument as _; use tracing_subscriber::EnvFilter; use super::{ ClientConfigBuilder, Endpoint, Incoming, NewConnection, RecvStream, SendStream, ServerConfigBuilder, TransportConfig, }; #[test] fn handshake_timeout() { let _guard = subscribe(); let runtime = rt_threaded(); let (client, _) = { let _guard = runtime.enter(); Endpoint::builder() .bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)) .unwrap() }; let mut client_config = crate::ClientConfig::default(); const IDLE_TIMEOUT: Duration = Duration::from_millis(500); let mut transport_config = crate::TransportConfig::default(); transport_config .max_idle_timeout(Some(IDLE_TIMEOUT)) .unwrap() .initial_rtt(Duration::from_millis(10)); client_config.transport = Arc::new(transport_config); let start = Instant::now(); runtime.block_on(async move { match client .connect_with( client_config, &SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1), "localhost", ) .unwrap() .await { Err(crate::ConnectionError::TimedOut) => {} Err(e) => panic!("unexpected error: {:?}", e), Ok(_) => panic!("unexpected success"), } }); let dt = start.elapsed(); assert!(dt > IDLE_TIMEOUT && dt < 2 * IDLE_TIMEOUT); } #[tokio::test] async fn close_endpoint() { let _guard = subscribe(); let endpoint = Endpoint::builder(); let (endpoint, incoming) = endpoint .bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)) .unwrap(); tokio::spawn(incoming.for_each(|_| future::ready(()))); let conn = endpoint .connect( &SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1234), "localhost", ) .unwrap(); endpoint.close(0u32.into(), &[]); match conn.await { Err(crate::ConnectionError::LocallyClosed) => (), Err(e) => panic!("unexpected error: {}", e), Ok(_) => { panic!("unexpected success"); } } } #[test] fn local_addr() { let socket = UdpSocket::bind("[::1]:0").unwrap(); let addr = socket.local_addr().unwrap(); let runtime = rt_basic(); let (ep, _) = { let _guard = runtime.enter(); Endpoint::builder().with_socket(socket).unwrap() }; assert_eq!( addr, ep.local_addr() .expect("Could not obtain our local endpoint") ); } #[test] fn read_after_close() { let _guard = subscribe(); let runtime = rt_basic(); let (endpoint, mut incoming) = { let _guard = runtime.enter(); endpoint() }; const MSG: &[u8] = b"goodbye!"; runtime.spawn(async move { let new_conn = incoming .next() .await .expect("endpoint") .await .expect("connection"); let mut s = new_conn.connection.open_uni().await.unwrap(); s.write_all(MSG).await.unwrap(); s.finish().await.unwrap(); }); runtime.block_on(async move { let mut new_conn = endpoint .connect(&endpoint.local_addr().unwrap(), "localhost") .unwrap() .await .expect("connect"); tokio::time::sleep_until(Instant::now() + Duration::from_millis(100)).await; let stream = new_conn .uni_streams .next() .await .expect("incoming streams") .expect("missing stream"); let msg = stream .read_to_end(usize::max_value()) .await .expect("read_to_end"); assert_eq!(msg, MSG); }); } #[test] fn export_keying_material() { let _guard = subscribe(); let runtime = rt_basic(); let (endpoint, mut incoming) = { let _guard = runtime.enter(); endpoint() }; runtime.block_on(async move { let outgoing_conn = endpoint .connect(&endpoint.local_addr().unwrap(), "localhost") .unwrap() .await .expect("connect"); let incoming_conn = incoming .next() .await .expect("endpoint") .await .expect("connection"); let mut i_buf = [0u8; 64]; incoming_conn .connection .export_keying_material(&mut i_buf, b"asdf", b"qwer") .unwrap(); let mut o_buf = [0u8; 64]; outgoing_conn .connection .export_keying_material(&mut o_buf, b"asdf", b"qwer") .unwrap(); assert_eq!(&i_buf[..], &o_buf[..]); }); } #[tokio::test] async fn accept_after_close() { let _guard = subscribe(); let (endpoint, mut incoming) = endpoint(); const MSG: &[u8] = b"goodbye!"; let sender = endpoint .connect(&endpoint.local_addr().unwrap(), "localhost") .unwrap() .await .expect("connect") .connection; let mut s = sender.open_uni().await.unwrap(); s.write_all(MSG).await.unwrap(); s.finish().await.unwrap(); sender.close(0u32.into(), b""); // Allow some time for the close to be sent and processed tokio::time::sleep(Duration::from_millis(100)).await; // Despite the connection having closed, we should be able to accept it... let mut receiver = incoming .next() .await .expect("endpoint") .await .expect("connection"); // ...and read what was sent. let stream = receiver .uni_streams .next() .await .expect("incoming streams") .expect("missing stream"); let msg = stream .read_to_end(usize::max_value()) .await .expect("read_to_end"); assert_eq!(msg, MSG); // But it's still definitely closed. assert!(receiver.connection.open_uni().await.is_err()); } /// Construct an endpoint suitable for connecting to itself fn endpoint() -> (Endpoint, Incoming) { let mut endpoint = Endpoint::builder(); let mut server_config = ServerConfigBuilder::default(); let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); let key = crate::PrivateKey::from_der(&cert.serialize_private_key_der()).unwrap(); let cert = crate::Certificate::from_der(&cert.serialize_der().unwrap()).unwrap(); let cert_chain = crate::CertificateChain::from_certs(vec![cert.clone()]); server_config.certificate(cert_chain, key).unwrap(); endpoint.listen(server_config.build()); let mut client_config = ClientConfigBuilder::default(); client_config.add_certificate_authority(cert).unwrap(); endpoint.default_client_config(client_config.build()); let (x, y) = endpoint .bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)) .unwrap(); (x, y) } #[tokio::test] async fn zero_rtt() { let _guard = subscribe(); let (endpoint, incoming) = endpoint(); const MSG: &[u8] = b"goodbye!"; tokio::spawn(incoming.take(2).for_each(|incoming| async { let NewConnection { mut uni_streams, connection, .. } = incoming.into_0rtt().unwrap_or_else(|_| unreachable!()).0; tokio::spawn(async move { while let Some(Ok(x)) = uni_streams.next().await { let msg = x.read_to_end(usize::max_value()).await.unwrap(); assert_eq!(msg, MSG); } }); let mut s = connection.open_uni().await.expect("open_uni"); s.write_all(MSG).await.expect("write"); s.finish().await.expect("finish"); })); let NewConnection { mut uni_streams, .. } = endpoint .connect(&endpoint.local_addr().unwrap(), "localhost") .unwrap() .into_0rtt() .err() .expect("0-RTT succeeded without keys") .await .expect("connect"); tokio::spawn(async move { // Buy time for the driver to process the server's NewSessionTicket tokio::time::sleep_until(Instant::now() + Duration::from_millis(100)).await; let stream = uni_streams .next() .await .expect("incoming streams") .expect("missing stream"); let msg = stream .read_to_end(usize::max_value()) .await .expect("read_to_end"); assert_eq!(msg, MSG); }); endpoint.wait_idle().await; info!("initial connection complete"); let ( NewConnection { connection, mut uni_streams, .. }, zero_rtt, ) = endpoint .connect(&endpoint.local_addr().unwrap(), "localhost") .unwrap() .into_0rtt() .unwrap_or_else(|_| panic!("missing 0-RTT keys")); // Send something ASAP to use 0-RTT tokio::spawn(async move { let mut s = connection.open_uni().await.expect("0-RTT open uni"); s.write_all(MSG).await.expect("0-RTT write"); s.finish().await.expect("0-RTT finish"); }); let stream = uni_streams .next() .await .expect("incoming streams") .expect("missing stream"); let msg = stream .read_to_end(usize::max_value()) .await .expect("read_to_end"); assert_eq!(msg, MSG); assert!(zero_rtt.await); drop(uni_streams); endpoint.wait_idle().await; } #[test] fn echo_v6() { run_echo(EchoArgs { client_addr: SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0), server_addr: SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 0), nr_streams: 1, stream_size: 10 * 1024, receive_window: None, stream_receive_window: None, }); } #[test] fn echo_v4() { run_echo(EchoArgs { client_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0), server_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0), nr_streams: 1, stream_size: 10 * 1024, receive_window: None, stream_receive_window: None, }); } #[test] #[cfg(any(target_os = "linux", target_os = "macos"))] // Dual-stack sockets aren't the default anywhere else. fn echo_dualstack() { run_echo(EchoArgs { client_addr: SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0), server_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0), nr_streams: 1, stream_size: 10 * 1024, receive_window: None, stream_receive_window: None, }); } #[test] fn stress_receive_window() { run_echo(EchoArgs { client_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0), server_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0), nr_streams: 50, stream_size: 25 * 1024 + 11, receive_window: Some(37), stream_receive_window: Some(100 * 1024 * 1024), }); } #[test] fn stress_stream_receive_window() { // Note that there is no point in runnning this with too many streams, // since the window is only active within a stream run_echo(EchoArgs { client_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0), server_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0), nr_streams: 2, stream_size: 250 * 1024 + 11, receive_window: Some(100 * 1024 * 1024), stream_receive_window: Some(37), }); } #[test] fn stress_both_windows() { run_echo(EchoArgs { client_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0), server_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0), nr_streams: 50, stream_size: 25 * 1024 + 11, receive_window: Some(37), stream_receive_window: Some(37), }); } fn run_echo(args: EchoArgs) { let _guard = subscribe(); let runtime = rt_basic(); let handle = { // Use small receive windows let mut transport_config = TransportConfig::default(); if let Some(receive_window) = args.receive_window { transport_config.receive_window(receive_window).unwrap(); } if let Some(stream_receive_window) = args.stream_receive_window { transport_config .stream_receive_window(stream_receive_window) .unwrap(); } transport_config.max_concurrent_bidi_streams(1).unwrap(); transport_config.max_concurrent_uni_streams(1).unwrap(); let transport_config = Arc::new(transport_config); // We don't use the `endpoint` helper here because we want two different endpoints with // different addresses. let mut server_config = ServerConfigBuilder::default(); let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); let key = crate::PrivateKey::from_der(&cert.serialize_private_key_der()).unwrap(); let cert = crate::Certificate::from_der(&cert.serialize_der().unwrap()).unwrap(); let cert_chain = crate::CertificateChain::from_certs(vec![cert.clone()]); server_config.certificate(cert_chain, key).unwrap(); let mut server = Endpoint::builder(); let mut server_config = server_config.build(); server_config.transport = transport_config.clone(); server.listen(server_config); let server_sock = UdpSocket::bind(args.server_addr).unwrap(); let server_addr = server_sock.local_addr().unwrap(); let (server, mut server_incoming) = { let _guard = runtime.enter(); server.with_socket(server_sock).unwrap() }; let mut client_config = ClientConfigBuilder::default(); client_config.add_certificate_authority(cert).unwrap(); client_config.enable_keylog(); let mut client_config = client_config.build(); client_config.transport = transport_config; let mut client = Endpoint::builder(); client.default_client_config(client_config); let (client, _) = { let _guard = runtime.enter(); client.bind(&args.client_addr).unwrap() }; let handle = runtime.spawn(async move { let incoming = server_incoming.next().await.unwrap(); // Note for anyone modifying the platform support in this test: // If `local_ip` gets available on additional platforms - which // requires modifying this test - please update the list of supported // platforms in the doc comments of the various `local_ip` functions. if cfg!(target_os = "linux") { let local_ip = incoming.local_ip().expect("Local IP must be available"); assert!(local_ip.is_loopback()); } else { assert_eq!(None, incoming.local_ip()); } let new_conn = incoming.instrument(info_span!("server")).await.unwrap(); tokio::spawn( new_conn .bi_streams .take_while(|x| future::ready(x.is_ok())) .for_each(|s| async { tokio::spawn(echo(s.unwrap())); }), ); server.wait_idle().await; }); info!( "connecting from {} to {}", args.client_addr, args.server_addr ); runtime.block_on(async move { let new_conn = client .connect(&server_addr, "localhost") .unwrap() .instrument(info_span!("client")) .await .expect("connect"); /// This is just an arbitrary number to generate deterministic test data const SEED: u64 = 0x12345678; for i in 0..args.nr_streams { println!("Opening stream {}", i); let (mut send, recv) = new_conn.connection.open_bi().await.expect("stream open"); let msg = gen_data(args.stream_size, SEED); let send_task = async { send.write_all(&msg).await.expect("write"); send.finish().await.expect("finish"); }; let recv_task = async { recv.read_to_end(usize::max_value()).await.expect("read") }; let (_, data) = futures::join!(send_task, recv_task); assert_eq!(data[..], msg[..], "Data mismatch"); } new_conn.connection.close(0u32.into(), b"done"); client.wait_idle().await; }); handle }; runtime.block_on(handle).unwrap(); } struct EchoArgs { client_addr: SocketAddr, server_addr: SocketAddr, nr_streams: usize, stream_size: usize, receive_window: Option<u64>, stream_receive_window: Option<u64>, } async fn echo((mut send, mut recv): (SendStream, RecvStream)) { loop { // These are 32 buffers, for reading approximately 32kB at once #[rustfmt::skip] let mut bufs = [ Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), ]; match recv.read_chunks(&mut bufs).await.expect("read chunks") { Some(n) => { send.write_all_chunks(&mut bufs[..n]) .await .expect("write chunks"); } None => break, } } let _ = send.finish().await; } fn gen_data(size: usize, seed: u64) -> Vec<u8> { let mut rng: StdRng = SeedableRng::seed_from_u64(seed); let mut buf = vec![0; size]; rng.fill_bytes(&mut buf); buf } pub fn subscribe() -> tracing::subscriber::DefaultGuard { let sub = tracing_subscriber::FmtSubscriber::builder() .with_env_filter(EnvFilter::from_default_env()) .with_writer(|| TestWriter) .finish(); tracing::subscriber::set_default(sub) } struct TestWriter; impl std::io::Write for TestWriter { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { print!( "{}", str::from_utf8(buf).expect("tried to log invalid UTF-8") ); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { io::stdout().flush() } } fn rt_basic() -> Runtime { Builder::new_current_thread().enable_all().build().unwrap() } fn rt_threaded() -> Runtime { Builder::new_multi_thread().enable_all().build().unwrap() }
31.985075
109
0.573962
8f945470b7e94b25646f6336a14cfa7d3b84dd1f
3,361
// Copyright 2013 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. //! Runtime services //! //! The `rt` module provides a narrow set of runtime services, //! including the global heap (exported in `heap`) and unwinding and //! backtrace support. The APIs in this module are highly unstable, //! and should be considered as private implementation details for the //! time being. #![unstable(feature = "rt", reason = "this public module should not exist and is highly likely \ to disappear", issue = "0")] #![doc(hidden)] // Re-export some of our utilities which are expected by other crates. pub use panicking::{begin_panic, begin_panic_fmt, update_panic_count}; // To reduce the generated code of the new `lang_start`, this function is doing // the real work. #[cfg(not(test))] fn lang_start_internal(main: &(Fn() -> i32 + Sync + ::panic::RefUnwindSafe), argc: isize, argv: *const *const u8) -> isize { use panic; use sys; use sys_common; use sys_common::thread_info; use thread::Thread; sys::init(); unsafe { let main_guard = sys::thread::guard::init(); sys::stack_overflow::init(); // Next, set up the current Thread with the guard information we just // created. Note that this isn't necessary in general for new threads, // but we just do this to name the main thread and to give it correct // info about the stack bounds. let thread = Thread::new(Some("main".to_owned())); thread_info::set(main_guard, thread); // Store our args if necessary in a squirreled away location sys::args::init(argc, argv); // Let's run some code! #[cfg(feature = "backtrace")] let exit_code = panic::catch_unwind(|| { ::sys_common::backtrace::__rust_begin_short_backtrace(move || main()) }); #[cfg(not(feature = "backtrace"))] let exit_code = panic::catch_unwind(move || main()); sys_common::cleanup(); exit_code.unwrap_or(101) as isize } } #[cfg(not(test))] #[lang = "start"] fn lang_start<T: ::process::Termination + 'static> (main: fn() -> T, argc: isize, argv: *const *const u8) -> isize { lang_start_internal(&move || main().report(), argc, argv) } /// Function used for reverting changes to the main stack before setrlimit(). /// This is POSIX (non-Linux) specific and unlikely to be directly stabilized. #[unstable(feature = "rustc_stack_internals", issue = "0")] pub unsafe fn deinit_stack_guard() { ::sys::thread::guard::deinit(); } /// Function used for resetting the main stack guard address after setrlimit(). /// This is POSIX specific and unlikely to be directly stabilized. #[unstable(feature = "rustc_stack_internals", issue = "0")] pub unsafe fn update_stack_guard() { let main_guard = ::sys::thread::guard::init(); ::sys_common::thread_info::reset_guard(main_guard); }
36.934066
81
0.661113
ab4d7d4594e9a46fa5b24c8b5b5b094dd417312b
2,028
// LNP/BP client-side-validation foundation libraries implementing LNPBP // specifications & standards (LNPBP-4, 7, 8, 9, 42, 81) // // Written in 2019-2021 by // Dr. Maxim Orlovsky <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the Apache 2.0 License along with this // software. If not, see <https://opensource.org/licenses/Apache-2.0>. extern crate compiletest_rs as compiletest; use std::fmt::{Debug, Display, Formatter}; use std::path::PathBuf; use strict_encoding::{StrictDecode, StrictEncode}; use strict_encoding_test::DataEncodingTestFailure; #[allow(dead_code)] pub fn compile_test(mode: &'static str) { let mut config = compiletest::Config::default(); config.mode = mode.parse().expect("Invalid mode"); config.src_base = PathBuf::from(format!("tests/{}", mode)); config.link_deps(); // Populate config.target_rustcflags with dependencies on the path config.clean_rmeta(); // If your tests import the parent crate, this helps with E0464 compiletest::run_tests(&config); } #[derive(Display)] #[display(inner)] pub struct Error(pub Box<dyn std::error::Error>); impl Debug for Error { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Display::fmt(self, f) } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(self.0.as_ref()) } } impl<T> From<strict_encoding_test::DataEncodingTestFailure<T>> for Error where T: StrictEncode + StrictDecode + PartialEq + Debug + Clone + 'static, { fn from(err: DataEncodingTestFailure<T>) -> Self { Self(Box::new(err)) } } impl From<strict_encoding::Error> for Error { fn from(err: strict_encoding::Error) -> Self { Self(Box::new(err)) } } pub type Result = std::result::Result<(), Error>;
32.190476
90
0.699211
22e10a31f40d188cf767fdc6e4dd5463a293b55b
2,163
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::access_path::AccessPath; use crate::account_address::AccountAddress; use crate::account_config::CORE_CODE_ADDRESS; use crate::event::EventHandle; use crate::language_storage::StructTag; use crate::move_resource::MoveResource; use crate::token::token_code::TokenCode; use serde::{Deserialize, Serialize}; /// A Rust representation of a Treasury resource. #[derive(Debug, Serialize, Deserialize)] pub struct Treasury { pub balance: u128, /// event handle for treasury withdraw event pub withdraw_events: EventHandle, /// event handle for treasury deposit event pub deposit_events: EventHandle, } impl MoveResource for Treasury { const MODULE_NAME: &'static str = "Treasury"; const STRUCT_NAME: &'static str = "Treasury"; } impl Treasury { pub fn struct_tag_for(token_code: TokenCode) -> StructTag { StructTag { address: CORE_CODE_ADDRESS, module: Self::module_identifier(), name: Self::struct_identifier(), type_params: vec![token_code.into()], } } pub fn resource_path_for(token_code: TokenCode) -> AccessPath { AccessPath::resource_access_path(token_code.address, Self::struct_tag_for(token_code)) } } #[derive(Debug, Serialize, Deserialize)] pub struct LinearWithdrawCapability { pub total: u128, pub withdraw: u128, pub start_time: u64, pub period: u64, } impl MoveResource for LinearWithdrawCapability { const MODULE_NAME: &'static str = "Treasury"; const STRUCT_NAME: &'static str = "LinearWithdrawCapability"; } impl LinearWithdrawCapability { pub fn struct_tag_for(token_code: TokenCode) -> StructTag { StructTag { address: CORE_CODE_ADDRESS, module: Self::module_identifier(), name: Self::struct_identifier(), type_params: vec![token_code.into()], } } pub fn resource_path_for(address: AccountAddress, token_code: TokenCode) -> AccessPath { AccessPath::resource_access_path(address, Self::struct_tag_for(token_code)) } }
30.9
94
0.696718
ac09e156e081c7dfd384000abd7dd2c13c8e945a
3,606
//! An example that periodically sends a message to the address 123 #![no_std] #![no_main] extern crate panic_halt; use teensy4_bsp as bsp; use cortex_m_rt::entry; use log::info; use teensy4_canfd::{CAN3FD, CANFDBuilder, TxFDFrame, RxFDFrame}; use teensy4_canfd::config::{ Clock, Config, Id, MailboxConfig, RegionConfig, RxMailboxConfig, TimingConfig, }; use core::cell::RefCell; use cortex_m::interrupt::Mutex; use cortex_m::interrupt; static CAN3: Mutex<RefCell<Option<CAN3FD>>> = Mutex::new(RefCell::new(None)); fn on_rx_recv(_cs: &interrupt::CriticalSection, _rx_frame: RxFDFrame) { info!("main::on_rx_recv(..)"); } #[entry] fn main() -> ! { let mut _p = bsp::Peripherals::take().unwrap(); let core_peripherals = cortex_m::Peripherals::take().unwrap(); let mut systick = bsp::SysTick::new(core_peripherals.SYST); //let (mut reader, mut writer) = bsp::usb::split(&systick).unwrap(); bsp::usb::init( &systick, bsp::usb::LoggingConfig::default(), ) .unwrap(); systick.delay(2000); info!("Teensy 4 CANFD Tester - Periodic transfer"); let mbrx = RxMailboxConfig { id: Id::Standard(123), id_mask: 0x3FFF_FFFF, }; let region_1_config = RegionConfig::MB32 { mailbox_configs: [ MailboxConfig::Tx, MailboxConfig::Rx { rx_config: mbrx, }, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, MailboxConfig::Unconfigured, ], }; let region_2_config = RegionConfig::MB64 { mailbox_configs: [MailboxConfig::Unconfigured; 7], }; // TOOD Timings let can_config = Config { clock_speed: Clock::Clock30Mhz, timing_classical: TimingConfig { prescalar_division: 1, prop_seg: 13, phase_seg_1: 3, phase_seg_2: 3, jump_width: 3, }, timing_fd: TimingConfig { prescalar_division: 1, prop_seg: 0, phase_seg_1: 3, phase_seg_2: 2, jump_width: 2, }, region_1_config: region_1_config.clone(), region_2_config: region_2_config.clone(), transceiver_compensation: Some(3), }; let canfd = CANFDBuilder::take().unwrap().build(can_config); if let Err(error) = canfd { info!("COULD NOT BUILD GOT {:?}", error); } let mut canfd = canfd.unwrap(); interrupt::free(|cs| { canfd.set_rx_callback(cs, Some(on_rx_recv)); }); interrupt::free(|cs| CAN3.borrow(cs).replace(Some(canfd))); let mut counter = 42u32; let mut buffer = [0_u8; 16]; loop { buffer[0] = (counter % 255) as u8; counter = counter + 1; let tx_frame = TxFDFrame { id: Id::Standard(123), buffer: &buffer, priority: None, }; interrupt::free(|cs| { if let Some(canfd) = CAN3.borrow(cs).borrow_mut().as_mut() { if let Err(_error) = canfd.transfer_blocking(cs, &tx_frame) { info!("WELL crap, got error"); } } else { info!("COULD NOT BORROW"); } }); info!("SENT FRAME"); systick.delay(50); } }
26.514706
82
0.573211
29286420b7425a86975c566c8867c54bbe8b097c
4,465
//! Abstract definition of a matrix data storage allocator. use std::any::Any; use crate::base::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint}; use crate::base::dimension::{Dim, U1}; use crate::base::{DefaultAllocator, Scalar}; use crate::storage::{IsContiguous, RawStorageMut}; use crate::StorageMut; use std::fmt::Debug; use std::mem::MaybeUninit; /// A matrix allocator of a memory buffer that may contain `R::to_usize() * C::to_usize()` /// elements of type `T`. /// /// An allocator is said to be: /// − static: if `R` and `C` both implement `DimName`. /// − dynamic: if either one (or both) of `R` or `C` is equal to `Dynamic`. /// /// Every allocator must be both static and dynamic. Though not all implementations may share the /// same `Buffer` type. pub trait Allocator<T, R: Dim, C: Dim = U1>: Any + Sized { /// The type of buffer this allocator can instanciate. type Buffer: StorageMut<T, R, C> + IsContiguous + Clone + Debug; /// The type of buffer with uninitialized components this allocator can instanciate. type BufferUninit: RawStorageMut<MaybeUninit<T>, R, C> + IsContiguous; /// Allocates a buffer with the given number of rows and columns without initializing its content. fn allocate_uninit(nrows: R, ncols: C) -> Self::BufferUninit; /// Assumes a data buffer to be initialized. /// /// # Safety /// The user must make sure that every single entry of the buffer has been initialized, /// or Undefined Behavior will immediately occur. unsafe fn assume_init(uninit: Self::BufferUninit) -> Self::Buffer; /// Allocates a buffer initialized with the content of the given iterator. fn allocate_from_iterator<I: IntoIterator<Item = T>>( nrows: R, ncols: C, iter: I, ) -> Self::Buffer; } /// A matrix reallocator. Changes the size of the memory buffer that initially contains (`RFrom` × /// `CFrom`) elements to a smaller or larger size (`RTo`, `CTo`). pub trait Reallocator<T: Scalar, RFrom: Dim, CFrom: Dim, RTo: Dim, CTo: Dim>: Allocator<T, RFrom, CFrom> + Allocator<T, RTo, CTo> { /// Reallocates a buffer of shape `(RTo, CTo)`, possibly reusing a previously allocated buffer /// `buf`. Data stored by `buf` are linearly copied to the output: /// /// # Safety /// The following invariants must be respected by the implementors of this method: /// * The copy is performed as if both were just arrays (without taking into account the matrix structure). /// * If the underlying buffer is being shrunk, the removed elements must **not** be dropped /// by this method. Dropping them is the responsibility of the caller. unsafe fn reallocate_copy( nrows: RTo, ncols: CTo, buf: <Self as Allocator<T, RFrom, CFrom>>::Buffer, ) -> <Self as Allocator<T, RTo, CTo>>::BufferUninit; } /// The number of rows of the result of a componentwise operation on two matrices. pub type SameShapeR<R1, R2> = <ShapeConstraint as SameNumberOfRows<R1, R2>>::Representative; /// The number of columns of the result of a componentwise operation on two matrices. pub type SameShapeC<C1, C2> = <ShapeConstraint as SameNumberOfColumns<C1, C2>>::Representative; // TODO: Bad name. /// Restricts the given number of rows and columns to be respectively the same. pub trait SameShapeAllocator<T, R1, C1, R2, C2>: Allocator<T, R1, C1> + Allocator<T, SameShapeR<R1, R2>, SameShapeC<C1, C2>> where R1: Dim, R2: Dim, C1: Dim, C2: Dim, ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2>, { } impl<T, R1, R2, C1, C2> SameShapeAllocator<T, R1, C1, R2, C2> for DefaultAllocator where R1: Dim, R2: Dim, C1: Dim, C2: Dim, DefaultAllocator: Allocator<T, R1, C1> + Allocator<T, SameShapeR<R1, R2>, SameShapeC<C1, C2>>, ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2>, { } // XXX: Bad name. /// Restricts the given number of rows to be equal. pub trait SameShapeVectorAllocator<T, R1, R2>: Allocator<T, R1> + Allocator<T, SameShapeR<R1, R2>> + SameShapeAllocator<T, R1, U1, R2, U1> where R1: Dim, R2: Dim, ShapeConstraint: SameNumberOfRows<R1, R2>, { } impl<T, R1, R2> SameShapeVectorAllocator<T, R1, R2> for DefaultAllocator where R1: Dim, R2: Dim, DefaultAllocator: Allocator<T, R1, U1> + Allocator<T, SameShapeR<R1, R2>>, ShapeConstraint: SameNumberOfRows<R1, R2>, { }
38.826087
111
0.682419