text
stringlengths
8
4.13M
extern crate las; use las::Reader; #[test] fn detect_laszip() { if cfg!(feature = "laz") { assert!(Reader::from_path("tests/data/autzen.laz").is_ok()); } else { assert!(Reader::from_path("tests/data/autzen.laz").is_err()); } } #[cfg(feature = "laz")] mod laz_compression_test { use las::{Read, Write}; use std::io::Cursor; /// Read file, write it compressed, read the compressed data written /// compare that points are the same fn test_compression_does_not_corrupt(path: &str) { let mut reader = las::Reader::from_path(path).expect("Cannot open reader"); let points: Vec<las::Point> = reader.points().map(|r| r.unwrap()).collect(); let mut header_builder = las::Builder::from(reader.header().version()); header_builder.point_format = *reader.header().point_format(); header_builder.point_format.is_compressed = true; let header = header_builder.into_header().unwrap(); let cursor = Cursor::new(Vec::<u8>::new()); let mut writer = las::Writer::new(cursor, header).unwrap(); for point in &points { writer.write(point.clone()).unwrap(); } writer.close().unwrap(); let cursor = writer.into_inner().unwrap(); let mut reader = las::Reader::new(cursor).unwrap(); let points_2: Vec<las::Point> = reader.points().map(|r| r.unwrap()).collect(); assert_eq!(points, points_2); } #[test] fn test_point_format_id_is_correct() { let las_reader = las::Reader::from_path("tests/data/autzen.las").unwrap(); assert_eq!(las_reader.header().point_format().to_u8().unwrap(), 1); let laz_reader = las::Reader::from_path("tests/data/autzen.laz").unwrap(); assert_eq!(laz_reader.header().point_format().to_u8().unwrap(), 3); } #[test] fn test_autzen_las() { test_compression_does_not_corrupt("tests/data/autzen.las"); } #[test] fn test_autzen_laz() { test_compression_does_not_corrupt("tests/data/autzen.laz"); } #[test] fn test_extra_bytes_laz() { test_compression_does_not_corrupt("tests/data/extrabytes.laz"); } }
use actix_web::web; use actix_web::HttpResponse; use crate::db_connection::{SqlitePool, SqlitePooledConnection}; pub fn pool_handler(pool: web::Data<SqlitePool>) -> Result<SqlitePooledConnection, HttpResponse> { pool.get().map_err(|_| { HttpResponse::InternalServerError().body("error") }) }
use serde::{Serialize, Deserialize}; // Maximum number of temp value types we keep track of pub const MAX_TEMP_TYPES: usize = 8; // Maximum number of local variable types we keep track of const MAX_LOCAL_TYPES: usize = 8; // Represent the type of a value (local/stack/self) in YJIT #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize, Deserialize)] pub enum Type { Unknown, UnknownImm, UnknownHeap, Nil, True, False, Fixnum, Flonum, Array, Hash, ImmSymbol, #[allow(unused)] HeapSymbol, TString, // An object with the T_STRING flag set, possibly an rb_cString CString, // An un-subclassed string of type rb_cString (can have instance vars in some cases) BlockParamProxy, // A special sentinel value indicating the block parameter should be read from // the current surrounding cfp } // Default initialization impl Default for Type { fn default() -> Self { Type::Unknown } } // Potential mapping of a value on the temporary stack to // self, a local variable or constant so that we can track its type #[derive(Copy, Clone, Eq, Debug, Serialize, Deserialize, Hash, PartialEq)] pub enum TempMapping { MapToStack, // Normal stack value MapToSelf, // Temp maps to the self operand MapToLocal(u8), // Temp maps to a local variable with index //ConstMapping, // Small constant (0, 1, 2, Qnil, Qfalse, Qtrue) } impl Default for TempMapping { fn default() -> Self { TempMapping::MapToStack } } #[derive(Copy, Clone, Default, Debug, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct Context { // Number of values currently on the temporary stack stack_size: u16, // Offset of the JIT SP relative to the interpreter SP // This represents how far the JIT's SP is from the "real" SP sp_offset: i16, // Depth of this block in the sidechain (eg: inline-cache chain) chain_depth: u8, // Local variable types we keep track of local_types: [Type; MAX_LOCAL_TYPES], // Temporary variable types we keep track of temp_types: [Type; MAX_TEMP_TYPES], // Type we track for self self_type: Type, // Mapping of temp stack entries to types we track temp_mapping: [TempMapping; MAX_TEMP_TYPES], } #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize, Deserialize)] pub struct VALUE(pub usize); #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct CmeDependency { receiver_klass: VALUE, callee_cme: u32, } #[derive(Debug, Copy, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct BlockId { pub iseq: usize, pub idx: u32, } impl BlockId { fn _name(&self) -> String { format!("block_{}_{}", self.iseq, self.idx) } } #[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, Hash)] pub enum BranchShape { Next0, // Target 0 is next Next1, // Target 1 is next Default, // Neither target is next } /// A place that a branch could jump to #[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct BranchTarget { pub address: Option<usize>, pub id: BlockId, pub ctx: Context, pub block: Option<usize>, } #[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct Branch { pub id: usize, pub block_id: usize, pub start_addr: Option<usize>, pub end_addr: Option<usize>, pub shape: BranchShape, #[serde(skip)] pub writable_areas: Vec<(usize, usize)>, pub disasm: String, // Branch target blocks and their contexts pub targets: [Option<BranchTarget>; 2], #[serde(skip)] pub bytes: Vec<u8>, } #[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct CodeLocation { pub file: Option<String>, pub method_name: Option<String>, pub line_start: (i32, i32), pub line_end: (i32, i32), } #[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct Block { pub block_id: BlockId, pub id: usize, pub end_idx: u32, pub ctx: Context, pub start_addr: Option<usize>, pub end_addr: Option<usize>, pub incoming: Vec<Branch>, pub outgoing: Vec<Branch>, pub gc_object_offsets: Vec<u32>, pub entry_exit: Option<usize>, pub location: CodeLocation, pub disasm: String, pub epoch: usize, #[serde(default)] pub is_exit: bool, pub created_at: usize, pub invalid: bool, }
// Get smart pointer for C++ into Rust code so it is usable use cxx::UniquePtr; // C++ <-> Rust Bridge #[cxx::bridge] mod ffi{ // Rust functions which go to C++ header extern "Rust"{ fn robot_init(); fn robot_periodic(); fn autonomous_init(); fn autonomous_periodic(); fn teleop_init(); fn teleop_periodic(); fn test_init(); fn test_periodic(); } // C++ objects/methods brought into Rust scope unsafe extern "C++"{ include!("wpilib_rs/header_files/frc/Spark.h"); type Spark; fn spark(channel: i64) -> UniquePtr<Spark>; fn Set(&self, value: f64); } } // Import nessescary C++ objects/methods from bridge use crate::ffi::Spark; use crate::ffi::spark; // Motors declared as constants so they will be available the whole scope const MOTOR1: UniquePtr<Spark> = spark(1); const MOTOR2: UniquePtr<Spark> = spark(2); // Robot functions go here fn robot_init(){ MOTOR1.Set(0.5); } fn robot_periodic(){ } fn autonomous_init(){ } fn autonomous_periodic(){ } fn teleop_init(){ } fn teleop_periodic(){ } fn test_init(){ } fn test_periodic(){ }
// Kata: https://www.codewars.com/kata/513e08acc600c94f01000001/train/rust pub fn rgb(r: i32, g: i32, b: i32) -> String { let mut array = [r, g, b]; for n in array.iter_mut() { if *n < 0 { *n = 0; } if *n > 255 { *n = 255; } } format!("{:02X}{:02X}{:02X}", array[0], array[1], array[2]) }
// Copyright (c) 2016 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use std::ops::Range; use buffer::BufferSlice; use buffer::sys::UnsafeBuffer; use device::DeviceOwned; use device::Queue; use image::ImageAccess; use memory::Content; use sync::AccessError; use SafeDeref; use VulkanObject; /// Trait for objects that represent either a buffer or a slice of a buffer. /// /// See also `TypedBuffer`. // TODO: require `DeviceOwned` pub unsafe trait Buffer { /// Object that represents a GPU access to the buffer. type Access: BufferAccess; /// Builds an object that represents a GPU access to the buffer. fn access(self) -> Self::Access; /// Returns the size of the buffer in bytes. fn size(&self) -> usize; /// Returns the length of the buffer in number of elements. /// /// This method can only be called for buffers whose type is known to be an array. #[inline] fn len(&self) -> usize where Self: TypedBuffer, Self::Content: Content { self.size() / <Self::Content as Content>::indiv_size() } /// Builds a `BufferSlice` object holding part of the buffer. /// /// This method can only be called for buffers whose type is known to be an array. /// /// This method can be used when you want to perform an operation on some part of the buffer /// and not on the whole buffer. /// /// Returns `None` if out of range. #[inline] fn slice<T>(self, range: Range<usize>) -> Option<BufferSlice<[T], Self>> where Self: Sized + TypedBuffer<Content = [T]> { BufferSlice::slice(self.into_buffer_slice(), range) } /// Builds a `BufferSlice` object holding the buffer by value. #[inline] fn into_buffer_slice(self) -> BufferSlice<Self::Content, Self> where Self: Sized + TypedBuffer { BufferSlice::from_typed_buffer(self) } /// Builds a `BufferSlice` object holding part of the buffer. /// /// This method can only be called for buffers whose type is known to be an array. /// /// This method can be used when you want to perform an operation on a specific element of the /// buffer and not on the whole buffer. /// /// Returns `None` if out of range. #[inline] fn index<T>(self, index: usize) -> Option<BufferSlice<[T], Self>> where Self: Sized + TypedBuffer<Content = [T]> { self.slice(index .. (index + 1)) } } /// Extension trait for `Buffer`. Indicates the type of the content of the buffer. pub unsafe trait TypedBuffer: Buffer { /// The type of the content of the buffer. type Content: ?Sized; } /// Trait for objects that represent a way for the GPU to have access to a buffer or a slice of a /// buffer. /// /// See also `TypedBufferAccess`. pub unsafe trait BufferAccess: DeviceOwned { /// Returns the inner information about this buffer. fn inner(&self) -> BufferInner; /// Returns the size of the buffer in bytes. // FIXME: don't provide by default, because can be wrong #[inline] fn size(&self) -> usize { self.inner().buffer.size() } /// Returns the length of the buffer in number of elements. /// /// This method can only be called for buffers whose type is known to be an array. #[inline] fn len(&self) -> usize where Self: TypedBufferAccess, Self::Content: Content { self.size() / <Self::Content as Content>::indiv_size() } /// Builds a `BufferSlice` object holding the buffer by reference. #[inline] fn as_buffer_slice(&self) -> BufferSlice<Self::Content, &Self> where Self: Sized + TypedBufferAccess { BufferSlice::from_typed_buffer_access(self) } /// Builds a `BufferSlice` object holding part of the buffer by reference. /// /// This method can only be called for buffers whose type is known to be an array. /// /// This method can be used when you want to perform an operation on some part of the buffer /// and not on the whole buffer. /// /// Returns `None` if out of range. #[inline] fn slice<T>(&self, range: Range<usize>) -> Option<BufferSlice<[T], &Self>> where Self: Sized + TypedBufferAccess<Content = [T]> { BufferSlice::slice(self.as_buffer_slice(), range) } /// Builds a `BufferSlice` object holding the buffer by value. #[inline] fn into_buffer_slice(self) -> BufferSlice<Self::Content, Self> where Self: Sized + TypedBufferAccess { BufferSlice::from_typed_buffer_access(self) } /// Builds a `BufferSlice` object holding part of the buffer by reference. /// /// This method can only be called for buffers whose type is known to be an array. /// /// This method can be used when you want to perform an operation on a specific element of the /// buffer and not on the whole buffer. /// /// Returns `None` if out of range. #[inline] fn index<T>(&self, index: usize) -> Option<BufferSlice<[T], &Self>> where Self: Sized + TypedBufferAccess<Content = [T]> { self.slice(index .. (index + 1)) } /// Returns true if an access to `self` (as defined by `self_offset` and `self_size`) /// potentially overlaps the same memory as an access to `other` (as defined by `other_offset` /// and `other_size`). /// /// If this function returns `false`, this means that we are allowed to access the offset/size /// of `self` at the same time as the offset/size of `other` without causing a data race. fn conflicts_buffer(&self, self_offset: usize, self_size: usize, other: &BufferAccess, other_offset: usize, other_size: usize) -> bool { // TODO: should we really provide a default implementation? debug_assert!(self_size <= self.size()); if self.inner().buffer.internal_object() != other.inner().buffer.internal_object() { return false; } let self_offset = self_offset + self.inner().offset; let other_offset = other_offset + other.inner().offset; if self_offset < other_offset && self_offset + self_size <= other_offset { return false; } if other_offset < self_offset && other_offset + other_size <= self_offset { return false; } true } /// Returns true if an access to `self` (as defined by `self_offset` and `self_size`) /// potentially overlaps the same memory as an access to `other` (as defined by /// `other_first_layer`, `other_num_layers`, `other_first_mipmap` and `other_num_mipmaps`). /// /// If this function returns `false`, this means that we are allowed to access the offset/size /// of `self` at the same time as the offset/size of `other` without causing a data race. fn conflicts_image(&self, self_offset: usize, self_size: usize, other: &ImageAccess, other_first_layer: u32, other_num_layers: u32, other_first_mipmap: u32, other_num_mipmaps: u32) -> bool { let other_key = other.conflict_key(other_first_layer, other_num_layers, other_first_mipmap, other_num_mipmaps); self.conflict_key(self_offset, self_size) == other_key } /// Returns a key that uniquely identifies the range given by offset/size. /// /// Two ranges that potentially overlap in memory should return the same key. /// /// The key is shared amongst all buffers and images, which means that you can make several /// different buffer objects share the same memory, or make some buffer objects share memory /// with images, as long as they return the same key. /// /// Since it is possible to accidentally return the same key for memory ranges that don't /// overlap, the `conflicts_buffer` or `conflicts_image` function should always be called to /// verify whether they actually overlap. fn conflict_key(&self, self_offset: usize, self_size: usize) -> u64 { // FIXME: remove implementation unimplemented!() } /// Shortcut for `conflicts_buffer` that compares the whole buffer to another. #[inline] fn conflicts_buffer_all(&self, other: &BufferAccess) -> bool { self.conflicts_buffer(0, self.size(), other, 0, other.size()) } /// Shortcut for `conflicts_image` that compares the whole buffer to a whole image. #[inline] fn conflicts_image_all(&self, other: &ImageAccess) -> bool { self.conflicts_image(0, self.size(), other, 0, other.dimensions().array_layers(), 0, other.mipmap_levels()) } /// Shortcut for `conflict_key` that grabs the key of the whole buffer. #[inline] fn conflict_key_all(&self) -> u64 { self.conflict_key(0, self.size()) } /// Locks the resource for usage on the GPU. Returns `false` if the lock was already acquired. /// /// This function implementation should remember that it has been called and return `false` if /// it gets called a second time. /// /// The only way to know that the GPU has stopped accessing a queue is when the buffer object /// gets destroyed. Therefore you are encouraged to use temporary objects or handles (similar /// to a lock) in order to represent a GPU access. fn try_gpu_lock(&self, exclusive_access: bool, queue: &Queue) -> Result<(), AccessError>; /// Locks the resource for usage on the GPU. Supposes that the resource is already locked, and /// simply increases the lock by one. /// /// Must only be called after `try_gpu_lock()` succeeded. unsafe fn increase_gpu_lock(&self); } /// Inner information about a buffer. #[derive(Copy, Clone, Debug)] pub struct BufferInner<'a> { /// The underlying buffer object. pub buffer: &'a UnsafeBuffer, /// The offset in bytes from the start of the underlying buffer object to the start of the /// buffer we're describing. pub offset: usize, } unsafe impl<T> BufferAccess for T where T: SafeDeref, T::Target: BufferAccess { #[inline] fn inner(&self) -> BufferInner { (**self).inner() } #[inline] fn size(&self) -> usize { (**self).size() } #[inline] fn conflicts_buffer(&self, self_offset: usize, self_size: usize, other: &BufferAccess, other_offset: usize, other_size: usize) -> bool { (**self).conflicts_buffer(self_offset, self_size, other, other_offset, other_size) } #[inline] fn conflict_key(&self, self_offset: usize, self_size: usize) -> u64 { (**self).conflict_key(self_offset, self_size) } #[inline] fn try_gpu_lock(&self, exclusive_access: bool, queue: &Queue) -> Result<(), AccessError> { (**self).try_gpu_lock(exclusive_access, queue) } #[inline] unsafe fn increase_gpu_lock(&self) { (**self).increase_gpu_lock() } } /// Extension trait for `BufferAccess`. Indicates the type of the content of the buffer. pub unsafe trait TypedBufferAccess: BufferAccess { /// The type of the content. type Content: ?Sized; } unsafe impl<T> TypedBufferAccess for T where T: SafeDeref, T::Target: TypedBufferAccess { type Content = <T::Target as TypedBufferAccess>::Content; }
use crate::{ cmd::*, result::Result, staking, traits::{TxnEnvelope, TxnSign}, }; #[derive(Debug, StructOpt)] /// Add a hotspot to the blockchain. The original transaction is created by the /// hotspot miner and supplied here for owner signing. Use an onboarding key to /// get the transaction signed by the DeWi staking server. pub struct Cmd { /// Base64 encoded transaction to sign. If no transaction is 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>, /// The onboarding key to use if the payer of the transaction fees /// is the DeWi "staking" server. #[structopt(long)] onboarding: Option<String>, #[structopt(long)] commit: bool, } impl Cmd { pub async fn run(self, opts: Opts) -> Result { let mut txn = BlockchainTxnAddGatewayV1::from_envelope(&read_txn(&self.txn)?)?; let password = get_password(false)?; let wallet = load_wallet(opts.files)?; let keypair = wallet.decrypt(password.as_bytes())?; let staking_client = staking::Client::default(); let client = new_client(api_url(wallet.public_key.network)); let wallet_key = keypair.public_key(); txn.owner_signature = txn.sign(&keypair)?; let envelope = match PublicKey::from_bytes(&txn.payer)? { key if &key == wallet_key => { txn.payer_signature = txn.owner_signature.clone(); Ok(txn.in_envelope()) } _key if self.onboarding.is_some() && self.commit => { // Only have staking server sign if there's an onboarding key, // and we're actually going to commit let onboarding_key = self.onboarding.as_ref().unwrap().replace("\"", ""); staking_client .sign(&onboarding_key, &txn.in_envelope()) .await } _key => Ok(txn.in_envelope()), }?; let status = maybe_submit_txn(self.commit, &client, &envelope).await?; print_txn(&txn, &status, opts.format) } } fn print_txn( txn: &BlockchainTxnAddGatewayV1, status: &Option<PendingTxnStatus>, format: OutputFormat, ) -> Result { let address = PublicKey::from_bytes(&txn.gateway)?.to_string(); let owner = PublicKey::from_bytes(&txn.owner)?.to_string(); let payer = if txn.payer.is_empty() { PublicKey::from_bytes(&txn.owner)?.to_string() } else { PublicKey::from_bytes(&txn.payer)?.to_string() }; match format { OutputFormat::Table => { ptable!( ["Key", "Value"], ["Address", address], ["Payer", payer], ["Owner", owner], ["Fee (DC)", txn.fee], ["Staking fee (DC)", txn.staking_fee], ["Hash", status_str(status)] ); print_footer(status) } OutputFormat::Json => { let table = json!({ "address": address, "owner": owner, "payer": payer, "fee": txn.fee, "staking fee": txn.staking_fee, "hash": status_json(status), "txn": txn.in_envelope().to_b64()? }); print_json(&table) } } }
const INPUT: &str = include_str!("../input"); #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct FourDimensionalPoint { x: isize, y: isize, z: isize, t: isize, } impl FourDimensionalPoint { fn from_input(input: &str) -> Self { let values: Vec<_> = input .split(',') .map(|s| s.parse()) .collect::<Result<Vec<_>, _>>() .unwrap(); FourDimensionalPoint { x: values[0], y: values[1], z: values[2], t: values[3], } } fn from_tuple((x, y, z, t): (isize, isize, isize, isize)) -> Self { FourDimensionalPoint { x, y, z, t } } fn manhattan_distance(&self, other: &Self) -> usize { let dx = (self.x - other.x).abs(); let dy = (self.y - other.y).abs(); let dz = (self.z - other.z).abs(); let dt = (self.t - other.t).abs(); (dx + dy + dz + dt) as usize } } fn find_constellations(points: &[FourDimensionalPoint]) -> Vec<Vec<FourDimensionalPoint>> { let mut points = points.to_vec(); let min_point = *points.iter().min_by_key(|p| p.x + p.y + p.z + p.t).unwrap(); points.sort_by_key(|p| p.manhattan_distance(&min_point)); let mut constellations: Vec<Vec<FourDimensionalPoint>> = vec![]; for &point in points.iter() { let (ref indices, ref mut joinable): (Vec<_>, Vec<_>) = constellations .iter_mut() .enumerate() .filter(|(_, c)| c.iter().any(|p| point.manhattan_distance(p) <= 3)) .unzip(); if joinable.is_empty() { constellations.push(vec![point]); } else if joinable.len() > 1 { let mut new_constellation = vec![point]; new_constellation.extend(joinable.iter().flat_map(|c| c.iter())); for &i in indices.iter().rev() { constellations.remove(i); } constellations.push(new_constellation); } else { joinable[0].push(point); } } constellations } fn parse_input(input: &str) -> Vec<FourDimensionalPoint> { input .lines() .map(FourDimensionalPoint::from_input) .collect() } fn solve_part_one(points: &[FourDimensionalPoint]) -> usize { let constellations = find_constellations(points); constellations.len() } fn main() { let points = parse_input(INPUT); println!("{}", solve_part_one(&points)); } #[cfg(test)] mod test { use super::*; type Sample = (&'static str, &'static str, usize); const SAMPLE_A: Sample = ("A", include_str!("../sample-a"), 2); const SAMPLE_B: Sample = ("B", include_str!("../sample-b"), 4); const SAMPLE_C: Sample = ("C", include_str!("../sample-c"), 3); const SAMPLE_D: Sample = ("D", include_str!("../sample-d"), 8); #[test] fn it_solves_part_one_samples_correctly() { let samples = [SAMPLE_A, SAMPLE_B, SAMPLE_C, SAMPLE_D]; for &(name, input, answer) in samples.iter() { let points = parse_input(input); assert_eq!( solve_part_one(&points), answer, "failed for sample {}", name ); } } }
// 17.2 Shuffle // Does 51 swaps, similar to quicksort fn shuffle(generator: &dyn Fn() -> usize) -> Vec<usize> { let mut numbers = (0..52).collect::<Vec<_>>(); for i in (1..52).rev() { let chosen_index = generator() % (i + 1); numbers.swap(chosen_index, i); } numbers } #[test] fn test() { use rand::random; println!("Ex 17.2: Generated: {:?}", shuffle(&random::<usize>)); }
pub mod simple; pub mod subpixel;
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use super::{trace::TraceTable, ProverError, StarkDomain}; mod boundary; use boundary::BoundaryConstraintGroup; mod periodic_table; use periodic_table::PeriodicValueTable; mod evaluator; pub use evaluator::ConstraintEvaluator; mod composition_poly; pub use composition_poly::CompositionPoly; mod evaluation_table; pub use evaluation_table::ConstraintEvaluationTable; mod commitment; pub use commitment::ConstraintCommitment;
extern crate civ; use civ::logger; fn main() { match logger::init() { Ok(_) => {}, Err(e) => println!("Could not init logger: {}", e) } }
use resol_vbus::{Data, Datagram, Header}; use tokio::net::TcpListener; use tokio::prelude::*; use tokio_resol_vbus::{LiveDataStream, Result, TcpServerHandshake}; fn main() -> Result<()> { let addr = "127.0.0.1:7053".parse().expect("Unable to parse address"); let listener = TcpListener::bind(&addr).expect("Unable to bind listener"); let server = listener .incoming() .map_err(|err| eprintln!("{}", err)) .for_each(|socket| { let conn = TcpServerHandshake::start(socket) .and_then(|hs| { hs.receive_pass_command_and_verify_password(|password| { if password == "vbus" { Ok(Some(password)) } else { Ok(None) } }) }) .and_then(|(hs, _)| hs.receive_data_command()) .and_then(|socket| { let (reader, writer) = socket.split(); let stream = LiveDataStream::new(reader, writer, 0, 0x7E11); future::loop_fn(stream, |stream| { let tx_data = Data::Datagram(Datagram { header: Header { destination_address: 0x0000, source_address: 0x7E11, protocol_version: 0x20, ..Header::default() }, command: 0x0500, param16: 0, param32: 0, }); stream .transceive(tx_data, 1, 1000, 0, |data| { data.as_ref().destination_address == 0x7E11 }) .and_then(|(stream, data)| { println!("{:?}", data); Ok(future::Loop::Continue(stream)) }) }) }) .map_err(|err| { panic!("Server error: {}", err); }); tokio::spawn(conn) }); tokio::run(server); Ok(()) }
use crate::ast::{Statement, Value}; use crate::environment::Environment; use crate::interpreter::{ErrorType, Interpreter}; use crate::token::Token; use std::cell::{Ref, RefCell, RefMut}; use std::fmt; use std::fmt::Debug; use std::rc::Rc; #[derive(Clone, Debug)] pub struct LoxFunction<'a> { data: Rc<RefCell<LoxFunctionImpl<'a>>>, } #[derive(Debug)] struct LoxFunctionImpl<'a> { name: &'a Token<'a>, params: Vec<&'a Token<'a>>, body: Vec<Statement<'a>>, } impl<'a> fmt::Display for LoxFunction<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "<fn {}>", self.name().lexeme) } } impl<'a> LoxFunction<'a> { pub fn new( name: &'a Token, params: Vec<&'a Token>, body: Vec<Statement<'a>>, ) -> LoxFunction<'a> { LoxFunction { data: Rc::new(RefCell::new(LoxFunctionImpl { name, params, body })), } } pub fn call( &self, interpreter: &mut Interpreter<'a>, arguments: &Vec<Value<'a>>, closure: Environment<'a>, is_initializer: bool, ) -> Result<Value<'a>, ErrorType<'a>> { let mut environment = closure.new_child(); for param_and_val in self.params().iter().zip(arguments.iter()) { environment.define(param_and_val.0.lexeme.to_string(), param_and_val.1.clone())?; } let result = interpreter.execute_block(&*self.body(), environment); match result { Err(e) => match e { ErrorType::Return(r) => { if is_initializer { Ok(closure.get_this()?) } else { Ok(r.0) } } _ => Err(e), }, Ok(_) => { if is_initializer { Ok(closure.get_this()?) } else { Ok(Value::Nil) } } } } pub fn arity(&self) -> usize { self.data.borrow().params.len() } pub fn name(&self) -> Ref<&'a Token<'a>> { Ref::map(self.data.borrow(), |data| &data.name) } pub fn params(&self) -> Ref<Vec<&'a Token<'a>>> { Ref::map(self.data.borrow(), |data| &data.params) } pub fn body(&self) -> Ref<Vec<Statement<'a>>> { Ref::map(self.data.borrow(), |data| &data.body) } pub fn body_mut(&mut self) -> RefMut<Vec<Statement<'a>>> { RefMut::map(self.data.borrow_mut(), |data| &mut data.body) } pub fn equals(&self, other: &LoxFunction<'a>) -> bool { Rc::ptr_eq(&self.data, &other.data) } } #[derive(Clone)] pub struct NativeFunction<'a> { pub call: fn(&Vec<Value<'a>>) -> Value<'a>, pub arity: usize, } impl<'a> Debug for NativeFunction<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "<native fn>") } } impl<'a> fmt::Display for NativeFunction<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "<native fn>") } }
#[cfg(feature = "client")] use graphics::Context; #[cfg(feature = "client")] use opengl_graphics::Gl; use battle_state::BattleContext; use module; use module::{IModule, Module, ModuleBase, ModuleRef}; use net::{InPacket, OutPacket}; use ship::{ShipRef, ShipState}; use sim::SimEventAdder; use vec::{Vec2, Vec2f}; #[cfg(feature = "client")] use sim_visuals::SpriteVisual; #[cfg(feature = "client")] use sim::{SimEffects, SimVisual}; #[cfg(feature = "client")] use sprite_sheet::{SpriteSheet, SpriteAnimation}; #[cfg(feature = "client")] use asset_store::AssetStore; #[derive(RustcEncodable, RustcDecodable, Clone)] pub struct SolarModule; impl SolarModule { pub fn new() -> Module<SolarModule> { Module { base: ModuleBase::new(1, 1, 0, 2, 3), module: SolarModule, } } } impl IModule for SolarModule { fn server_preprocess(&mut self, base: &mut ModuleBase, ship_state: &mut ShipState) { } fn before_simulation(&mut self, base: &mut ModuleBase, ship: &ShipRef, events: &mut SimEventAdder) { } #[cfg(feature = "client")] fn add_plan_effects(&self, base: &ModuleBase, asset_store: &AssetStore, effects: &mut SimEffects, ship: &ShipRef) { let mut solar_sprite = SpriteSheet::new(asset_store.get_sprite_info_str("modules/solar_panel_sprite.png")); if base.is_active() { solar_sprite.add_animation(SpriteAnimation::Loop(0.0, 7.0, 1, 4, 0.1)); } else { solar_sprite.add_animation(SpriteAnimation::Stay(0.0, 7.0, 0)); } effects.add_visual(ship.borrow().id, 0, box SpriteVisual { position: base.get_render_position().clone(), sprite_sheet: solar_sprite, }); } #[cfg(feature = "client")] fn add_simulation_effects(&self, base: &ModuleBase, asset_store: &AssetStore, effects: &mut SimEffects, ship: &ShipRef) { self.add_plan_effects(base, asset_store, effects, ship); } fn after_simulation(&mut self, base: &mut ModuleBase, ship_state: &mut ShipState) { } fn on_activated(&mut self, base: &mut ModuleBase, ship_state: &mut ShipState, modules: &Vec<ModuleRef>) { ship_state.add_power(5); } fn on_deactivated(&mut self, base: &mut ModuleBase, ship_state: &mut ShipState, modules: &Vec<ModuleRef>) { ship_state.remove_power(5, modules); } fn get_target_mode(&self, base: &ModuleBase) -> Option<module::TargetMode> { None } }
use super::*; use num_traits::{Float}; use num_complex::{Complex as NumComplex}; impl<T: Float> Complex<T> { /// Convert into `num_complex::Complex` struct. pub fn into_num(self) -> NumComplex<T> { Into::<NumComplex<_>>::into(self) } /// Calculate the principal Arg of self. pub fn arg(self) -> T { self.into_num().arg() } /// Computes `e^(self)`, where `e` is the base of the natural logarithm. pub fn exp(self) -> Self { self.into_num().exp().into() } /// Computes the principal value of natural logarithm of `self`. pub fn ln(self) -> Self { self.into_num().ln().into() } /// Computes the principal value of the square root of `self`. pub fn sqrt(self) -> Self { self.into_num().sqrt().into() } /// Computes the principal value of the cube root of `self`. /// /// Note that this does not match the usual result for the cube root of negative real numbers. /// For example, the real cube root of `-8` is `-2`, but the principal complex cube root of `-8` is `1 + i√3`. pub fn cbrt(self) -> Self { self.into_num().cbrt().into() } /// Raises `self` to an unsigned integer power. pub fn powu(self, exp: u32) -> Self { self.into_num().powu(exp).into() } /// Raises `self` to a signed integer power. pub fn powi(self, exp: i32) -> Self { self.into_num().powi(exp).into() } /// Raises `self` to a floating point power. pub fn powf(self, exp: T) -> Self { self.into_num().powf(exp).into() } /// Raises `self` to a complex power. pub fn powc(self, exp: Self) -> Self { self.into_num().powc(exp.into_num()).into() } /// Returns the logarithm of `self` with respect to an arbitrary base. pub fn log(self, base: T) -> Self { self.into_num().log(base).into() } /// Raises a floating point number to the complex power `self`. pub fn expf(self, base: T) -> Self { self.into_num().expf(base).into() } /// Computes the sine of `self`. pub fn sin(self) -> Self { self.into_num().sin().into() } /// Computes the cosine of `self`. pub fn cos(self) -> Self { self.into_num().cos().into() } /// Computes the tangent of `self`. pub fn tan(self) -> Self { self.into_num().tan().into() } /// Computes the principal value of the inverse sine of `self`. pub fn asin(self) -> Self { self.into_num().asin().into() } /// Computes the principal value of the inverse cosine of `self`. pub fn acos(self) -> Self { self.into_num().acos().into() } /// Computes the principal value of the inverse tangent of `self`. pub fn atan(self) -> Self { self.into_num().atan().into() } /// Computes the hyperbolic sine of `self`. pub fn sinh(self) -> Self { self.into_num().sinh().into() } /// Computes the hyperbolic cosine of `self`. pub fn cosh(self) -> Self { self.into_num().cosh().into() } /// Computes the hyperbolic tangent of `self`. pub fn tanh(self) -> Self { self.into_num().tanh().into() } /// Computes the principal value of the inverse hyperbolic sine of `self`. pub fn asinh(self) -> Self { self.into_num().asinh().into() } /// Computes the principal value of the inverse hyperbolic cosine of `self`. pub fn acosh(self) -> Self { self.into_num().acosh().into() } /// Computes the principal value of the inverse hyperbolic tangent of `self`. pub fn atanh(self) -> Self { self.into_num().atanh().into() } /// Returns `1/self` using floating-point operations. pub fn finv(self) -> Self { self.into_num().finv().into() } } impl<T: Float + Clone> Complex<T> where Self: Norm<Output=T> { /// Convert to polar form. pub fn to_polar(self) -> (T, T) { (self.norm(), self.arg()) } /// Convert a polar representation into a complex number. pub fn from_polar(r: T, theta: T) -> Self { Self::new(T::zero(), theta).exp() * r } }
#![feature(std_misc, negate_unsigned, dynamic_lib)] extern crate gl; extern crate glfw; extern crate libc; #[cfg(windows)] pub mod win32; #[cfg(windows)] use win32 as platform; #[cfg(target_os = "linux")] pub mod linux; #[cfg(target_os = "linux")] use linux as platform; #[cfg(target_os = "macos")] pub mod osx; #[cfg(target_os = "macos")] use osx as platform; use std::path::Path; use std::fs; use glfw::{Context}; use libc::c_void; use std::dynamic_lib::DynamicLibrary; use std::thread; // use std::c_str::ToCStr; use std::mem::{transmute, uninitialized, drop}; use std::sync::mpsc::channel; use std::sync::mpsc::Receiver; type LoadFn = extern "C" fn ( bool, // first load? &mut u8, // GameData &mut u8, // GLData &glfw::Glfw, &glfw::Window, *const c_void // glfw _data ); type UpdateFn = extern "C" fn ( &mut u8, // GameData &mut u8, // GLData f32, // delta time &glfw::Glfw, &glfw::Window, &Receiver<(f64, glfw::WindowEvent)>, i64 ); // Glfw shit extern "C" { pub static _glfw: *const c_void; } fn copy_game_lib_to_cwd() { match fs::copy(platform::GAME_LIB_PATH, platform::GAME_LIB_FILE) { Err(e) => panic!("Couldn't copy {}: {}", platform::GAME_LIB_PATH, e), _ => {} } } fn load_game_lib() -> DynamicLibrary { let dylib_path = Path::new(platform::GAME_LIB_FILE); match DynamicLibrary::open(Some(dylib_path)) { Ok(lib) => lib, Err(e) => panic!("Couldn't load game lib: {}", e) } } fn load_symbols_from(lib: &DynamicLibrary) -> (LoadFn, UpdateFn) { unsafe { let load: LoadFn = match lib.symbol::<u8>("load") { Ok(f) => transmute(f), Err(e) => panic!("Couldn't grab update symbol from game lib! {}", e) }; let update: UpdateFn = match lib.symbol::<u8>("update") { Ok(f) => transmute(f), Err(e) => panic!("Couldn't grab load symbol from game lib! {}", e) }; (load, update) } } fn main() { let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); let (mut window, events) = glfw .create_window(500, 500, "Hello this is window", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window."); gl::load_with(|s| window.get_proc_address(s)); window.set_key_polling(true); window.set_size_polling(true); window.make_current(); let mut game_memory = unsafe { Box::new([uninitialized::<u8>(); 4096]) }; let mut gl_memory = unsafe { Box::new([uninitialized::<u8>(); 1024]) }; copy_game_lib_to_cwd(); let mut game_lib = load_game_lib(); let (mut load, mut update) = load_symbols_from(&game_lib); let (game_lib_sender, game_lib_receiver) = channel(); unsafe { let _t = thread::Builder::new().name("Game Lib Updater".to_string()).spawn( move || platform::watch_for_updated_game_lib(&game_lib_sender) ); load( true, transmute(&mut game_memory[0]), transmute(&mut gl_memory[0]), &glfw, &window, _glfw ); } let mut last_frame_time = 0i64; let mut this_frame_time = 0i64; let ticks_per_second = platform::query_performance_frequency() as f32; while !window.should_close() { unsafe { platform::query_performance_counter(&mut this_frame_time); match game_lib_receiver.try_recv() { Ok(()) => { drop(game_lib); copy_game_lib_to_cwd(); game_lib = load_game_lib(); match load_symbols_from(&game_lib) { (l, u) => { load = l; update = u } } load( false, transmute(&mut game_memory[0]), transmute(&mut gl_memory[0]), &glfw, &window, _glfw ); } _ => {} } let delta_time = if last_frame_time <= 0 { 1.0/60.0 } else { ((this_frame_time - last_frame_time) as f32) / ticks_per_second }; update( transmute(&mut game_memory[0]), transmute(&mut gl_memory[0]), delta_time, &glfw, &window, &events, this_frame_time ); last_frame_time = this_frame_time; } } }
use crate::AddAsHeader; use bytes::Bytes; use http::request::Builder; use http::HeaderMap; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct Metadata(HashMap<String, Bytes>); impl Default for Metadata { fn default() -> Self { Self::new() } } impl AsMut<HashMap<String, Bytes>> for Metadata { fn as_mut(&mut self) -> &mut HashMap<String, Bytes> { &mut self.0 } } impl Metadata { pub fn new() -> Self { Self(HashMap::new()) } pub fn insert<K, V>(&mut self, k: K, v: V) -> Option<Bytes> where K: Into<String>, V: Into<Bytes>, { self.0.insert(k.into(), v.into()) } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn get(&self, k: &str) -> Option<Bytes> { self.0.get(k).cloned() } } impl AddAsHeader for &Metadata { fn add_as_header(&self, builder: Builder) -> Builder { let mut builder = builder; for (key, val) in self.0.iter() { builder = builder.header(&format!("x-ms-meta-{}", key), val.as_ref()); } builder } fn add_as_header2( &self, request: &mut crate::Request, ) -> Result<(), crate::errors::HTTPHeaderError> { for (key, value) in self.0.iter() { let header_name = http::header::HeaderName::from_bytes(format!("x-ms-meta-{}", key).as_bytes())?; let header_value = http::header::HeaderValue::from_bytes(value)?; request.headers_mut().append(header_name, header_value); } Ok(()) } } impl From<&HeaderMap> for Metadata { fn from(header_map: &HeaderMap) -> Self { let mut metadata = Metadata::new(); header_map .iter() .map(|header| (header.0.as_str(), header.1.as_bytes())) .filter(|(key, _)| key.starts_with("x-ms-meta-")) .for_each(|(key, value)| { metadata.insert( key.strip_prefix("x-ms-meta-").unwrap().to_owned(), value.to_owned(), ); }); metadata } }
//! This example demonstrates using the powerful [`static_table!`] macro to translate //! a sequence of arrays and several, optional settings to a static [`str`] table representation. //! //! * Note that [`static_table!`] is evaluated at compile time, resulting in highly efficient runtime performance. //! * [`static_table!`] supports configuration of: //! * granular column and row span specification //! * [`THEME`](tabled::settings::Style) //! * [`ALIGNMENT`](tabled::settings::Alignment) //! * [`PADDING`](`tabled::settings::Padding`) //! * [`MARGIN`](tabled::settings::Margin) use static_table::static_table; static LANG_LIST: &str = static_table!([ ["name", "designed by", "first release"], ["C", "Dennis Ritchie", "1972"], ["Go", "Rob Pike", "2009"], ["Rust", "Graydon Hoare", "2010"], ]); fn main() { println!("{LANG_LIST}") }
fn last_digit(lst: &[u64]) -> u64 { if lst.len() == 0 { return 1; } let mut n: u128 = 1; for i in (0..lst.len()).rev() { if n < 4 { n = ((lst[i] % 1000) as u128).pow(n as u32); } else { n = ((lst[i] % 1000) as u128).pow((n % 4 + 4) as u32); } } (n % 10) as u64 } #[test] fn test0() { assert_eq!(last_digit(&vec![]), 1); } #[test] fn test1() { assert_eq!(last_digit(&vec![0, 0]), 1); } #[test] fn test2() { assert_eq!(last_digit(&vec![0, 0, 0]), 0); } #[test] fn test3() { assert_eq!(last_digit(&vec![1, 2]), 1); } #[test] fn test4() { assert_eq!(last_digit(&vec![3, 4, 5]), 1); } #[test] fn test5() { assert_eq!(last_digit(&vec![1,2,3,4,5]), 1); } #[test] fn test6() { assert_eq!(last_digit(&vec![1,2,3,4,5,6,7,8,9,0]), 1); } #[test] fn test7() { assert_eq!(last_digit(&vec![937640, 767456, 981242]), 0); } #[test] fn test8() { assert_eq!(last_digit(&vec![123232, 694022, 140249]), 6); } #[test] fn test9() { assert_eq!(last_digit(&vec![499942, 898102, 846073]), 6); } fn main() { }
#![feature(rustc_attrs)] #[rustc_layout_scalar_valid_range_start(u32::MAX)] //~ ERROR pub struct A(u32); #[rustc_layout_scalar_valid_range_end(1, 2)] //~ ERROR pub struct B(u8); #[rustc_layout_scalar_valid_range_end(a = "a")] //~ ERROR pub struct C(i32); #[rustc_layout_scalar_valid_range_end(1)] //~ ERROR enum E { X = 1, Y = 14, } fn main() { let _ = A(0); let _ = B(0); let _ = C(0); let _ = E::X; }
//! Different kinds of render passes. // pub use self::flat::DrawFlat; pub use self::pbm::DrawPbm; pub use self::shaded::DrawShaded; mod flat; mod pbm; mod shaded;
// Copyright 2019. The Tari Project // SPDX-License-Identifier: BSD-3-Clause //! Pedersen commitment types and factories for Ristretto use curve25519_dalek::{ ristretto::RistrettoPoint, traits::{Identity, MultiscalarMul}, }; #[cfg(feature = "precomputed_tables")] use crate::ristretto::pedersen::scalar_mul_with_pre_computation_tables; use crate::{ commitment::{HomomorphicCommitment, HomomorphicCommitmentFactory}, ristretto::{ pedersen::{ristretto_pedersen_h, PedersenCommitment, RISTRETTO_PEDERSEN_G}, RistrettoPublicKey, RistrettoSecretKey, }, }; /// Generates Pederson commitments `k.G + v.H` using the provided base /// [RistrettoPoints](curve25519_dalek::ristretto::RistrettoPoint). #[derive(Debug, PartialEq, Eq, Clone)] #[allow(non_snake_case)] pub struct PedersenCommitmentFactory { pub(crate) G: RistrettoPoint, pub(crate) H: RistrettoPoint, } impl PedersenCommitmentFactory { /// Create a new Ristretto Commitment factory with the given points as the bases. It's very cheap to create /// factories, since we only hold references to the static generator points. #[allow(non_snake_case)] pub fn new(G: RistrettoPoint, H: RistrettoPoint) -> PedersenCommitmentFactory { PedersenCommitmentFactory { G, H } } } impl Default for PedersenCommitmentFactory { /// The default Ristretto Commitment factory uses the Base point for x25519 and its first Blake256 hash. fn default() -> Self { PedersenCommitmentFactory::new(RISTRETTO_PEDERSEN_G, *ristretto_pedersen_h()) } } impl HomomorphicCommitmentFactory for PedersenCommitmentFactory { type P = RistrettoPublicKey; #[allow(non_snake_case)] fn commit(&self, k: &RistrettoSecretKey, v: &RistrettoSecretKey) -> PedersenCommitment { // If we're using the default generators, speed it up using pre-computation tables let c = if (self.G, self.H) == (RISTRETTO_PEDERSEN_G, *ristretto_pedersen_h()) { #[cfg(feature = "precomputed_tables")] { scalar_mul_with_pre_computation_tables(&k.0, &v.0) } #[cfg(not(feature = "precomputed_tables"))] { RistrettoPoint::multiscalar_mul(&[v.0, k.0], &[self.H, self.G]) } } else { RistrettoPoint::multiscalar_mul(&[v.0, k.0], &[self.H, self.G]) }; HomomorphicCommitment(RistrettoPublicKey::new_from_pk(c)) } fn zero(&self) -> PedersenCommitment { HomomorphicCommitment(RistrettoPublicKey::new_from_pk(RistrettoPoint::identity())) } fn open(&self, k: &RistrettoSecretKey, v: &RistrettoSecretKey, commitment: &PedersenCommitment) -> bool { let c_test = self.commit(k, v); commitment.0 == c_test.0 } fn commit_value(&self, k: &RistrettoSecretKey, value: u64) -> PedersenCommitment { let v = RistrettoSecretKey::from(value); self.commit(k, &v) } fn open_value(&self, k: &RistrettoSecretKey, v: u64, commitment: &PedersenCommitment) -> bool { let kv = RistrettoSecretKey::from(v); self.open(k, &kv, commitment) } } #[cfg(test)] mod test { use alloc::vec::Vec; use std::{ collections::hash_map::DefaultHasher, convert::From, hash::{Hash, Hasher}, }; use curve25519_dalek::scalar::Scalar; use super::*; use crate::{ commitment::HomomorphicCommitmentFactory, keys::{PublicKey, SecretKey}, ristretto::{pedersen::commitment_factory::PedersenCommitmentFactory, RistrettoSecretKey}, }; #[test] fn check_default_base() { let base = PedersenCommitmentFactory::default(); assert_eq!(base.G, RISTRETTO_PEDERSEN_G); assert_eq!(base.H, *ristretto_pedersen_h()) } #[test] /// Verify that the identity point is equal to a commitment to zero with a zero blinding factor on the base point fn check_zero() { let c = RistrettoPoint::multiscalar_mul(&[Scalar::ZERO, Scalar::ZERO], &[ RISTRETTO_PEDERSEN_G, *ristretto_pedersen_h(), ]); let factory = PedersenCommitmentFactory::default(); assert_eq!( HomomorphicCommitment(RistrettoPublicKey::new_from_pk(c)), PedersenCommitmentFactory::zero(&factory) ); } /// Simple test for open: Generate 100 random sets of scalars and calculate the Pedersen commitment for them. /// Then check that the commitment = k.G + v.H, and that `open` returns `true` for `open(&k, &v)` #[test] #[allow(non_snake_case)] fn check_open() { let factory = PedersenCommitmentFactory::default(); let H = *ristretto_pedersen_h(); let mut rng = rand::thread_rng(); for _ in 0..100 { let v = RistrettoSecretKey::random(&mut rng); let k = RistrettoSecretKey::random(&mut rng); let c = factory.commit(&k, &v); let c_calc: RistrettoPoint = v.0 * H + k.0 * RISTRETTO_PEDERSEN_G; assert_eq!(RistrettoPoint::from(c.as_public_key()), c_calc); assert!(factory.open(&k, &v, &c)); // A different value doesn't open the commitment assert!(!factory.open(&k, &(&v + &v), &c)); // A different blinding factor doesn't open the commitment assert!(!factory.open(&(&k + &v), &v, &c)); } } /// Test, for 100 random sets of scalars that the homomorphic property holds. i.e. /// $$ /// C = C_1 + C_2 = (k_1+k_2).G + (v_1+v_2).H /// $$ /// and /// `open(k1+k2, v1+v2)` is true for _C_ #[test] fn check_homomorphism() { let mut rng = rand::thread_rng(); for _ in 0..100 { let v1 = RistrettoSecretKey::random(&mut rng); let v2 = RistrettoSecretKey::random(&mut rng); let v_sum = &v1 + &v2; let k1 = RistrettoSecretKey::random(&mut rng); let k2 = RistrettoSecretKey::random(&mut rng); let k_sum = &k1 + &k2; let factory = PedersenCommitmentFactory::default(); let c1 = factory.commit(&k1, &v1); let c2 = factory.commit(&k2, &v2); let c_sum = &c1 + &c2; let c_sum2 = factory.commit(&k_sum, &v_sum); assert!(factory.open(&k1, &v1, &c1)); assert!(factory.open(&k2, &v2, &c2)); assert_eq!(c_sum, c_sum2); assert!(factory.open(&k_sum, &v_sum, &c_sum)); } } /// Test addition of a public key to a homomorphic commitment. /// $$ /// C = C_1 + P = (v_1.H + k_1.G) + k_2.G = v_1.H + (k_1 + k_2).G /// $$ /// and /// `open(k1+k2, v1)` is true for _C_ #[test] fn check_homomorphism_with_public_key() { let mut rng = rand::thread_rng(); // Left-hand side let v1 = RistrettoSecretKey::random(&mut rng); let k1 = RistrettoSecretKey::random(&mut rng); let factory = PedersenCommitmentFactory::default(); let c1 = factory.commit(&k1, &v1); let (k2, k2_pub) = RistrettoPublicKey::random_keypair(&mut rng); let c_sum = &c1 + &k2_pub; // Right-hand side let c2 = factory.commit(&(&k1 + &k2), &v1); // Test assert_eq!(c_sum, c2); assert!(factory.open(&(&k1 + &k2), &v1, &c2)); } /// Test addition of individual homomorphic commitments to be equal to a single vector homomorphic commitment. /// $$ /// sum(C_j) = sum((v.H + k.G)_j) = sum(v_j).H + sum(k_j).G /// $$ /// and /// `open(sum(k_j), sum(v_j))` is true for `sum(C_j)` #[test] fn sum_commitment_vector() { let mut rng = rand::thread_rng(); let mut v_sum = RistrettoSecretKey::default(); let mut k_sum = RistrettoSecretKey::default(); let zero = RistrettoSecretKey::default(); let commitment_factory = PedersenCommitmentFactory::default(); let mut c_sum = commitment_factory.commit(&zero, &zero); let mut commitments = Vec::with_capacity(100); for _ in 0..100 { let v = RistrettoSecretKey::random(&mut rng); v_sum = &v_sum + &v; let k = RistrettoSecretKey::random(&mut rng); k_sum = &k_sum + &k; let c = commitment_factory.commit(&k, &v); c_sum = &c_sum + &c; commitments.push(c); } assert!(commitment_factory.open(&k_sum, &v_sum, &c_sum)); assert_eq!(c_sum, commitments.iter().sum()); } #[cfg(feature = "serde")] #[test] fn serialize_deserialize() { use tari_utilities::message_format::MessageFormat; let mut rng = rand::thread_rng(); let factory = PedersenCommitmentFactory::default(); let k = RistrettoSecretKey::random(&mut rng); let c = factory.commit_value(&k, 420); // Base64 let ser_c = c.to_base64().unwrap(); let c2 = PedersenCommitment::from_base64(&ser_c).unwrap(); assert!(factory.open_value(&k, 420, &c2)); // MessagePack let ser_c = c.to_binary().unwrap(); let c2 = PedersenCommitment::from_binary(&ser_c).unwrap(); assert!(factory.open_value(&k, 420, &c2)); // Invalid Base64 assert!(PedersenCommitment::from_base64("bad@ser$").is_err()); } #[test] #[allow(clippy::redundant_clone)] fn derived_methods() { let factory = PedersenCommitmentFactory::default(); let k = RistrettoSecretKey::from(1024); let value = 2048; let c1 = factory.commit_value(&k, value); // Test 'Debug' implementation assert_eq!( format!("{c1:?}"), "HomomorphicCommitment(601cdc5c97e94bb16ae56f75430f8ab3ef4703c7d89ca9592e8acadc81629f0e)" ); // Test 'Clone' implementation let c2 = c1.clone(); assert_eq!(c1, c2); // Test hash implementation let mut hasher = DefaultHasher::new(); c1.hash(&mut hasher); let result = format!("{:x}", hasher.finish()); assert_eq!(&result, "699d38210741194e"); // Test 'Ord' and 'PartialOrd' implementations let mut values = (value - 100..value).collect::<Vec<_>>(); values.extend((value + 1..value + 101).collect::<Vec<_>>()); let (mut tested_less_than, mut tested_greater_than) = (false, false); for val in values { let c3 = factory.commit_value(&k, val); assert_ne!(c2, c3); assert_ne!(c2.cmp(&c3), c3.cmp(&c2)); if c2 > c3 { assert!(c3 < c2); assert!(matches!(c2.cmp(&c3), std::cmp::Ordering::Greater)); assert!(matches!(c3.cmp(&c2), std::cmp::Ordering::Less)); tested_less_than = true; } if c2 < c3 { assert!(c3 > c2); assert!(matches!(c2.cmp(&c3), std::cmp::Ordering::Less)); assert!(matches!(c3.cmp(&c2), std::cmp::Ordering::Greater)); tested_greater_than = true; } if tested_less_than && tested_greater_than { break; } } assert!( tested_less_than && tested_greater_than, "Try extending the range of values to compare" ); } }
//! Floating Point Unit //! //! *NOTE* Available only on targets with a Floating Point Unit (FPU) extension. use volatile_register::{RO, RW}; /// Register block #[repr(C)] pub struct RegisterBlock { reserved: u32, /// Floating Point Context Control pub fpccr: RW<u32>, /// Floating Point Context Address pub fpcar: RW<u32>, /// Floating Point Default Status Control pub fpdscr: RW<u32>, /// Media and FP Feature pub mvfr: [RO<u32>; 3], }
use crate::utils::get_fl_name; use proc_macro::TokenStream; use quote::*; use syn::*; pub fn impl_browser_trait(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let name_str = get_fl_name(name.to_string()); let remove = Ident::new(format!("{}_{}", name_str, "remove").as_str(), name.span()); let add = Ident::new(format!("{}_{}", name_str, "add").as_str(), name.span()); let insert = Ident::new(format!("{}_{}", name_str, "insert").as_str(), name.span()); let move_item = Ident::new(format!("{}_{}", name_str, "move").as_str(), name.span()); let swap = Ident::new(format!("{}_{}", name_str, "swap").as_str(), name.span()); let clear = Ident::new(format!("{}_{}", name_str, "clear").as_str(), name.span()); let size = Ident::new(format!("{}_{}", name_str, "size").as_str(), name.span()); let set_size = Ident::new(format!("{}_{}", name_str, "set_size").as_str(), name.span()); let select = Ident::new(format!("{}_{}", name_str, "select").as_str(), name.span()); let selected = Ident::new(format!("{}_{}", name_str, "selected").as_str(), name.span()); let text = Ident::new(format!("{}_{}", name_str, "text").as_str(), name.span()); let set_text = Ident::new(format!("{}_{}", name_str, "set_text").as_str(), name.span()); let load_file = Ident::new( format!("{}_{}", name_str, "load_file").as_str(), name.span(), ); let text_size = Ident::new( format!("{}_{}", name_str, "text_size").as_str(), name.span(), ); let set_text_size = Ident::new( format!("{}_{}", name_str, "set_text_size").as_str(), name.span(), ); let set_icon = Ident::new(format!("{}_{}", name_str, "set_icon").as_str(), name.span()); let icon = Ident::new(format!("{}_{}", name_str, "icon").as_str(), name.span()); let remove_icon = Ident::new( format!("{}_{}", name_str, "remove_icon").as_str(), name.span(), ); let topline = Ident::new(format!("{}_{}", name_str, "topline").as_str(), name.span()); let middleline = Ident::new( format!("{}_{}", name_str, "middleline").as_str(), name.span(), ); let bottomline = Ident::new( format!("{}_{}", name_str, "bottomline").as_str(), name.span(), ); let format_char = Ident::new( format!("{}_{}", name_str, "format_char").as_str(), name.span(), ); let set_format_char = Ident::new( format!("{}_{}", name_str, "set_format_char").as_str(), name.span(), ); let column_char = Ident::new( format!("{}_{}", name_str, "column_char").as_str(), name.span(), ); let set_column_char = Ident::new( format!("{}_{}", name_str, "set_column_char").as_str(), name.span(), ); let column_widths = Ident::new( format!("{}_{}", name_str, "column_widths").as_str(), name.span(), ); let set_column_widths = Ident::new( format!("{}_{}", name_str, "set_column_widths").as_str(), name.span(), ); let displayed = Ident::new( format!("{}_{}", name_str, "displayed").as_str(), name.span(), ); let make_visible = Ident::new( format!("{}_{}", name_str, "make_visible").as_str(), name.span(), ); let position = Ident::new(format!("{}_{}", name_str, "position").as_str(), name.span()); let set_position = Ident::new( format!("{}_{}", name_str, "set_position").as_str(), name.span(), ); let hposition = Ident::new( format!("{}_{}", name_str, "hposition").as_str(), name.span(), ); let set_hposition = Ident::new( format!("{}_{}", name_str, "set_hposition").as_str(), name.span(), ); let has_scrollbar = Ident::new( format!("{}_{}", name_str, "has_scrollbar").as_str(), name.span(), ); let set_has_scrollbar = Ident::new( format!("{}_{}", name_str, "set_has_scrollbar").as_str(), name.span(), ); let scrollbar_size = Ident::new( format!("{}_{}", name_str, "scrollbar_size").as_str(), name.span(), ); let set_scrollbar_size = Ident::new( format!("{}_{}", name_str, "set_scrollbar_size").as_str(), name.span(), ); let sort = Ident::new(format!("{}_{}", name_str, "sort").as_str(), name.span()); let scrollbar = Ident::new( format!("{}_{}", name_str, "scrollbar").as_str(), name.span(), ); let hscrollbar = Ident::new( format!("{}_{}", name_str, "hscrollbar").as_str(), name.span(), ); let value = Ident::new(format!("{}_{}", name_str, "value").as_str(), name.span()); let gen = quote! { unsafe impl BrowserExt for #name { fn remove(&mut self, line: i32) { unsafe { assert!(!self.was_deleted()); #remove(self.inner, line as i32) } } fn add(&mut self, item: &str) { assert!(!self.was_deleted()); let item = CString::safe_new(item); unsafe { #add(self.inner, item.as_ptr()) } } fn insert(&mut self, line: i32, item: &str) { assert!(!self.was_deleted()); let item = CString::safe_new(item); unsafe { #insert(self.inner, line as i32, item.as_ptr()) } } fn move_item(&mut self, to: i32, from: i32) { assert!(!self.was_deleted()); unsafe { #move_item(self.inner, to as i32, from as i32) } } fn swap(&mut self, a: i32, b: i32) { assert!(!self.was_deleted()); unsafe { #swap(self.inner, a as i32, b as i32) } } fn clear(&mut self) { unsafe { assert!(!self.was_deleted()); #clear(self.inner) } } fn size(&self) -> i32 { unsafe { assert!(!self.was_deleted()); #size(self.inner) as i32 } } fn select(&mut self, line: i32) { assert!(!self.was_deleted()); if line <= self.size() { unsafe { #select(self.inner, line as i32); } } } fn selected(&self, line: i32) -> bool { assert!(!self.was_deleted()); unsafe { #selected(self.inner, line as i32) != 0 } } fn text(&self, line: i32) -> Option<String> { assert!(!self.was_deleted()); unsafe { let text = #text(self.inner, line as i32); if text.is_null() { None } else { Some(CStr::from_ptr(text as *mut raw::c_char).to_string_lossy().to_string()) } } } fn selected_text(&self) -> Option<String> { self.text(self.value()) } fn set_text(&mut self, line: i32, txt: &str) { assert!(!self.was_deleted()); let txt = CString::safe_new(txt); unsafe { #set_text(self.inner, line as i32, txt.as_ptr()) } } fn load<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), FltkError> { assert!(!self.was_deleted()); if !path.as_ref().exists() { return Err(FltkError::Internal(FltkErrorKind::ResourceNotFound)); } let path = path.as_ref().to_str().ok_or(FltkError::Unknown(String::from("Failed to convert path to string")))?; let path = CString::new(path)?; unsafe { #load_file(self.inner, path.as_ptr()); Ok(()) } } fn text_size(&self) -> i32 { assert!(!self.was_deleted()); unsafe { #text_size(self.inner) as i32 } } fn set_text_size(&mut self, c: i32) { unsafe { assert!(!self.was_deleted()); #set_text_size(self.inner, c as i32) } } fn set_icon<Img: ImageExt>(&mut self, line: i32, image: Option<Img>) { assert!(!self.was_deleted()); if let Some(image) = image { unsafe { #set_icon(self.inner, line as i32, image.as_image_ptr() as *mut _) } } else { unsafe { #set_icon(self.inner, line as i32, std::ptr::null_mut() as *mut raw::c_void) } } } fn icon(&self, line: i32) -> Option<Box<dyn ImageExt>> { unsafe { assert!(!self.was_deleted()); let image_ptr = #icon(self.inner, line as i32); if image_ptr.is_null() { None } else { let mut img = Image::from_image_ptr(image_ptr as *mut fltk_sys::image::Fl_Image); Some(Box::new(img)) } } } fn remove_icon(&mut self, line: i32) { unsafe { assert!(!self.was_deleted()); #remove_icon(self.inner, line as i32) } } fn top_line(&mut self, line: i32) { assert!(!self.was_deleted()); unsafe { #topline(self.inner, line as i32) } } fn bottom_line(&mut self, line: i32) { assert!(!self.was_deleted()); unsafe { #bottomline(self.inner, line as i32) } } fn middle_line(&mut self, line: i32) { assert!(!self.was_deleted()); unsafe { #middleline(self.inner, line as i32) } } fn format_char(&self) -> char { assert!(!self.was_deleted()); unsafe { #format_char(self.inner) as u8 as char } } fn set_format_char(&mut self, c: char) { assert!(!self.was_deleted()); debug_assert!(c != 0 as char); let c = if c as i32 > 128 { 128 as char } else { c }; unsafe { #set_format_char(self.inner, c as raw::c_char) } } fn column_char(&self) -> char { assert!(!self.was_deleted()); unsafe { #column_char(self.inner) as u8 as char } } fn set_column_char(&mut self, c: char) { assert!(!self.was_deleted()); debug_assert!(c != 0 as char); let c = if c as i32 > 128 { 128 as char } else { c }; unsafe { #set_column_char(self.inner, c as raw::c_char) } } fn column_widths(&self) -> Vec<i32> { assert!(!self.was_deleted()); unsafe { let widths = #column_widths(self.inner); // Should never throw assert!(!widths.is_null()); let mut v: Vec<i32> = vec![]; let mut i = 0; while (*widths.offset(i) != 0) { v.push(*widths.offset(i)); i += 1; } v } } fn set_column_widths(&mut self, arr: &'static [i32]) { assert!(!self.was_deleted()); unsafe { let mut v = arr.to_vec(); v.push(0); let v = mem::ManuallyDrop::new(v); #set_column_widths(self.inner, v.as_ptr()); } } fn displayed(&self, line: i32,) -> bool { assert!(!self.was_deleted()); unsafe { #displayed(self.inner, line as i32,) != 0 } } fn make_visible(&mut self, line: i32) { assert!(!self.was_deleted()); unsafe { #make_visible(self.inner, line as i32) } } fn position(&self) -> i32 { assert!(!self.was_deleted()); unsafe { #position(self.inner) as i32 } } fn set_position(&mut self, pos: i32) { assert!(!self.was_deleted()); unsafe { #set_position(self.inner, pos as i32) } } fn hposition(&self) -> i32 { assert!(!self.was_deleted()); unsafe { #hposition(self.inner) as i32 } } fn set_hposition(&mut self, pos: i32) { assert!(!self.was_deleted()); unsafe { #set_hposition(self.inner, pos as i32) } } fn has_scrollbar(&self) -> BrowserScrollbar { assert!(!self.was_deleted()); unsafe { mem::transmute(#has_scrollbar(self.inner)) } } fn set_has_scrollbar(&mut self, mode: BrowserScrollbar) { assert!(!self.was_deleted()); unsafe { #set_has_scrollbar(self.inner, mode as raw::c_uchar) } } fn scrollbar_size(&self) -> i32 { assert!(!self.was_deleted()); unsafe { #scrollbar_size(self.inner) as i32 } } fn set_scrollbar_size(&mut self, new_size: i32) { assert!(!self.was_deleted()); unsafe { #set_scrollbar_size(self.inner, new_size as i32) } } fn sort(&mut self) { assert!(!self.was_deleted()); unsafe { #sort(self.inner) } } fn scrollbar(&self) -> Box<dyn ValuatorExt> { assert!(!self.was_deleted()); unsafe { let ptr = #scrollbar(self.inner); assert!(!ptr.is_null()); Box::new(crate::valuator::Scrollbar::from_widget_ptr(ptr as *mut fltk_sys::widget::Fl_Widget)) } } fn hscrollbar(&self) -> Box<dyn ValuatorExt> { assert!(!self.was_deleted()); unsafe { let ptr = #hscrollbar(self.inner); assert!(!ptr.is_null()); Box::new(crate::valuator::Scrollbar::from_widget_ptr(ptr as *mut fltk_sys::widget::Fl_Widget)) } } fn value(&self) -> i32 { assert!(!self.was_deleted()); unsafe { #value(self.inner) as i32 } } } }; gen.into() }
/*! The common `ErrorKind`, `Error`, and `Result` types used throughout. */ #![allow(missing_docs)] use crate::shared::{PackageKind, Platform}; use std::process::ExitStatus; // ------------------------------------------------------------------------------------------------ // Public Types // ------------------------------------------------------------------------------------------------ error_chain! { errors { #[doc("Invalid configuration value")] InvalidConfigValue(field: String, value: String) { description("Invalid configuration value") display("Invalid value for configuration field '{}': '{}'", field, value) } #[doc("No package set found in group")] NoPackageSet(group: String, package_set: String) { description("No package set found in group") display("No package set '{}' found in group '{}'", package_set, group) } #[doc("No package set found in group")] PackagePlatformError(package: String) { description("The package cannot be installed on this platform") display("The package '{}' cannot be installed on platform {:?}", package, Platform::CURRENT) } #[doc("No installer found for package kind")] NoInstallerForKind(kind: PackageKind) { description("No installer found for package kind") display("No installer found for platform '{:?}' and package kind '{:?}'", Platform::CURRENT, kind) } #[doc("Wrong installer used for package kind")] WrongInstallerForKind(kind: PackageKind) { description("Wrong installer used for package kind") display("Wrong installer used for package kind '{:?}'", kind) } #[doc("Invalid command string for installer action")] InvalidCommandString(cmd_str: String) { description("Invalid command string for installer action") display("Invalid command string for installer action: {:?}", cmd_str) } #[doc("Command string for install action failed to run")] InstallerCommandFailed { description("Command string for install action failed to run") display("Command string for install action failed to run") } #[doc("std::process::Command failed to execute command")] CommandExecutionFailed(cmd: String, exit_status: Option<ExitStatus>) { description("std::process::Command failed to execute command") display("std::process::Command failed to execute command '{}', status: {:?}", cmd, exit_status) } #[doc("Invalid builder state")] InvalidBuilderState { description("Invalid builder state") display("Invalid builder state") } #[doc("Value provided is not a valid Name representation")] InvalidNameString(name: String) { description("Value provided is not a valid Name representation") display("Value '{}' is not a valid Name representation", name) } } foreign_links { Fmt(::std::fmt::Error); Git(::git2::Error); Io(::std::io::Error); Serialization(::serde_yaml::Error); Sql(::rusqlite::Error); } } // ------------------------------------------------------------------------------------------------ // Private Types // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ // Public Functions // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ // Implementations // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ // Private Functions // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ // Modules // ------------------------------------------------------------------------------------------------
extern crate hostname; extern crate bufstream; use bufstream::BufStream; use std::io::{self, Write}; use std::net::TcpListener; use std::thread::spawn; use std::{thread, time}; use std::time::{SystemTime, UNIX_EPOCH}; use std::fs::OpenOptions; mod receiver; mod maildir; fn main() { println!("hello, here is main."); smtpd("127.0.0.1:8025").expect("error: "); } fn smtpd(addr: &str) -> io::Result<()> { receiver::main(); maildir::main(); spawn(move || { loop { maildir::scan().err(); thread::sleep(time::Duration::from_millis(1000)); } }); spawn(move || { thread::sleep(time::Duration::from_millis(1000 * 3)); loop { let start = SystemTime::now(); let since_the_epoch = start.duration_since(UNIX_EPOCH).unwrap(); let _filename = format!("tests/Maildir/new/mail.{:?}", since_the_epoch); println!("filename {}", _filename); { let mut _file = OpenOptions::new() .read(true) .write(true) .create(true) .open(_filename).expect("file create"); _file.write_all(b"Hello, world!").unwrap(); } thread::sleep(time::Duration::from_millis(1000 * 10)); } }); let listener = TcpListener::bind(addr)?; println!("smtpd-rs: listening on {}", addr); listener.set_ttl(100).expect("could not set TTL"); loop { let (stream, c_addr) = listener.accept()?; println!("connection received from {}", c_addr); spawn(move || { let mut smtp_stream = BufStream::new(stream); receiver::handler(&mut smtp_stream).err(); }); } }
use serde::{Deserialize, Serialize}; use std::default::Default; use std::path::{Path, PathBuf}; #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct HttpHandlerConfig { /// Instructs the HTTP handler to use the specified port pub port: Option<u16>, /// Instructs the HTTP handler to bind to any open port and report the port /// to the specified file. /// The port is written in its textual representation, no newline at the /// end. pub write_port_to: Option<PathBuf>, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct ArtifactPoolConfig { pub consensus_pool_path: PathBuf, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct CryptoConfig { pub crypto_root: PathBuf, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct StateManagerConfig { pub state_root: PathBuf, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct ReplicaConfig { pub http_handler: HttpHandlerConfig, pub state_manager: StateManagerConfig, pub crypto: CryptoConfig, pub artifact_pool: ArtifactPoolConfig, pub no_artificial_delay: bool, } impl ReplicaConfig { pub fn new(state_root: &Path, no_artificial_delay: bool) -> Self { ReplicaConfig { http_handler: HttpHandlerConfig { write_port_to: None, port: None, }, state_manager: StateManagerConfig { state_root: state_root.join("replicated_state"), }, crypto: CryptoConfig { crypto_root: state_root.join("crypto_store"), }, artifact_pool: ArtifactPoolConfig { consensus_pool_path: state_root.join("consensus_pool"), }, no_artificial_delay, } } #[allow(dead_code)] pub fn with_port(&mut self, port: u16) -> &mut Self { self.http_handler.port = Some(port); self.http_handler.write_port_to = None; self } pub fn with_random_port(&mut self, write_port_to: &Path) -> Self { self.http_handler.port = None; self.http_handler.write_port_to = Some(write_port_to.to_path_buf()); let config = &*self; config.clone() } }
use lapin::ConnectionProperties; pub trait BastionExt { fn with_bastion(self) -> Self where Self: Sized, { self.with_bastion_executor() } fn with_bastion_executor(self) -> Self where Self: Sized; } impl BastionExt for ConnectionProperties { fn with_bastion_executor(self) -> Self { self.with_executor(bastion_executor_trait::Bastion) } }
use bevy::{ core::FixedTimestep, app::{AppExit, ScheduleRunnerPlugin, ScheduleRunnerSettings}, ecs::schedule::ReportExecutionOrderAmbiguities, input::{keyboard::KeyCode, Input}, log::LogPlugin, prelude::*, utils::Duration, }; use rand::random; const ARENA_WIDTH: u32 = 100; const ARENA_HEIGHT: u32 = 100; struct Player { name: String, head: PlayerHead, } #[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)] struct Position { x: i32, y: i32, } struct PlayerSegment; struct GrowthEvent; struct GameOverEvent; #[derive(Default)] struct PlayerSegments(Vec<Entity>); #[derive(Default)] struct LastTailPosition(Option<Position>); struct BoxSize { width: f32, height: f32, } impl BoxSize { pub fn square(x: f32) -> Self { Self { width: x, height: x, } } } #[derive(PartialEq, Copy, Clone)] enum Direction { Left, Up, Right, Down, } #[derive(SystemLabel, Debug, Hash, PartialEq, Eq, Clone)] pub enum PlayerMovement { Input, Movement, Growth, Spawn, } #[derive(SystemLabel, Debug, Clone, Eq, PartialEq, Hash)] enum AppState { MainMenu, InGame, Paused, GameOver } impl Direction { fn opposite(self) -> Self { match self { Self::Left => Self::Right, Self::Right => Self::Left, Self::Up => Self::Down, Self::Down => Self::Up, } } } struct Score { value: usize, } // RESOURCES: "Global" state accessible by systems. These are also just normal Rust data types. #[derive(Default)] struct GameState { current_round: usize, total_players: usize, winning_player: Option<String>, } struct PlayerHead { direction: Direction, } struct Materials { head_material: Handle<ColorMaterial>, segment_material: Handle<ColorMaterial>, } struct GameRules { winning_score: usize, max_rounds: usize, max_players: usize, } struct MenuData { button_entity: Entity, } // SYSTEMS: Logic that runs on entities, components, and resources. These generally run once each // time the app updates. fn new_round_system(game_rules: Res<GameRules>, mut game_state: ResMut<GameState>) { game_state.current_round += 1; println!( "Begin round {} of {}", game_state.current_round, game_rules.max_rounds ); } // Menu fn setup_menu( mut commands: Commands, asset_server: Res<AssetServer>, mut materials: ResMut<Assets<ColorMaterial>>, ) { // ui camera commands.spawn_bundle(OrthographicCameraBundle::new_2d()); //commands.spawn_bundle(UiCameraBundle::default()); let button_entity = commands .spawn_bundle(ButtonBundle { style: Style { size: Size::new(Val::Px(150.0), Val::Px(65.0)), // center button margin: Rect::all(Val::Auto), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, ..Default::default() }, //material: button_materials.normal.clone(), ..Default::default() }) .with_children(|parent| { parent.spawn_bundle(TextBundle { text: Text::with_section( "Play", TextStyle { font: asset_server.load("fonts/Chivo-Regular.ttf"), font_size: 40.0, color: Color::rgb(0.9, 0.9, 0.9), }, Default::default(), ), ..Default::default() }); }) .id(); commands.insert_resource(MenuData { button_entity }); commands.insert_resource(Materials { head_material: materials.add(Color::rgb(0.1, 0.9, 0.9).into()), segment_material: materials.add(Color::rgb(0.1, 0.7, 0.7).into()) }); } fn menu( mut state: ResMut<State<AppState>>, mut interaction_query: Query< (&Interaction, &mut Handle<ColorMaterial>), (Changed<Interaction>, With<Button>), >, ) { for (interaction, mut material) in interaction_query.iter_mut() { match *interaction { Interaction::Clicked => { state.set(AppState::InGame).unwrap(); } Interaction::Hovered => { println!("{:?}", state.current()); } Interaction::None => { println!("hovered"); } } } } fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) { commands.entity(menu_data.button_entity).despawn_recursive(); } fn change_color( time: Res<Time>, mut assets: ResMut<Assets<ColorMaterial>>, query: Query<&Handle<ColorMaterial>, With<Sprite>>, ) { for handle in query.iter() { let material = assets.get_mut(handle).unwrap(); material .color .set_b((time.seconds_since_startup() * 5.0).sin() as f32 + 2.0); } } // This system updates the score for each entity with the "Player" and "Score" component. fn score_system(mut query: Query<(&Player, &mut Score)>) { for (player, mut score) in query.iter_mut() { let scored_a_point = random::<bool>(); if scored_a_point { score.value += 1; println!( "{} scored a point! Their score is: {}", player.name, score.value ); } else { println!( "{} did not score a point! Their score is: {}", player.name, score.value ); } } } // Scaling sprites fn size_scaling(windows: Res<Windows>, mut q: Query<(&BoxSize, &mut Sprite)>) { let window = windows.get_primary().unwrap(); for (sprite_size, mut sprite) in q.iter_mut() { sprite.size = Vec2::new( sprite_size.width / ARENA_WIDTH as f32 * window.width() as f32, sprite_size.height / ARENA_HEIGHT as f32 * window.height() as f32, ); } } fn position_translation(windows: Res<Windows>, mut q: Query<(&Position, &mut Transform)>) { fn convert(pos: f32, bound_window: f32, bound_game: f32) -> f32 { let tile_size = bound_window / bound_game; pos / bound_game * bound_window - (bound_window / 2.) + (tile_size / 2.) } let window = windows.get_primary().unwrap(); for (pos, mut transform) in q.iter_mut() { transform.translation = Vec3::new( convert(pos.x as f32, window.width() as f32, ARENA_WIDTH as f32), convert(pos.y as f32, window.height() as f32, ARENA_HEIGHT as f32), 0.0, ); } } // This system runs on all entities with the "Player" and "Score" components, but it also // accesses the "GameRules" resource to determine if a player has won. fn score_check_system( game_rules: Res<GameRules>, mut game_state: ResMut<GameState>, query: Query<(&Player, &Score)>, ) { for (player, score) in query.iter() { if score.value == game_rules.winning_score { game_state.winning_player = Some(player.name.clone()); } } } // This system ends the game if we meet the right conditions. This fires an AppExit event, which // tells our App to quit. Check out the "event.rs" example if you want to learn more about using // events. fn game_over_system( game_rules: Res<GameRules>, game_state: Res<GameState>, mut app_exit_events: EventWriter<AppExit>, ) { if let Some(ref player) = game_state.winning_player { println!("{} won the game!", player); app_exit_events.send(AppExit); } else if game_state.current_round == game_rules.max_rounds { println!("Ran out of rounds. Nobody wins!"); app_exit_events.send(AppExit); } } // This is a "startup" system that runs exactly once when the app starts up. Startup systems are // generally used to create the initial "state" of our game. The only thing that distinguishes a // "startup" system from a "normal" system is how it is registered: Startup: // app.add_startup_system(startup_system) Normal: app.add_system(normal_system) fn startup_system( mut commands: Commands, mut game_state: ResMut<GameState>, mut materials: ResMut<Assets<ColorMaterial>>, ) { // Create our game rules resource commands.insert_resource(GameRules { max_rounds: 100, winning_score: 51, max_players: 4, }); commands.spawn_batch(vec![ ( Player { name: "Quorra".to_string(), head: PlayerHead {direction: Direction::Up}, }, Score { value: 0 }, ), ( Player { name: "Clu".to_string(), head: PlayerHead {direction: Direction::Down}, }, Score { value: 0 }, ), ]); // Create a camera //commands.spawn_bundle(OrthographicCameraBundle::new_2d()); /* commands.insert_resource(Materials { head_material: materials.add(Color::rgb(0.1, 0.9, 0.9).into()), segment_material: materials.add(Color::rgb(0.1, 0.7, 0.7).into()) });*/ game_state.total_players = 2; } // This system uses a command buffer to (potentially) add a new player to our game on each // iteration. Normal systems cannot safely access the World instance directly because they run in // parallel. Our World contains all of our components, so mutating arbitrary parts of it in parallel // is not thread safe. Command buffers give us the ability to queue up changes to our World without // directly accessing it fn new_player_system( mut commands: Commands, game_rules: Res<GameRules>, mut game_state: ResMut<GameState>, ) { let add_new_player = random::<bool>(); if add_new_player && game_state.total_players < game_rules.max_players { game_state.total_players += 1; commands.spawn_bundle(( Player { name: format!("Player {}", game_state.total_players), head: PlayerHead {direction: Direction::Down}, }, Score { value: 0 }, )); println!("Player {} joined the game!", game_state.total_players); } } // Spawn new tron player fn spawn_player( mut commands: Commands, materials: Res<Materials>, mut segments: ResMut<PlayerSegments>, ) { println!("\n\nSPAWN\n\n"); segments.0 = vec![ commands .spawn_bundle(SpriteBundle { material: materials.head_material.clone(), sprite: Sprite::new(Vec2::new(10.0, 10.0)), ..Default::default() }) .insert(PlayerHead { direction: Direction::Up, }) .insert(PlayerSegment) .insert(Position { x: 3, y: 3 }) .insert(BoxSize::square(0.8)) .id(), spawn_segment( commands, &materials.segment_material, Position { x: 3, y: 2 }, ), ]; } // Move player fn player_movement_input(keyboard_input: Res<Input<KeyCode>>, mut heads: Query<&mut PlayerHead>, state: ResMut<State<AppState>>,) { if let Some(mut head) = heads.iter_mut().next() { let dir: Direction = if keyboard_input.pressed(KeyCode::Left) { Direction::Left } else if keyboard_input.pressed(KeyCode::Down) { Direction::Down } else if keyboard_input.pressed(KeyCode::Up) { Direction::Up } else if keyboard_input.pressed(KeyCode::Right) { Direction::Right } else { head.direction }; if dir != head.direction.opposite() { head.direction = dir; } } println!("{:?}", state.current()); } fn player_movement( segments: ResMut<PlayerSegments>, mut heads: Query<(Entity, &PlayerHead)>, mut positions: Query<&mut Position>, mut game_over_writer: EventWriter<GameOverEvent>, ) { if let Some((head_entity, head)) = heads.iter_mut().next() { let segment_positions = segments .0 .iter() .map(|e| *positions.get_mut(*e).unwrap()) .collect::<Vec<Position>>(); let mut head_pos = positions.get_mut(head_entity).unwrap(); match &head.direction { Direction::Left => { head_pos.x -= 1; } Direction::Right => { head_pos.x += 1; } Direction::Up => { head_pos.y += 1; } Direction::Down => { head_pos.y -= 1; } }; if segment_positions.contains(&head_pos) { game_over_writer.send(GameOverEvent); } if head_pos.x < 0 || head_pos.y < 0 || head_pos.x as u32 >= ARENA_WIDTH || head_pos.y as u32 >= ARENA_HEIGHT { game_over_writer.send(GameOverEvent); } segment_positions .iter() .zip(segments.0.iter().skip(1)) .for_each(|(pos, segment)| { *positions.get_mut(*segment).unwrap() = *pos; }); } } fn player_growth( commands: Commands, head_positions: Query<&Position, With<PlayerHead>>, mut segments: ResMut<PlayerSegments>, materials: Res<Materials>, ) { println!("\n\nIN GROWTH\n\n"); segments.0.push(spawn_segment( // This would add the tail always to the same player commands, &materials.segment_material, head_positions.single().unwrap().clone().into(), )); } fn spawn_segment( mut commands: Commands, material: &Handle<ColorMaterial>, position: Position, ) -> Entity { commands .spawn_bundle(SpriteBundle { material: material.clone(), ..Default::default() }) .insert(PlayerSegment) .insert(position) .insert(BoxSize::square(0.65)) .id() } fn game_over( mut commands: Commands, mut reader: EventReader<GameOverEvent>, materials: Res<Materials>, players: Query<Entity, With<Position>>, segments_res: ResMut<PlayerSegments>, segments: Query<Entity, With<PlayerSegment>>, ) { if reader.iter().next().is_some() { println!("Game over!"); for ent in players.iter().chain(segments.iter()) { commands.entity(ent).despawn(); } spawn_player(commands, materials, segments_res); // Before this line delete the player trail } } #[derive(Debug, Hash, PartialEq, Eq, Clone, StageLabel)] enum MyStage { BeforeRound, AfterRound, } #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel)] enum MyLabels { ScoreCheck, } // Our Bevy app's entry point fn main() { // Bevy apps are created using the builder pattern. We use the builder to add systems, // resources, and plugins to our app App::build() .insert_resource(ReportExecutionOrderAmbiguities) .add_plugins(DefaultPlugins) // Resize and rename window .insert_resource(WindowDescriptor { // <-- title: "Nuisance Value".to_string(), // <-- width: 500.0, // <-- height: 500.0, // <-- ..Default::default() // <-- }) .add_state(AppState::MainMenu) // Change colors .insert_resource(ClearColor(Color::rgb(0.04, 0.04, 0.04))) // Player tails .insert_resource(PlayerSegments::default()) .insert_resource(LastTailPosition::default()) // Some systems are configured by adding their settings as a resource //.insert_resource(ScheduleRunnerSettings::run_loop(Duration::from_secs(5))) // Plugins are just a grouped set of app builder calls (just like we're doing here). // We could easily turn our game into a plugin, but you can check out the plugin example for // that :) The plugin below runs our app's "system schedule" once every 5 seconds // (configured above). //.add_plugin(ScheduleRunnerPlugin::default()) // Resources that implement the Default or FromResources trait can be added like this: .init_resource::<GameState>() // Startup systems run exactly once BEFORE all other systems. These are generally used for // app initialization code (ex: adding entities and resources) //.add_startup_system(startup_system.system()) // Add Player death .add_event::<GameOverEvent>() // Add tail event .add_event::<GrowthEvent>() // Add game setup to stage //.add_startup_stage("game_setup", SystemStage::single(spawn_player.system())) // SYSTEM EXECUTION ORDER // // Each system belongs to a `Stage`, which controls the execution strategy and broad order // of the systems within each tick. Startup stages (which startup systems are // registered in) will always complete before ordinary stages begin, // and every system in a stage must complete before the next stage advances. // Once every stage has concluded, the main loop is complete and begins again. // // By default, all systems run in parallel, except when they require mutable access to a // piece of data. This is efficient, but sometimes order matters. // For example, we want our "game over" system to execute after all other systems to ensure // we don't accidentally run the game for an extra round. // // Rather than splitting each of your systems into separate stages, you should force an // explicit ordering between them by giving the relevant systems a label with // `.label`, then using the `.before` or `.after` methods. Systems will not be // scheduled until all of the systems that they have an "ordering dependency" on have // completed. // // Doing that will, in just about all cases, lead to better performance compared to // splitting systems between stages, because it gives the scheduling algorithm more // opportunities to run systems in parallel. // Stages are still necessary, however: end of a stage is a hard sync point // (meaning, no systems are running) where `Commands` issued by systems are processed. // This is required because commands can perform operations that are incompatible with // having systems in flight, such as spawning or deleting entities, // adding or removing resources, etc. // // add_system(system) adds systems to the UPDATE stage by default // However we can manually specify the stage if we want to. The following is equivalent to // add_system(score_system) //.add_system_to_stage(CoreStage::Update, score_system.system()) // We can also create new stages. Here is what our games stage order will look like: // "before_round": new_player_system, new_round_system // "update": print_message_system, score_system // "after_round": score_check_system, game_over_system .add_stage_before( CoreStage::Update, MyStage::BeforeRound, SystemStage::parallel(), ) .add_stage_after( CoreStage::Update, MyStage::AfterRound, SystemStage::parallel(), ) //.add_system_to_stage(MyStage::BeforeRound, new_round_system.system()) //.add_system_to_stage(MyStage::BeforeRound, new_player_system.system()) // We can ensure that game_over system runs after score_check_system using explicit ordering // constraints First, we label the system we want to refer to using `.label` // Then, we use either `.before` or `.after` to describe the order we want the relationship /* .add_system_to_stage( MyStage::AfterRound, score_check_system.system().label(MyLabels::ScoreCheck), )*/ /* .add_system_to_stage( MyStage::AfterRound, game_over_system.system().after(MyLabels::ScoreCheck), )*/ .add_system_set( SystemSet::on_enter(AppState::MainMenu) //.with_system(startup_system.system()) .with_system(setup_menu.system()) ) .add_system_set( SystemSet::on_update(AppState::MainMenu) .with_system(menu.system()) .before(PlayerMovement::Movement) .before(PlayerMovement::Input) ) .add_system_set( SystemSet::on_exit(AppState::MainMenu) .with_system(cleanup_menu.system()) ) .add_system_set( SystemSet::on_enter(AppState::InGame) .with_system( startup_system.system() .before(PlayerMovement::Spawn) ) .with_system( spawn_player .system() .label(PlayerMovement::Spawn) //.before(PlayerMovement::Movement) ) ) .add_system_set( SystemSet::on_update(AppState::InGame) //.with_run_criteria(FixedTimestep::step(0.250)) .with_system( player_growth .system() .label(PlayerMovement::Growth) .after(PlayerMovement::Movement) .after(PlayerMovement::Spawn), ) .with_system( player_movement_input .system() .label(PlayerMovement::Input) .before(PlayerMovement::Movement), ) .with_system( player_movement.system() .label(PlayerMovement::Movement) .after(PlayerMovement::Spawn) ) .with_system( game_over .system() .before(PlayerMovement::Movement) ) .with_system(position_translation.system()) .with_system(size_scaling.system()) ) .run(); }
//! //! The Moon OS kernel : Rocket //! #![feature(naked_functions)] #![feature(core_intrinsics)] #![feature(const_fn)] #![feature(unique)] #![feature(asm)] #![feature(lang_items)] #![no_std] /// Provides some classic libc functions, like `memset`, `memcpy` etc... extern crate rlibc; #[macro_use] extern crate lazy_static; #[macro_use] extern crate bitflags; /// Contains some rust language items, like the `println!` macro. #[macro_use] mod rlang; /// Provides some utils functions that can be used independantly anywhere /// in the Rocket kernel. extern crate rocket_utils as utils; /// Provides some architecture-specific wrappers. mod arch; /// Way of printing to screen during initialisation /// (Will be replaced by a tty when multi-processes will be done) mod vga; use vga::Color as Color; /// Provokes a division by zero. Used to test the exceptions handlers. #[allow(dead_code)] fn divide_by_zero() -> i32 { unsafe { asm!("mov dx, 0; div dx" ::: "ax", "dx" : "volatile", "intel") } 5 } /// Provokes an invalid opcode trap. Used to test the exceptions handlers. #[allow(dead_code)] fn invalid_op_code() -> u32 { unsafe { asm!("ud2"); } 5 } /// Provokes a page fault. Used to test the exceptions handlers. /// (Nb: doesn't works on i386 bits yet, because Grub identity map the all /// memory). #[allow(dead_code)] fn page_fault() -> u32 { unsafe { *(0xdeadbeef as *mut usize) = 42; } 5 } /// /// Kernel entry point. Called directly from asm. /// #[no_mangle] pub extern fn kernel_main() { arch::init(); unsafe { vga::SCREEN.set_colors(Color::DarkGray, Color::White); vga::SCREEN.clear(); } println!("Hello World !"); println!("Welcome to Moon OS"); println!("You are running a {} bits system ! :D", core::mem::size_of::<usize>() * 8); println!("Wololo: {}", divide_by_zero()); println!("Yay o/"); } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn _Unwind_Resume() -> ! { loop {} }
// == // https://github.com/json-patch/json-patch-tests // == use serde::Deserialize; use serde_json::from_slice; use serde_json::from_value; use serde_json::Value; use json_patch::Error; use json_patch::Patch; const T1: &[u8] = include_bytes!("fixtures/spec_tests.json"); const T2: &[u8] = include_bytes!("fixtures/tests.json"); #[derive(Clone, Debug, Deserialize)] struct Test { #[serde(default)] comment: String, #[serde(default)] disabled: bool, doc: Value, patch: Value, error: Option<String>, expected: Option<Value>, } const INVALID_POINTER: &[&str] = &[ // tests.json "Out of bounds (upper)", "Out of bounds (lower)", "index is greater than number of items in array", "Object operation on array target", "replace op should fail with missing parent key", "remove op shouldn't remove from array with bad number", "replace op shouldn't replace in array with bad number", "copy op shouldn't work with bad number", "move op shouldn't work with bad number", "add op shouldn't add to array with bad number", "JSON Pointer should start with a slash", "missing 'from' location", "removing a nonexistent field should fail", "removing a nonexistent index should fail", // spec_tests.json "path /a does not exist -- missing objects are not created recursively", "add to a non-existent target", ]; const INVALID_TEST: &[&str] = &[ // tests.json "test op should fail", "test op shouldn't get array element 1", "test op should reject the array value, it has leading zeros", // spec_tests.json "string not equivalent", "number is not equal to string", ]; fn check_err(expected: String, current: String) { if INVALID_POINTER.contains(&&*expected) { assert_eq!(current, Error::InvalidPointer.to_string()); } else if INVALID_TEST.contains(&&*expected) { assert_eq!(current, Error::InvalidTest.to_string()); } else { match expected.as_str() { "missing 'from' parameter" => { assert_eq!(current, "missing field `from`"); } "missing 'path' parameter" => { assert_eq!(current, "missing field `path`"); } "missing 'value' parameter" => { assert_eq!(current, "missing field `value`"); } "null is not valid value for 'path'" => { assert_eq!(current, "invalid type: null, expected a string"); } "Unrecognized op 'spam'" => { assert_eq!(current, "unknown variant `spam`, expected one of `add`, `remove`, `replace`, `move`, `copy`, `test`"); } _ => { panic!("Unknown Error: {:?} != {:?}", current, expected); } } } } fn check_test(index: usize, mut test: Test) { if test.disabled { println!("[+] Test #{:02} (D): {}", index, test.comment); } else { println!("[+] Test #{:02} (E): {}", index, test.comment); match (test.expected, test.error) { (Some(inner), None) => { from_value::<Patch>(test.patch) .unwrap() .apply_mut(&mut test.doc) .unwrap(); assert_eq!(inner, test.doc); } (None, Some(inner)) => match from_value::<Patch>(test.patch) { Ok(patch) => check_err( inner, patch.apply_mut(&mut test.doc).unwrap_err().to_string(), ), Err(error) => check_err(inner, error.to_string()), }, (Some(_), Some(_)) | (None, None) => unreachable!(), } } } #[test] fn test_tests() { for (index, test) in from_slice::<Vec<Test>>(T1).unwrap().into_iter().enumerate() { check_test(index, test); } for (index, test) in from_slice::<Vec<Test>>(T2).unwrap().into_iter().enumerate() { check_test(index, test); } }
#[macro_use(dense_vec, sparse_vec)] extern crate vectors; use vectors::Vector; use vectors::heap::{SparseVector, DenseVector}; fn main() { let sparse_1 = SparseVector::from(vec![(0, 0.1), (2, 0.2), (4, 0.3), (6, 0.4)]); let sparse_2 = SparseVector::from(vec![(0, 0.2), (3, 0.4), (5, 0.2), (6, 0.6)]); let dot = sparse_1.dot(&sparse_2); println!("{:?}", dot); let dense_1 = DenseVector::from(vec![0.0, 1.0, 2.0, 4.0, 6.0]); let dense_2 = DenseVector::from(vec![0.2, 3.0, 0.0, 1.5, 6.0]); let dot = dense_1.dot(&dense_2); println!("{:?}", dot); }
extern crate futures; extern crate hyper; use internaldata::Server; use futures::future::Future; use futures::{Stream}; use hyper::header::ContentLength; use hyper::server::{Request, Response}; pub type BoxFuture = Box<Future<Item = Response, Error = hyper::Error>>; pub trait EchoHandler { fn handle_post(&self, req: Request) -> BoxFuture; } impl EchoHandler for Server { fn handle_post(&self, req: Request) -> BoxFuture { let mut res = Response::new(); let (_method, _uri, _version, headers, body) = req.deconstruct(); let input: Vec<u8> = if let Some(len) = headers.get::<ContentLength>() { res.headers_mut().set(len.clone()); Vec::with_capacity(**len as usize) } else { Vec::new() }; Box::new(body.fold(input, |mut acc, chunk| { acc.extend_from_slice(chunk.as_ref()); Ok::<_, hyper::Error>(acc) }).and_then(move |value| { debug!("Incoming post: {}", String::from_utf8(value.clone()).unwrap_or("error".to_string())); Ok(res.with_body(value)) })) } }
#[doc = "Register `CLKCR` reader"] pub type R = crate::R<CLKCR_SPEC>; #[doc = "Register `CLKCR` writer"] pub type W = crate::W<CLKCR_SPEC>; #[doc = "Field `CLKDIV` reader - Clock divide factor"] pub type CLKDIV_R = crate::FieldReader; #[doc = "Field `CLKDIV` writer - Clock divide factor"] pub type CLKDIV_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 8, O>; #[doc = "Field `CLKEN` reader - Clock enable bit"] pub type CLKEN_R = crate::BitReader<CLKEN_A>; #[doc = "Clock enable bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CLKEN_A { #[doc = "0: Disable clock"] Disabled = 0, #[doc = "1: Enable clock"] Enabled = 1, } impl From<CLKEN_A> for bool { #[inline(always)] fn from(variant: CLKEN_A) -> Self { variant as u8 != 0 } } impl CLKEN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CLKEN_A { match self.bits { false => CLKEN_A::Disabled, true => CLKEN_A::Enabled, } } #[doc = "Disable clock"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == CLKEN_A::Disabled } #[doc = "Enable clock"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == CLKEN_A::Enabled } } #[doc = "Field `CLKEN` writer - Clock enable bit"] pub type CLKEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CLKEN_A>; impl<'a, REG, const O: u8> CLKEN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Disable clock"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(CLKEN_A::Disabled) } #[doc = "Enable clock"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(CLKEN_A::Enabled) } } #[doc = "Field `PWRSAV` reader - Power saving configuration bit"] pub type PWRSAV_R = crate::BitReader<PWRSAV_A>; #[doc = "Power saving configuration bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PWRSAV_A { #[doc = "0: SDIO_CK clock is always enabled"] Enabled = 0, #[doc = "1: SDIO_CK is only enabled when the bus is active"] Disabled = 1, } impl From<PWRSAV_A> for bool { #[inline(always)] fn from(variant: PWRSAV_A) -> Self { variant as u8 != 0 } } impl PWRSAV_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PWRSAV_A { match self.bits { false => PWRSAV_A::Enabled, true => PWRSAV_A::Disabled, } } #[doc = "SDIO_CK clock is always enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == PWRSAV_A::Enabled } #[doc = "SDIO_CK is only enabled when the bus is active"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == PWRSAV_A::Disabled } } #[doc = "Field `PWRSAV` writer - Power saving configuration bit"] pub type PWRSAV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PWRSAV_A>; impl<'a, REG, const O: u8> PWRSAV_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "SDIO_CK clock is always enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(PWRSAV_A::Enabled) } #[doc = "SDIO_CK is only enabled when the bus is active"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(PWRSAV_A::Disabled) } } #[doc = "Field `BYPASS` reader - Clock divider bypass enable bit"] pub type BYPASS_R = crate::BitReader<BYPASS_A>; #[doc = "Clock divider bypass enable bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BYPASS_A { #[doc = "0: SDIOCLK is divided according to the CLKDIV value before driving the SDIO_CK output signal."] Disabled = 0, #[doc = "1: SDIOCLK directly drives the SDIO_CK output signal"] Enabled = 1, } impl From<BYPASS_A> for bool { #[inline(always)] fn from(variant: BYPASS_A) -> Self { variant as u8 != 0 } } impl BYPASS_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BYPASS_A { match self.bits { false => BYPASS_A::Disabled, true => BYPASS_A::Enabled, } } #[doc = "SDIOCLK is divided according to the CLKDIV value before driving the SDIO_CK output signal."] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == BYPASS_A::Disabled } #[doc = "SDIOCLK directly drives the SDIO_CK output signal"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == BYPASS_A::Enabled } } #[doc = "Field `BYPASS` writer - Clock divider bypass enable bit"] pub type BYPASS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BYPASS_A>; impl<'a, REG, const O: u8> BYPASS_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "SDIOCLK is divided according to the CLKDIV value before driving the SDIO_CK output signal."] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(BYPASS_A::Disabled) } #[doc = "SDIOCLK directly drives the SDIO_CK output signal"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(BYPASS_A::Enabled) } } #[doc = "Field `WIDBUS` reader - Wide bus mode enable bit"] pub type WIDBUS_R = crate::FieldReader<WIDBUS_A>; #[doc = "Wide bus mode enable bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum WIDBUS_A { #[doc = "0: 1 lane wide bus"] BusWidth1 = 0, #[doc = "1: 4 lane wide bus"] BusWidth4 = 1, #[doc = "2: 8 lane wide bus"] BusWidth8 = 2, } impl From<WIDBUS_A> for u8 { #[inline(always)] fn from(variant: WIDBUS_A) -> Self { variant as _ } } impl crate::FieldSpec for WIDBUS_A { type Ux = u8; } impl WIDBUS_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<WIDBUS_A> { match self.bits { 0 => Some(WIDBUS_A::BusWidth1), 1 => Some(WIDBUS_A::BusWidth4), 2 => Some(WIDBUS_A::BusWidth8), _ => None, } } #[doc = "1 lane wide bus"] #[inline(always)] pub fn is_bus_width1(&self) -> bool { *self == WIDBUS_A::BusWidth1 } #[doc = "4 lane wide bus"] #[inline(always)] pub fn is_bus_width4(&self) -> bool { *self == WIDBUS_A::BusWidth4 } #[doc = "8 lane wide bus"] #[inline(always)] pub fn is_bus_width8(&self) -> bool { *self == WIDBUS_A::BusWidth8 } } #[doc = "Field `WIDBUS` writer - Wide bus mode enable bit"] pub type WIDBUS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, WIDBUS_A>; impl<'a, REG, const O: u8> WIDBUS_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "1 lane wide bus"] #[inline(always)] pub fn bus_width1(self) -> &'a mut crate::W<REG> { self.variant(WIDBUS_A::BusWidth1) } #[doc = "4 lane wide bus"] #[inline(always)] pub fn bus_width4(self) -> &'a mut crate::W<REG> { self.variant(WIDBUS_A::BusWidth4) } #[doc = "8 lane wide bus"] #[inline(always)] pub fn bus_width8(self) -> &'a mut crate::W<REG> { self.variant(WIDBUS_A::BusWidth8) } } #[doc = "Field `NEGEDGE` reader - SDIO_CK dephasing selection bit"] pub type NEGEDGE_R = crate::BitReader<NEGEDGE_A>; #[doc = "SDIO_CK dephasing selection bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NEGEDGE_A { #[doc = "0: SDIO_CK generated on the rising edge"] Rising = 0, #[doc = "1: SDIO_CK generated on the falling edge"] Falling = 1, } impl From<NEGEDGE_A> for bool { #[inline(always)] fn from(variant: NEGEDGE_A) -> Self { variant as u8 != 0 } } impl NEGEDGE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> NEGEDGE_A { match self.bits { false => NEGEDGE_A::Rising, true => NEGEDGE_A::Falling, } } #[doc = "SDIO_CK generated on the rising edge"] #[inline(always)] pub fn is_rising(&self) -> bool { *self == NEGEDGE_A::Rising } #[doc = "SDIO_CK generated on the falling edge"] #[inline(always)] pub fn is_falling(&self) -> bool { *self == NEGEDGE_A::Falling } } #[doc = "Field `NEGEDGE` writer - SDIO_CK dephasing selection bit"] pub type NEGEDGE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, NEGEDGE_A>; impl<'a, REG, const O: u8> NEGEDGE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "SDIO_CK generated on the rising edge"] #[inline(always)] pub fn rising(self) -> &'a mut crate::W<REG> { self.variant(NEGEDGE_A::Rising) } #[doc = "SDIO_CK generated on the falling edge"] #[inline(always)] pub fn falling(self) -> &'a mut crate::W<REG> { self.variant(NEGEDGE_A::Falling) } } #[doc = "Field `HWFC_EN` reader - HW Flow Control enable"] pub type HWFC_EN_R = crate::BitReader<HWFC_EN_A>; #[doc = "HW Flow Control enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HWFC_EN_A { #[doc = "0: HW Flow Control is disabled"] Disabled = 0, #[doc = "1: HW Flow Control is enabled"] Enabled = 1, } impl From<HWFC_EN_A> for bool { #[inline(always)] fn from(variant: HWFC_EN_A) -> Self { variant as u8 != 0 } } impl HWFC_EN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HWFC_EN_A { match self.bits { false => HWFC_EN_A::Disabled, true => HWFC_EN_A::Enabled, } } #[doc = "HW Flow Control is disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == HWFC_EN_A::Disabled } #[doc = "HW Flow Control is enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == HWFC_EN_A::Enabled } } #[doc = "Field `HWFC_EN` writer - HW Flow Control enable"] pub type HWFC_EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HWFC_EN_A>; impl<'a, REG, const O: u8> HWFC_EN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "HW Flow Control is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(HWFC_EN_A::Disabled) } #[doc = "HW Flow Control is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(HWFC_EN_A::Enabled) } } impl R { #[doc = "Bits 0:7 - Clock divide factor"] #[inline(always)] pub fn clkdiv(&self) -> CLKDIV_R { CLKDIV_R::new((self.bits & 0xff) as u8) } #[doc = "Bit 8 - Clock enable bit"] #[inline(always)] pub fn clken(&self) -> CLKEN_R { CLKEN_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Power saving configuration bit"] #[inline(always)] pub fn pwrsav(&self) -> PWRSAV_R { PWRSAV_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Clock divider bypass enable bit"] #[inline(always)] pub fn bypass(&self) -> BYPASS_R { BYPASS_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bits 11:12 - Wide bus mode enable bit"] #[inline(always)] pub fn widbus(&self) -> WIDBUS_R { WIDBUS_R::new(((self.bits >> 11) & 3) as u8) } #[doc = "Bit 13 - SDIO_CK dephasing selection bit"] #[inline(always)] pub fn negedge(&self) -> NEGEDGE_R { NEGEDGE_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - HW Flow Control enable"] #[inline(always)] pub fn hwfc_en(&self) -> HWFC_EN_R { HWFC_EN_R::new(((self.bits >> 14) & 1) != 0) } } impl W { #[doc = "Bits 0:7 - Clock divide factor"] #[inline(always)] #[must_use] pub fn clkdiv(&mut self) -> CLKDIV_W<CLKCR_SPEC, 0> { CLKDIV_W::new(self) } #[doc = "Bit 8 - Clock enable bit"] #[inline(always)] #[must_use] pub fn clken(&mut self) -> CLKEN_W<CLKCR_SPEC, 8> { CLKEN_W::new(self) } #[doc = "Bit 9 - Power saving configuration bit"] #[inline(always)] #[must_use] pub fn pwrsav(&mut self) -> PWRSAV_W<CLKCR_SPEC, 9> { PWRSAV_W::new(self) } #[doc = "Bit 10 - Clock divider bypass enable bit"] #[inline(always)] #[must_use] pub fn bypass(&mut self) -> BYPASS_W<CLKCR_SPEC, 10> { BYPASS_W::new(self) } #[doc = "Bits 11:12 - Wide bus mode enable bit"] #[inline(always)] #[must_use] pub fn widbus(&mut self) -> WIDBUS_W<CLKCR_SPEC, 11> { WIDBUS_W::new(self) } #[doc = "Bit 13 - SDIO_CK dephasing selection bit"] #[inline(always)] #[must_use] pub fn negedge(&mut self) -> NEGEDGE_W<CLKCR_SPEC, 13> { NEGEDGE_W::new(self) } #[doc = "Bit 14 - HW Flow Control enable"] #[inline(always)] #[must_use] pub fn hwfc_en(&mut self) -> HWFC_EN_W<CLKCR_SPEC, 14> { HWFC_EN_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 = "SDI clock control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`clkcr::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 [`clkcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CLKCR_SPEC; impl crate::RegisterSpec for CLKCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`clkcr::R`](R) reader structure"] impl crate::Readable for CLKCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`clkcr::W`](W) writer structure"] impl crate::Writable for CLKCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CLKCR to value 0"] impl crate::Resettable for CLKCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::{effects::EffectKind, fyrox::core::math::Vector3Ext, message::Message, GameTime}; use fyrox::{ core::{ algebra::Vector3, pool::{Handle, Pool}, visitor::{Visit, VisitResult, Visitor}, }, engine::resource_manager::ResourceManager, scene::{ base::BaseBuilder, graph::Graph, node::Node, pivot::PivotBuilder, transform::TransformBuilder, Scene, }, }; use std::{path::Path, sync::mpsc::Sender}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Visit)] pub enum ItemKind { Medkit, // Ammo Plasma, Ak47Ammo, M4Ammo, // Weapons PlasmaGun, Ak47, M4, RocketLauncher, } #[derive(Visit)] pub struct Item { kind: ItemKind, pivot: Handle<Node>, model: Handle<Node>, offset: Vector3<f32>, dest_offset: Vector3<f32>, offset_factor: f32, reactivation_timer: f32, active: bool, #[visit(skip)] pub sender: Option<Sender<Message>>, lifetime: Option<f32>, } impl Default for Item { fn default() -> Self { Self { kind: ItemKind::Medkit, pivot: Default::default(), model: Default::default(), offset: Default::default(), dest_offset: Default::default(), offset_factor: 0.0, reactivation_timer: 0.0, active: true, sender: None, lifetime: None, } } } pub struct ItemDefinition { model: &'static str, scale: f32, reactivation_interval: f32, } impl Item { pub fn get_definition(kind: ItemKind) -> &'static ItemDefinition { match kind { ItemKind::Medkit => { static DEFINITION: ItemDefinition = ItemDefinition { model: "data/models/medkit.fbx", scale: 1.0, reactivation_interval: 20.0, }; &DEFINITION } ItemKind::Plasma => { static DEFINITION: ItemDefinition = ItemDefinition { model: "data/models/yellow_box.FBX", scale: 0.25, reactivation_interval: 15.0, }; &DEFINITION } ItemKind::Ak47Ammo => { static DEFINITION: ItemDefinition = ItemDefinition { model: "data/models/box_medium.FBX", scale: 0.30, reactivation_interval: 14.0, }; &DEFINITION } ItemKind::M4Ammo => { static DEFINITION: ItemDefinition = ItemDefinition { model: "data/models/box_small.FBX", scale: 0.30, reactivation_interval: 13.0, }; &DEFINITION } ItemKind::PlasmaGun => { static DEFINITION: ItemDefinition = ItemDefinition { model: "data/models/plasma_rifle.FBX", scale: 3.0, reactivation_interval: 30.0, }; &DEFINITION } ItemKind::Ak47 => { static DEFINITION: ItemDefinition = ItemDefinition { model: "data/models/ak47.FBX", scale: 3.0, reactivation_interval: 30.0, }; &DEFINITION } ItemKind::M4 => { static DEFINITION: ItemDefinition = ItemDefinition { model: "data/models/m4.FBX", scale: 3.0, reactivation_interval: 30.0, }; &DEFINITION } ItemKind::RocketLauncher => { static DEFINITION: ItemDefinition = ItemDefinition { model: "data/models/Rpg7.FBX", scale: 3.0, reactivation_interval: 30.0, }; &DEFINITION } } } pub async fn new( kind: ItemKind, position: Vector3<f32>, scene: &mut Scene, resource_manager: ResourceManager, sender: Sender<Message>, ) -> Self { let definition = Self::get_definition(kind); let model = resource_manager .request_model(Path::new(definition.model)) .await .unwrap() .instantiate_geometry(scene); let pivot = PivotBuilder::new( BaseBuilder::new().with_local_transform( TransformBuilder::new() .with_local_position(position) .with_local_scale(Vector3::new( definition.scale, definition.scale, definition.scale, )) .build(), ), ) .build(&mut scene.graph); scene.graph.link_nodes(model, pivot); Self { pivot, kind, model, sender: Some(sender), ..Default::default() } } pub fn get_pivot(&self) -> Handle<Node> { self.pivot } pub fn position(&self, graph: &Graph) -> Vector3<f32> { graph[self.pivot].global_position() } pub fn update(&mut self, graph: &mut Graph, time: GameTime) { self.offset_factor += 1.2 * time.delta; let amp = 0.085; self.dest_offset = Vector3::new(0.0, amp + amp * self.offset_factor.sin(), 0.0); self.offset.follow(&self.dest_offset, 0.2); let position = graph[self.pivot].global_position(); let model = &mut graph[self.model]; model.set_visibility(!self.is_picked_up()); model.local_transform_mut().set_position(self.offset); if !self.active { self.reactivation_timer -= time.delta; if self.reactivation_timer <= 0.0 { self.active = true; self.sender .as_ref() .unwrap() .send(Message::CreateEffect { kind: EffectKind::ItemAppear, position, }) .unwrap(); } } } pub fn get_kind(&self) -> ItemKind { self.kind } pub fn definition(&self) -> &'static ItemDefinition { Self::get_definition(self.kind) } pub fn pick_up(&mut self) { self.reactivation_timer = self.definition().reactivation_interval; self.active = false; } pub fn is_picked_up(&self) -> bool { !self.active } fn cleanup(&self, graph: &mut Graph) { graph.remove_node(self.pivot) } fn can_be_removed(&self) -> bool { match self.lifetime { None => false, Some(time) => time <= 0.0 || !self.active, } } pub fn set_lifetime(&mut self, lifetime: Option<f32>) { self.lifetime = lifetime; } } #[derive(Visit)] pub struct ItemContainer { pool: Pool<Item>, } impl Default for ItemContainer { fn default() -> Self { Self::new() } } impl ItemContainer { pub fn new() -> Self { Self { pool: Pool::new() } } pub fn add(&mut self, item: Item) -> Handle<Item> { self.pool.spawn(item) } pub fn get_mut(&mut self, item: Handle<Item>) -> &mut Item { self.pool.borrow_mut(item) } pub fn contains(&self, item: Handle<Item>) -> bool { self.pool.is_valid_handle(item) } pub fn pair_iter(&self) -> impl Iterator<Item = (Handle<Item>, &Item)> { self.pool.pair_iter() } pub fn iter(&self) -> impl Iterator<Item = &Item> { self.pool.iter() } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Item> { self.pool.iter_mut() } pub fn update(&mut self, scene: &mut Scene, time: GameTime) { for item in self.pool.iter_mut() { item.update(&mut scene.graph, time); } // Remove temporary items. for item in self.pool.iter() { if item.can_be_removed() { item.cleanup(&mut scene.graph); } } self.pool.retain(|i| !i.can_be_removed()) } }
use specs::prelude::*; use types::*; use component::flag::IsPlayer; use component::time::{LastFrame, ThisFrame}; pub struct EnergyRegenSystem; #[derive(SystemData)] pub struct EnergyRegenSystemData<'a> { pub lastframe: Read<'a, LastFrame>, pub thisframe: Read<'a, ThisFrame>, pub config: Read<'a, Config>, pub energy: WriteStorage<'a, Energy>, pub plane: ReadStorage<'a, Plane>, pub flag: ReadStorage<'a, IsPlayer>, pub upgrades: ReadStorage<'a, Upgrades>, } impl<'a> System<'a> for EnergyRegenSystem { type SystemData = EnergyRegenSystemData<'a>; fn run(&mut self, data: Self::SystemData) { let Self::SystemData { lastframe, thisframe, config, mut energy, plane, flag, upgrades, } = data; let dt = Time::new((thisframe.0 - lastframe.0).subsec_nanos() as f32 * (60.0 / 1.0e9)); (&mut energy, &plane, &flag, &upgrades) .join() .map(|(energy, plane, _, upgrades)| { let regen = config.planes[*plane].energy_regen; let mult = config.upgrades.energy.factor[upgrades.energy as usize]; (energy, regen * mult) }) .for_each(|(energy, regen)| { let val: Energy = *energy + regen * dt; *energy = Energy::new(val.inner().min(1.0).max(0.0)); }); } } use super::missile::MissileFireHandler; use dispatch::SystemInfo; impl SystemInfo for EnergyRegenSystem { type Dependencies = MissileFireHandler; fn name() -> &'static str { concat!(module_path!(), "::", line!()) } fn new() -> Self { Self {} } }
//! Functions and types related to windows. use controls::Control; use ffi_utils::{self, Text}; use libc::{c_int, c_void}; use std::cell::RefCell; use std::ffi::CString; use std::mem; use ui_sys::{self, uiControl, uiWindow}; thread_local! { static WINDOWS: RefCell<Vec<Window>> = RefCell::new(Vec::new()) } define_control!{ /// Contains a single child control and displays it and its children in a window on the screen. control(Window, uiWindow, ui_window); } impl Window { #[inline] /// Create a new window with the given title, width, and height. /// If `has_menubar` is true, you can add items to the window's menu bar with /// the [`Menu`](struct.Menu.html) struct. pub fn new(title: &str, width: c_int, height: c_int, has_menubar: bool) -> Window { ffi_utils::ensure_initialized(); unsafe { let c_string = CString::new(title.as_bytes().to_vec()).unwrap(); let window = Window::from_ui_window(ui_sys::uiNewWindow( c_string.as_ptr(), width, height, has_menubar as c_int, )); WINDOWS.with(|windows| windows.borrow_mut().push(window.clone())); window } } #[inline] /// Return the inner `libui` pointer. pub fn as_ui_window(&self) -> *mut uiWindow { self.ui_window } #[inline] /// Get the current title of the window. pub fn title(&self) -> Text { ffi_utils::ensure_initialized(); unsafe { Text::new(ui_sys::uiWindowTitle(self.ui_window)) } } #[inline] /// Set the window's title to the given string. pub fn set_title(&self, title: &str) { ffi_utils::ensure_initialized(); unsafe { let c_string = CString::new(title.as_bytes().to_vec()).unwrap(); ui_sys::uiWindowSetTitle(self.ui_window, c_string.as_ptr()) } } #[inline] /// Set a callback to be run when the window closes. /// /// This is often used on the main window of an application to quit /// the application when the window is closed. pub fn on_closing<F: FnMut(&Window) -> bool>(&self, callback: F) { ffi_utils::ensure_initialized(); unsafe { let mut data: Box<Box<FnMut(&Window) -> bool>> = Box::new(Box::new(callback)); ui_sys::uiWindowOnClosing( self.ui_window, c_callback, &mut *data as *mut Box<FnMut(&Window) -> bool> as *mut c_void, ); mem::forget(data); } extern "C" fn c_callback(window: *mut uiWindow, data: *mut c_void) -> i32 { unsafe { let window = Window { ui_window: window }; mem::transmute::<*mut c_void, Box<Box<FnMut(&Window) -> bool>>>(data)(&window) as i32 } } } #[inline] /// Sets the window's child widget. The window can only have one child widget at a time. pub fn set_child(&self, child: Control) { ffi_utils::ensure_initialized(); unsafe { ui_sys::uiWindowSetChild(self.ui_window, child.as_ui_control()) } } #[inline] /// Check whether or not this window has margins around the edges. pub fn margined(&self) -> bool { ffi_utils::ensure_initialized(); unsafe { ui_sys::uiWindowMargined(self.ui_window) != 0 } } #[inline] /// Set whether or not the window has margins around the edges. pub fn set_margined(&self, margined: bool) { ffi_utils::ensure_initialized(); unsafe { ui_sys::uiWindowSetMargined(self.ui_window, margined as c_int) } } #[inline] /// Allow the user to select an existing file. pub fn open_file(&self) -> Option<Text> { unsafe { Text::optional(ui_sys::uiOpenFile(self.as_ui_window())) } } #[inline] /// Allow the user to select a new or existing file. pub fn save_file(&self) -> Option<Text> { unsafe { Text::optional(ui_sys::uiSaveFile(self.as_ui_window())) } } #[inline] /// Open a generic message box to show a message to the user. pub fn msg_box(&self, title: &str, description: &str) { unsafe { let c_title = CString::new(title.as_bytes().to_vec()).unwrap(); let c_description = CString::new(description.as_bytes().to_vec()).unwrap(); ui_sys::uiMsgBox( self.as_ui_window(), c_title.as_ptr(), c_description.as_ptr(), ) } } #[inline] /// Open an error-themed message box to show a message to the user. pub fn msg_box_error(&self, title: &str, description: &str) { unsafe { let c_title = CString::new(title.as_bytes().to_vec()).unwrap(); let c_description = CString::new(description.as_bytes().to_vec()).unwrap(); ui_sys::uiMsgBoxError( self.as_ui_window(), c_title.as_ptr(), c_description.as_ptr(), ) } } #[inline] pub unsafe fn from_ui_window(window: *mut uiWindow) -> Window { Window { ui_window: window } } pub unsafe fn destroy_all_windows() { WINDOWS.with(|windows| { let mut windows = windows.borrow_mut(); for window in windows.drain(..) { window.destroy() } }) } }
//! This crate provides simple API to apply [Simple Linear Image Segmentation](http://infoscience.epfl.ch/record/177415/files/Superpixel_PAMI2011-2.pdf) //! on all types of 3-channel images. It also support SLIC0 variation of SLIC, //! with dynamic normalization of spectral distances. extern crate math; use crate::lab::{rgb_2_lab, sub, LabColor}; use image::{ImageBuffer, RgbImage, Rgba, RgbaImage}; use std::f64::MAX; use std::marker::Copy; pub mod lab; #[derive(Copy, Clone)] struct SuperPixel { label: u32, centroid: LabPixel, } struct AvgValues { l: Vec<f64>, a: Vec<f64>, b: Vec<f64>, x: Vec<f64>, y: Vec<f64>, count: Vec<f64>, distances: u32, } const X_MTX: [i64; 4] = [-1, 0, 1, 0]; const Y_MTX: [i64; 4] = [0, -1, 0, 1]; const X_MTX_8: [i64; 8] = [-1, -1, 0, 1, 1, 1, 0, -1]; const Y_MTX_8: [i64; 8] = [0, -1, -1, -1, 0, 1, 1, 1]; const RESIDUAL_ERROR_THRESHOLD: f64 = 0.0; /// Main SLIC state struct which holds the state for each step /// of clustering process. /// /// This struct is created by the [`slic::get_slic`] function. See its /// documentation for more. /// /// [`slic::get_slic`]: ./fn.get_slic.html pub struct Slic<'a> { /// result amount of superpixels (clusters). pub k: u32, /// value between 0-20. balances color proximity and space proximity. Higher values give more weight to space proximity, making superpixel shapes more square/cubic. In SLICO mode, this is the initial compactness. pub compactness: f64, /// run SLIC-zero, the zero compactness parameter mode of SLIC. pub slic_zero_mode: bool, /// SLIC result Vec<u32>. Labels mask produced on input image. Max label is *k*. pub labels: Vec<i64>, /// reference image target image received in [`slic::get_slic`](./fn.get_slic.html). pub img: &'a RgbImage, n: u32, s: f64, super_pixel_width: u32, super_pixel_height: u32, super_pixels: Vec<SuperPixel>, compactnesses: Vec<f64>, distances: Vec<f64>, lab_image_data: Vec<f64>, } impl Slic<'_> { /// Mutable methods which runs SLIC computations. /// Applies iterations until [residual error](https://en.wikipedia.org/wiki/Errors_and_residuals) will be close to 0. /// Calls enforce connectivity using [Connected Components Algorithm](https://en.wikipedia.org/wiki/Connected-component_labeling) pub fn compute(&mut self) { loop { if self.digest() == RESIDUAL_ERROR_THRESHOLD { break; } } self.labels = self.enforce_connectivity(); } /// Crates 4-channel [`image::RgbaImage`](https://docs.rs/image/0.18.0/image/type.RgbaImage.html) with `self.img` dimensions. /// Draws yellow borders for each cluster on transparent background. /// Moves result variable to caller. /// /// # Examples: /// /// ```no_run /// use slic::get_slic; /// use image::{open}; /// fn main() { /// let mut image = open("./my_image.jpg").ok().expect("Cannot open image"); /// let img = image /// .as_mut_rgb8() /// .expect("Cannot get RGB from DynamicImage"); /// /// let mut slic = get_slic(img, 30, 10.0, true); /// slic.compute(); /// slic.get_borders_image().save("./borders.png").expect("Cannot save image on disk"); /// } /// ``` pub fn get_borders_image(&self) -> RgbaImage { let (width, height) = (self.img.width(), self.img.height()); let total_size = self.n as usize; let (mut border_x, mut border_y, mut already_bordered) = ( vec![0u32; total_size], vec![0u32; total_size], vec![false; total_size], ); let (mut cursor, mut border_pixels_count) = (0usize, 0usize); let mut buffer = ImageBuffer::<Rgba<u8>, Vec<u8>>::new(self.img.width(), self.img.height()); let (yellow, red) = (Rgba([255, 255, 0, 255]), Rgba([255, 0, 0, 255])); for j in 0..height { for k in 0..width { if self.labels[cursor] == 0 { buffer.put_pixel(k, j, red); cursor += 1; continue; } let mut heterogeneity = 0; for i in 0..8 { let x = (k as i64) + X_MTX_8[i]; let y = (j as i64) + Y_MTX_8[i]; if (x >= 0 && (x as u32) < width) && (y >= 0 && (y as u32) < height) { let index = (y * width as i64 + x) as usize; if !already_bordered[index] && self.labels[cursor] != self.labels[index] { heterogeneity += 1; } } } if heterogeneity > 1 { border_x[border_pixels_count] = k; border_y[border_pixels_count] = j; already_bordered[cursor] = true; border_pixels_count += 1; } cursor += 1; } } for j in 0..border_pixels_count { buffer.put_pixel(border_x[j], border_y[j], yellow); } buffer } fn iter(&mut self) { let offset = (self.s).ceil() as u32; for j in 0..self.super_pixels.len() { let pxl = self.super_pixels[j]; let (cx, cy, _) = pxl.centroid; let x1 = if cx > offset { cx - offset } else { 0 }; let y1 = if cy > offset { cy - offset } else { 0 }; let x2 = if cx + offset < self.img.width() { cx + offset } else { self.img.width() - 1 }; let y2 = if cy + offset < self.img.height() { cy + offset } else { self.img.height() - 1 }; let i = (pxl.label - 1) as usize; let compactness = if self.slic_zero_mode { let old_compactness = 100.0 - self.compactnesses[i]; self.compactnesses[i] = 0.0; old_compactness } else { self.compactness }; self.compactnesses[i] = 0.0; for y in y1..(y2 + 1) { for x in x1..(x2 + 1) { let idx = (y * self.img.width() + x) as usize; let prev_distance = self.distances[idx]; // calc distance let pixel = get_lab_pixel(&self.lab_image_data, self.img.width(), x, y); let (color_distance, new_distance) = get_distance(pxl.centroid, pixel, compactness, self.s); if self.slic_zero_mode { let compactness_ratio = f64::min(color_distance, 100.0); if self.compactnesses[i] < compactness_ratio { self.compactnesses[i] = compactness_ratio; }; } if prev_distance > new_distance { self.distances[idx] = new_distance; self.labels[idx] = pxl.label as i64; }; } } } } fn digest(&mut self) -> f64 { self.iter(); self.recompute_centers() } fn recompute_centers(&mut self) -> f64 { let w = self.img.width(); let h = self.img.height(); let k = self.k as usize; let mut values = AvgValues { l: vec![0.0; k], a: vec![0.0; k], b: vec![0.0; k], x: vec![0.0; k], y: vec![0.0; k], count: vec![0.0; k], distances: 0, }; for y in 0..h { for x in 0..w { let label_idx = (y * w + x) as usize; let label = self.labels[label_idx] as usize - 1; self.distances[label] = MAX; let (x, y, color) = get_lab_pixel(&self.lab_image_data, w, x, y); values.x[label] += x as f64; values.y[label] += y as f64; values.l[label] += color[0]; values.a[label] += color[1]; values.b[label] += color[2]; values.count[label] += 1.0; } } self.super_pixels.iter_mut().for_each(|super_pixel| { let label = super_pixel.label as usize - 1; let (cx, cy, _) = super_pixel.centroid; let count = values.count[label]; let l =values.l[label] / count; let a =values.a[label] / count; let b =values.b[label] / count; let x = (values.x[label] / count).round() as u32; let y = (values.y[label] / count).round() as u32; let distance = l1_distance(cx, cy, x, y); values.distances += distance; super_pixel.centroid = (x, y, [l, a, b]); }); values.distances as f64 / self.k as f64 } fn enforce_connectivity(&self) -> (Vec<i64>) { let (w, h) = (self.img.width() as i64, self.img.height() as i64); let image_size = w * h; let super_pixels_count = image_size / (self.super_pixel_height * self.super_pixel_width) as i64; let (super_pixel_size, image_size_usize) = (image_size / super_pixels_count, image_size as usize); let (mut x_coords, mut y_coords) = (vec![0i64; image_size_usize], vec![0i64; image_size_usize]); let (mut main_index, mut adjust_label, mut label) = (0usize, 1i64, 1i64); let mut merged_labels: Vec<i64> = vec![0; image_size_usize]; // connected components row-by-row for j in 0..h { for k in 0..w { if 0 == merged_labels[main_index] { merged_labels[main_index] = label; x_coords[0] = k; y_coords[0] = j; // find adjust label for n in 0usize..4 { let x = x_coords[0] as i64 + X_MTX[n]; let y = y_coords[0] as i64 + Y_MTX[n]; if (x >= 0 && x < w) && (y >= 0 && y < h) { let sub_index = (y * w + x) as usize; if merged_labels[sub_index] > 0 { adjust_label = merged_labels[sub_index] } } } // collect super_pixel, save its real pixel coords into buffer vectors let (mut o, mut order) = (0, 1); while o < order { for n in 0..4 { let x = x_coords[o] + X_MTX[n]; let y = y_coords[o] + Y_MTX[n]; if (x >= 0 && x < w) && (y >= 0 && y < h) { let sub_index = (y * w + x) as usize; if 0 == merged_labels[sub_index] && self.labels[main_index] == self.labels[sub_index] { x_coords[order] = x; y_coords[order] = y; merged_labels[sub_index] = label; order += 1; } } } o += 1; } // filter super_pixels above threshold, assign them to adjust labels using buffer vectors if order as i64 <= super_pixel_size >> 2 { for o in 0..order { let ind = (y_coords[o] * w + x_coords[o]) as usize; merged_labels[ind] = adjust_label } label -= 1; } label += 1; } main_index += 1; } } return merged_labels; } } /// Constructor for [`slic0::Slic`] struct. Produces SLIC state object. /// /// | Argument | Role | /// |:---------------------:|:-----------------------------------------------------------:| /// | *img* | Image ([`image::RgbImage`]) target for SLIC. | /// | *num_of_super_pixels* | Approximate (+/- 3) amount of requested clusters. | /// | *compactness* | balances color proximity and space proximity. Between 0-20. | /// | *slic_zero_mode* | run SLIC-zero, the zero compactness parameter mode of SLIC. | /// /// /// # Examples: /// /// ```no_run /// use slic::get_slic; /// use image::{open}; /// fn main() { /// let mut image = open("./my_image.jpg").ok().expect("Cannot open image"); /// let img = image /// .as_mut_rgb8() /// .expect("Cannot get RGB from DynamicImage"); /// /// let mut slic = get_slic(img, 30, 10.0, true); /// slic.compute(); /// // print labels as ascii symbols art to stdout /// slic.labels.iter().enumerate().for_each(|(i, x)| { /// print!("{}", ((32 + *x) as u8 as char).to_string()); /// if ((i + 1) % img.width() as usize) == 0 { /// println!(); /// } /// }); /// } /// ``` /// /// [`slic0::Slic`]: ./struct.Slic.html /// [`image::RgbImage`]: https://docs.rs/image/0.19.0/image/type.RgbImage.html pub fn get_slic( img: &RgbImage, num_of_clusters: u32, compactness: f64, slic_zero_mode: bool, ) -> Slic { let (w, h) = img.dimensions(); let n = w * h; let (super_pixels_per_width, super_pixels_per_height) = get_clusters_count(num_of_clusters, w, h); let num_of_super_pixels = super_pixels_per_width * super_pixels_per_height; let mut super_pixels: Vec<SuperPixel> = Vec::with_capacity(num_of_super_pixels as usize); let super_pixels_per_height = num_of_super_pixels / super_pixels_per_width; let (left_x, mut left_y) = (w % super_pixels_per_width, h % super_pixels_per_height); let (super_pixel_width, super_pixel_height) = ((w-left_x)/ super_pixels_per_width, (h - left_y) / super_pixels_per_height); let mut lab_image_data = vec![0.0; (n*3) as usize]; for y in 0..h { for x in 0..w { let (_, _, color) = get_lab_pixel_from_image(img, x, y); let idx = ((y * w + x) * 3) as usize; lab_image_data[idx] = color[0]; lab_image_data[idx+1] = color[1]; lab_image_data[idx+2] = color[2]; } } let mut offset_y = 0; for y in 0..super_pixels_per_height { let full_super_pixel_height = super_pixel_height + if left_y != 0 { left_y -= 1; 1} else {0}; let mut left_width = left_x; let mut offset_x = 0; for x in 0..super_pixels_per_width { let full_super_pixel_width = super_pixel_width + if left_width != 0 { left_width -= 1; 1} else {0}; let (sx, sy) = (offset_x, offset_y); let (cx, cy) = ( sx + (full_super_pixel_width as f64 * 0.5_f64).round() as u32, sy + (full_super_pixel_height as f64 * 0.5_f64).round() as u32, ); let label = y * super_pixels_per_width + x + 1; let centroid = get_initial_centroid(&lab_image_data, w, h, cx, cy); super_pixels.push(SuperPixel { label, centroid }); offset_x += full_super_pixel_width; } offset_y += full_super_pixel_height; } let k = super_pixels_per_width * super_pixels_per_height; Slic { k, n, s: (n as f64 / k as f64).sqrt(), super_pixel_width, super_pixel_height, compactness, super_pixels, slic_zero_mode, distances: vec![MAX; n as usize], compactnesses: vec![compactness; k as usize], labels: vec![-1; n as usize], img, lab_image_data, } } fn get_clusters_count(requested_count: u32, w: u32, h: u32) -> (u32, u32) { let cluster_size = w * h / requested_count; let step = ((cluster_size as f64).sqrt() + 0.5) as u32; let mut super_pixels_per_width = (0.5 + w as f64/step as f64) as u32; let mut super_pixels_per_height = (0.5 + h as f64/step as f64) as u32; let residual_for_x = w as i64 - (step*super_pixels_per_width) as i64; let residual_for_y = h as i64 - (step*super_pixels_per_height) as i64; if residual_for_x < 0 { super_pixels_per_width -= 1; } if residual_for_y < 0 { super_pixels_per_height -= 1; } (super_pixels_per_width, super_pixels_per_height) } fn get_initial_centroid(lab_image_data: &Vec<f64>, w: u32, h: u32, cx: u32, cy: u32) -> LabPixel { let (_, pxl) = get_pixel_3x3_neighbourhood(lab_image_data, w, h, cx, cy) .into_iter() .flatten() .fold((MAX, None), |acc, option| { if let Some(next_pxl) = option { let (prev_gradient, _) = acc; let (x, y, _) = next_pxl; let next_gradient = get_gradient_position(lab_image_data, w, h, *x, *y); if next_gradient <= prev_gradient { (next_gradient, Some(*next_pxl)) } else { acc } } else { acc } }); pxl.unwrap() } fn get_lab_pixel(lab_data: &Vec<f64>, w: u32, x: u32, y: u32) -> LabPixel { let i = ((y * w + x) * 3) as usize; ( x, y, [lab_data[i], lab_data[i+1], lab_data[i+2]], ) } fn get_lab_pixel_from_image(img: &RgbImage, x: u32, y: u32) -> LabPixel { let pxl = *img.get_pixel(x, y); ( x, y, rgb_2_lab([f64::from(pxl[0]), f64::from(pxl[1]), f64::from(pxl[2])]), ) } fn get_pixel_cross_neighbourhood( lab_image_data: &Vec<f64>, w: u32, h: u32, x: u32, y: u32, ) -> ( Option<LabPixel>, Option<LabPixel>, Option<LabPixel>, Option<LabPixel>, ) { ( if x != 0 { Some(get_lab_pixel(lab_image_data, w, x - 1, y)) } else { None }, if x + 1 < w { Some(get_lab_pixel(lab_image_data, w, x + 1, y)) } else { None }, if y != 0 { Some(get_lab_pixel(lab_image_data, w, x, y - 1)) } else { None }, if y + 1 < h { Some(get_lab_pixel(lab_image_data, w, x, y + 1)) } else { None }, ) } fn get_pixel_3x3_neighbourhood(lab_image_data: &Vec<f64>, w: u32, h: u32, x: u32, y: u32) -> ([[Option<LabPixel>; 3]; 3]) { let pxl = get_lab_pixel(lab_image_data, w, x, y); let (left, right, top, bottom) = get_pixel_cross_neighbourhood(lab_image_data, w, h, x, y); let top_left = if x != 0 && y != 0 { Some(get_lab_pixel(lab_image_data, w, x - 1, y - 1)) } else { None }; let bottom_left = if x != 0 && y + 1 < h { Some(get_lab_pixel(lab_image_data, w, x - 1, y + 1)) } else { None }; let top_right = if x + 1 < w && y != 0 { Some(get_lab_pixel(lab_image_data, w, x + 1, y - 1)) } else { None }; let bottom_right = if x + 1 < w && y + 1 < h { Some(get_lab_pixel(lab_image_data, w, x + 1, y + 1)) } else { None }; [ [top_left, top, top_right], [left, Some(pxl), right], [bottom_left, bottom, bottom_right], ] } fn get_gradient_position(lab_image_data: &Vec<f64>, w: u32, h: u32, x: u32, y: u32) -> f64 { let pxl = get_lab_pixel(lab_image_data, w, x, y); let (left, right, top, bottom) = get_pixel_cross_neighbourhood(lab_image_data, w, h, x, y); let left_color = get_neighbour_color_vector(&pxl, left); let right_color = get_neighbour_color_vector(&pxl, right); let top_color = get_neighbour_color_vector(&pxl, top); let bottom_color = get_neighbour_color_vector(&pxl, bottom); l2_norm(sub(right_color, left_color)).powf(2_f64) + l2_norm(sub(bottom_color, top_color)).powf(2_f64) } fn get_neighbour_color_vector(pxl: &LabPixel, neighbour: Option<LabPixel>) -> LabColor { if let Some(n_pxl) = neighbour { let (_, _, n_color) = n_pxl; n_color } else { // if no neighbour return original pixel let (_, _, color) = *pxl; color } } fn l2_norm(y: LabColor) -> f64 { y.iter() .fold(0f64, |sum, &ey| sum + (ey.abs()).powf(2.)) .sqrt() } fn l1_distance(x1: u32, y1: u32, x2: u32, y2: u32) -> u32 { ((x1 as i64 - x2 as i64).abs() + (y1 as i64 - y2 as i64).abs()) as u32 } fn get_color_distance(p1: LabColor, p2: LabColor) -> f64 { ((p1[0] - p2[0]).powi(2) + (p1[1] - p2[1]).powi(2) + (p1[2] - p2[2]).powi(2)).sqrt() } fn get_spacial_distance(p1: (u32, u32), p2: (u32, u32)) -> f64 { let (p1x, p1y) = p1; let (p2x, p2y) = p2; (((p1x as i64 - p2x as i64) as f64).powi(2) + ((p1y as i64 - p2y as i64) as f64).powi(2)) .sqrt() } fn get_distance(p1: LabPixel, p2: LabPixel, m: f64, s: f64) -> (f64, f64) { let (p1x, p1y, color_p1) = p1; let (p2x, p2y, color_p2) = p2; let color_distance = get_color_distance(color_p1, color_p2); ( color_distance, color_distance + m / s * get_spacial_distance((p1x, p1y), (p2x, p2y)) ) } type LabPixel = (u32, u32, LabColor); #[cfg(test)] mod tests;
#![recursion_limit = "256"] #![allow(clippy::expect_fun_call)] #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] //! delicate-scheduler. #[macro_use] extern crate diesel; #[macro_use] extern crate serde; #[macro_use] extern crate diesel_migrations; pub(crate) mod actions; pub(crate) mod components; pub(crate) mod db; pub(crate) mod prelude; #[macro_use] pub(crate) mod macros; pub(crate) use prelude::*; use {cfg_mysql_support, cfg_postgres_support}; #[actix_web::main] async fn main() -> AnyResut<()> { // Loads environment variables. dotenv().ok(); db::init(); let scheduler_listening_address = env::var("SCHEDULER_LISTENING_ADDRESS") .expect("Without `SCHEDULER_LISTENING_ADDRESS` set in .env"); let scheduler_front_end_domain: String = env::var("SCHEDULER_FRONT_END_DOMAIN") .expect("Without `SCHEDULER_FRONT_END_DOMAIN` set in .env"); FmtSubscriber::builder() // will be written to stdout. .with_max_level(Level::INFO) .with_thread_names(true) // completes the builder. .init(); let delay_timer = DelayTimerBuilder::default().enable_status_report().build(); let shared_delay_timer = ShareData::new(delay_timer); let connection_pool = db::get_connection_pool(); let shared_connection_pool = ShareData::new(connection_pool); let shared_scheduler_meta_info: SharedSchedulerMetaInfo = ShareData::new(SchedulerMetaInfo::default()); let result = HttpServer::new(move || { let cors = Cors::default() .allowed_origin(&scheduler_front_end_domain) .allow_any_method() .allow_any_header() .supports_credentials() .max_age(3600); App::new() .configure(actions::task::config) .configure(actions::user::config) .configure(actions::task_log::config) .configure(actions::executor_group::config) .configure(actions::executor_processor::config) .configure(actions::executor_processor_bind::config) .configure(actions::data_reports::config) .configure(actions::components::config) .app_data(shared_delay_timer.clone()) .app_data(shared_connection_pool.clone()) .app_data(shared_scheduler_meta_info.clone()) .wrap(components::session::auth_middleware()) .wrap(components::session::session_middleware()) .wrap(cors) .wrap(MiddlewareLogger::default()) }) .bind(scheduler_listening_address)? .run() .await; Ok(result?) }
fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn check(v: &Vec<i32>, n: i32, a0: i32, a1: i32) -> Option<Vec<i32>> { let mut a: Vec<i32> = vec![]; a.push(a0); a.push(a1); for i in 0..n { let tmp1 = a[i as usize]; let tmp2 = a[(i + 1) as usize]; let tmp = tmp1 * tmp2 * v[((i + 1) % n) as usize]; a.push(tmp); } if a0 == a[n as usize] && a1 == a[(n + 1) as usize] { Some(a.clone()) } else { None } } fn main() { let n: i32 = read(); let s: String = read(); let v: Vec<i32> = s.chars().map(|e| if e == 'o' { 1 } else { -1 }).collect(); if let Some(a) = check(&v, n, 1, 1) { for i in 0..n { if a[i as usize] == 1 { print!("S"); } else { print!("W"); } } } else if let Some(a) = check(&v, n, 1, -1) { for i in 0..n { if a[i as usize] == 1 { print!("S"); } else { print!("W"); } } } else if let Some(a) = check(&v, n, -1, 1) { for i in 0..n { if a[i as usize] == 1 { print!("S"); } else { print!("W"); } } } else if let Some(a) = check(&v, n, -1, -1) { for i in 0..n { if a[i as usize] == 1 { print!("S"); } else { print!("W"); } } } else { print!("-1"); } println!(""); }
use crate::backend::{DrawBackend, Resources}; use crate::draw::{Color, DrawContext}; use crate::event::{Event, EventDispatcher}; use crate::geometry::{Position, Size}; use crate::toplevel::TopLevel; use crate::widget::Widget; use std::ops; pub const DEFAULT_WINDOW_SIZE: Size = Size::new(320, 240); /// Top level Window. #[derive(Debug, Clone, Default)] pub struct Window<T> { /// The window attributes. pub attr: WindowAttributes, /// Event dispatcher dispatcher: EventDispatcher, /// Window content. pub child: T, } impl<T> Window<T> { /// Creates a new window with default attributes. pub fn new(child: T) -> Self { Window { attr: Default::default(), dispatcher: Default::default(), child, } } /// Creates a new window with the specified attributes. pub fn new_with_attr(child: T, attr: WindowAttributes) -> Self { Window { attr, dispatcher: Default::default(), child, } } } impl<T: Widget> TopLevel for Window<T> { fn update_layout<R: Resources>(&mut self, resources: &mut R) { if self.size.is_zero_area() { // our size is unset, first try to get the default content size let initial = self .child .get_bounds() .expand_to_origin() .map_size(|s| s.nonzero_or(DEFAULT_WINDOW_SIZE)); // if we failed to get a size then use a default // update the child's size using this size as our viewport self.child.update_layout(initial, resources); // set our size to the calculated content size let updated = self.child.get_bounds().expand_to_origin().size.nonzero_or(DEFAULT_WINDOW_SIZE); self.set_size(updated); } else { // we alread have a size, only update child self.child.update_layout(self.size.into(), resources); } } fn draw<B: DrawBackend>(&self, backend: &mut B) { let mut dc = DrawContext::new(backend, self.size.into()); dc.draw_child(&self.child); } fn push_event(&mut self, event: Event) -> bool { self.dispatcher.dispatch_event(event, self.size, &mut self.child) } #[inline] fn get_attr(&self) -> &WindowAttributes { &self.attr } #[inline] fn get_attr_mut(&mut self) -> &mut WindowAttributes { &mut self.attr } } impl<T> ops::Deref for Window<T> { type Target = WindowAttributes; #[inline] fn deref(&self) -> &Self::Target { &self.attr } } impl<T> ops::DerefMut for Window<T> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.attr } } /// The attributes of a window. #[derive(Debug, Clone, PartialEq)] pub struct WindowAttributes { pub title: Option<String>, pub position: Option<Position>, pub size: Size, pub min_size: Size, pub max_size: Size, pub background: Option<Color>, pub resizable: bool, pub maximized: bool, pub transparent: bool, pub always_on_top: bool, pub decorations: bool, } impl WindowAttributes { #[inline] pub fn set_title(&mut self, title: impl Into<String>) { self.title = Some(title.into()); } #[inline] pub fn set_position(&mut self, position: impl Into<Position>) { self.position = Some(position.into()) } #[inline] pub fn set_size(&mut self, size: impl Into<Size>) { self.size = size.into(); } #[inline] pub fn set_min_size(&mut self, size: impl Into<Size>) { self.min_size = size.into(); } #[inline] pub fn set_max_size(&mut self, size: impl Into<Size>) { self.max_size = size.into(); } #[inline] pub fn set_background(&mut self, background: impl Into<Color>) { self.background = Some(background.into()) } } impl Default for WindowAttributes { #[inline] fn default() -> Self { WindowAttributes { title: None, position: None, size: Size::zero(), min_size: Size::zero(), max_size: Size::zero(), background: Some(Color::BLACK), resizable: true, maximized: false, transparent: false, always_on_top: false, decorations: true, } } }
pub fn is_cli_colorized() -> bool { if let Some(_) = option_env!("NO_COLOR") { return false; } if let Some(clicolor_force) = option_env!("CLICOLOR_FORCE") { if clicolor_force != "0" { return true; } } false }
use crate::{Net, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_types::prelude::Unpack; use log::info; pub struct TemplateSizeLimit; impl Spec for TemplateSizeLimit { crate::name!("template_size_limit"); fn run(&self, net: &mut Net) { let node = &net.nodes[0]; node.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize); info!("Generate 1 block"); let blank_block = node.new_block(None, None, None); node.submit_block(&blank_block); let blank_block_size = blank_block.data().serialized_size_without_uncle_proposals(); info!("Generate 6 txs"); let mut txs_hash = Vec::new(); let block = node.get_tip_block(); let cellbase = &block.transactions()[0]; let capacity = cellbase.outputs().get(0).unwrap().capacity().unpack(); let tx = node.new_transaction_with_since_capacity(cellbase.hash(), 0, capacity); let tx_size = tx.data().serialized_size_in_block(); info!( "blank_block_size: {}, tx_size: {}", blank_block_size, tx_size ); let mut hash = node.rpc_client().send_transaction(tx.data().into()); txs_hash.push(hash.clone()); (0..5).for_each(|_| { let tx = node.new_transaction_with_since_capacity(hash.clone(), 0, capacity); hash = node.rpc_client().send_transaction(tx.data().into()); txs_hash.push(hash.clone()); }); // skip proposal window node.generate_block(); node.generate_block(); let new_block = node.new_block(None, None, None); assert_eq!( new_block.data().serialized_size_without_uncle_proposals(), blank_block_size + tx_size * 6 ); // 6 txs + 1 cellbase tx assert_eq!(new_block.transactions().len(), 7); for bytes_limit in (1000..=2000).step_by(100) { let new_block = node.new_block(Some(bytes_limit), None, None); let tx_num = ((bytes_limit as usize) - blank_block_size) / tx_size; assert_eq!(new_block.transactions().len(), tx_num + 1); } } }
use std::collections::HashMap; use std::fs::File; use std::io::Write; use bio::io::fastq; use fastq_pair; use neighborhood::*; #[derive(Debug)] pub struct Config { pub barcode_fastq: String, pub sequ_fastq: String, pub out_fastq: String, pub out_barcodes: Option<String>, pub out_barcode_freqs: Option<String>, pub neighborhood: Option<String>, } pub fn bc_seqs(config: Config) -> Result<(), failure::Error> { let barcode_reader = fastq::Reader::from_file(&config.barcode_fastq)?; let sequ_reader = fastq::Reader::from_file(&config.sequ_fastq)?; let mut fastq_writer = fastq::Writer::to_file(&config.out_fastq)?; let mut barcode_recs = HashMap::new(); let pair_records = fastq_pair::PairRecords::new(barcode_reader.records(), sequ_reader.records()); for pair_result in pair_records { let (barcode_record, sequ_record) = pair_result?; let barcode = barcode_record.seq().to_vec(); let recs = barcode_recs.entry(barcode).or_insert_with(|| Vec::new()); recs.push(sequ_record); } let bc_recs = if let Some(nbhd_filename) = config.neighborhood { let nbhds_raw = Neighborhood::gather_neighborhoods(barcode_recs); let mut nbhds: Vec<_> = nbhds_raw.into_iter().map(|n| n.into_sorted()).collect(); nbhds.sort_unstable_by(|nbhdl, nbhdr| nbhdl.key_barcode().0.cmp(nbhdr.key_barcode().0)); let mut nbhd_recs = Vec::new(); let mut nbhd_counts = Vec::new(); for nbhd in nbhds { nbhd_counts.push(nbhd.to_counts()); let barcode = nbhd.key_barcode().0.to_vec(); let recs = nbhd.into_barcodes().flat_map(|(_, recs)| recs.into_iter()).collect(); nbhd_recs.push((barcode, recs)); } SortedNeighborhood::write_tables(&nbhd_filename, nbhd_counts.iter())?; nbhd_recs } else { let mut bc_recs: Vec<(Vec<u8>, Vec<fastq::Record>)> = barcode_recs.into_iter().collect(); bc_recs.sort_unstable_by(|(bcl, _recsl), (bcr, _recsr)| bcl.cmp(bcr)); bc_recs }; if let Some(barcode_filename) = config.out_barcodes { let barcode_writer = File::create(barcode_filename)?; write_barcode_table(barcode_writer, bc_recs.iter())?; } if let Some(freq_filename) = config.out_barcode_freqs { let freq_writer = File::create(freq_filename)?; write_freq_table(freq_writer, bc_recs.iter())?; } for (bc, recs) in bc_recs { let barcode = String::from_utf8(bc)?; for (recidx, rec) in recs.into_iter().enumerate() { let name = format!("{}_{}", barcode, recidx + 1); let named_record = fastq::Record::with_attrs(&name, None, rec.seq(), rec.qual()); fastq_writer.write_record(&named_record)?; } } Ok(()) } fn write_barcode_table<'i, W, I, A: 'i>( barcode_out: W, barcode_iter: I, ) -> Result<(), failure::Error> where W: std::io::Write, I: Iterator<Item = &'i (Vec<u8>, Vec<A>)> { let mut bcout = std::io::BufWriter::new(barcode_out); for (barcode, entries) in barcode_iter { bcout.write(barcode)?; bcout.write("\t".as_bytes())?; bcout.write(entries.len().to_string().as_bytes())?; bcout.write("\n".as_bytes())?; } Ok(()) } fn write_freq_table<'i, W, I, A: 'i>( freq_out: W, barcode_iter: I, ) -> Result<(), failure::Error> where W: std::io::Write, I: Iterator<Item = &'i (Vec<u8>, Vec<A>)> { let mut fout = std::io::BufWriter::new(freq_out); let mut freq_counts = HashMap::new(); for freq in barcode_iter { let freq_count = freq_counts.entry(freq.1.len()).or_insert(0); *freq_count += 1; } let mut freqs: Vec<usize> = freq_counts.keys().map(|&k| k).collect(); freqs.sort(); for freq in freqs { write!(fout, "{}\t{}\n", freq, freq_counts.get(&freq).unwrap_or(&0))?; } Ok(()) }
#![allow(clippy::module_inception)] #![allow(clippy::too_many_arguments)] #![allow(clippy::ptr_arg)] #![allow(clippy::large_enum_variant)] #![doc = "generated by AutoRust 0.1.0"] #[cfg(feature = "package-2021-06.14.0")] pub mod package_2021_06_14_0; #[cfg(all(feature = "package-2021-06.14.0", not(feature = "no-default-version")))] pub use package_2021_06_14_0::{models, operations, operations::Error}; #[cfg(feature = "package-2020-09.12.0")] pub mod package_2020_09_12_0; #[cfg(all(feature = "package-2020-09.12.0", not(feature = "no-default-version")))] pub use package_2020_09_12_0::{models, operations, operations::Error}; #[cfg(feature = "package-2020-03.11.0")] pub mod package_2020_03_11_0; #[cfg(all(feature = "package-2020-03.11.0", not(feature = "no-default-version")))] pub use package_2020_03_11_0::{models, operations, operations::Error}; #[cfg(feature = "package-2019-08.10.0")] pub mod package_2019_08_10_0; #[cfg(all(feature = "package-2019-08.10.0", not(feature = "no-default-version")))] pub use package_2019_08_10_0::{models, operations, operations::Error}; #[cfg(feature = "package-2019-06.9.0")] pub mod package_2019_06_9_0; #[cfg(all(feature = "package-2019-06.9.0", not(feature = "no-default-version")))] pub use package_2019_06_9_0::{models, operations, operations::Error}; #[cfg(feature = "package-2018-12.8.0")] pub mod package_2018_12_8_0; #[cfg(all(feature = "package-2018-12.8.0", not(feature = "no-default-version")))] pub use package_2018_12_8_0::{models, operations, operations::Error}; #[cfg(feature = "package-2018-08.7.0")] pub mod package_2018_08_7_0; #[cfg(all(feature = "package-2018-08.7.0", not(feature = "no-default-version")))] pub use package_2018_08_7_0::{models, operations, operations::Error}; #[cfg(feature = "package-2018-03.6.1")] pub mod package_2018_03_6_1; #[cfg(all(feature = "package-2018-03.6.1", not(feature = "no-default-version")))] pub use package_2018_03_6_1::{models, operations, operations::Error}; #[cfg(feature = "package-2017-09.6.0")] pub mod package_2017_09_6_0; #[cfg(all(feature = "package-2017-09.6.0", not(feature = "no-default-version")))] pub use package_2017_09_6_0::{models, operations, operations::Error}; #[cfg(feature = "package-2017-06.5.1")] pub mod package_2017_06_5_1; use azure_core::setters; #[cfg(all(feature = "package-2017-06.5.1", not(feature = "no-default-version")))] pub use package_2017_06_5_1::{models, operations, operations::Error}; pub fn config( http_client: std::sync::Arc<dyn azure_core::HttpClient>, token_credential: Box<dyn azure_core::TokenCredential>, ) -> OperationConfigBuilder { OperationConfigBuilder { http_client, base_path: None, token_credential, token_credential_resource: None, } } pub struct OperationConfigBuilder { http_client: std::sync::Arc<dyn azure_core::HttpClient>, base_path: Option<String>, token_credential: Box<dyn azure_core::TokenCredential>, token_credential_resource: Option<String>, } impl OperationConfigBuilder { setters! { base_path : String => Some (base_path) , token_credential_resource : String => Some (token_credential_resource) , } pub fn build(self) -> OperationConfig { OperationConfig { http_client: self.http_client, base_path: self.base_path.unwrap_or_else(|| "https://management.azure.com".to_owned()), token_credential: Some(self.token_credential), token_credential_resource: self .token_credential_resource .unwrap_or_else(|| "https://management.azure.com/".to_owned()), } } } pub struct OperationConfig { http_client: std::sync::Arc<dyn azure_core::HttpClient>, base_path: String, token_credential: Option<Box<dyn azure_core::TokenCredential>>, token_credential_resource: String, } impl OperationConfig { pub fn http_client(&self) -> &dyn azure_core::HttpClient { self.http_client.as_ref() } pub fn base_path(&self) -> &str { self.base_path.as_str() } pub fn token_credential(&self) -> Option<&dyn azure_core::TokenCredential> { self.token_credential.as_deref() } pub fn token_credential_resource(&self) -> &str { self.token_credential_resource.as_str() } }
use serde::Deserialize; use crate::models::media::Media; use crate::models::AniListID; #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AiringSchedule { /// The time the episode airs at airing_at: i64, /// The airing episode number episode: u32, /// The id of the airing schedule item pub id: AniListID, /// The associate media of the airing episode pub media: Media, /// The associate media id of the airing episode media_id: AniListID, /// Seconds until episode starts airing time_until_airing: i64, }
use async_trait::async_trait; use common::result::Result; use crate::domain::role::{Role, RoleId}; #[async_trait] pub trait RoleRepository: Sync + Send { async fn find_all(&self) -> Result<Vec<Role>>; async fn find_by_id(&self, id: &RoleId) -> Result<Role>; async fn save(&self, role: &mut Role) -> Result<()>; }
pub mod player_controller;
use log::{debug, error, warn}; use serde::{Deserialize, Serialize}; use super::InfocomError; use super::memory::{MemoryMap, Version}; use super::state::FrameStack; use super::text::Decoder; #[derive(Serialize, Deserialize, Clone)] struct Property { number: usize, address: usize, size: u16, data_address: usize, data: Vec<u8>, } impl Property { fn load(mem: &MemoryMap, prop_addr: usize) -> Result<Option<Property>, InfocomError> { let size_byte = mem.get_byte(prop_addr)?; if size_byte == 0 { return Ok(None); } let (number, size, skip) = match mem.version { Version::V(1) | Version::V(2) | Version::V(3) => { let size = (size_byte as u16 / 32) + 1; let number = size_byte as usize & 0x1F; (number, size, 1) }, Version::V(4) | Version::V(5) | Version::V(6) | Version::V(7) | Version::V(8) => { if size_byte & 0x80 == 0x80 { let size_byte_2 = mem.get_byte(prop_addr + 1)? as u16; let size:u16 = if size_byte_2 & 0x3F == 0 { 64 } else { size_byte_2 & 0x3F }; let number = size_byte as usize & 0x3F; (number, size, 2) } else { let size = match size_byte & 0x40 { 0x40 => 2, _ => 1 }; let number = size_byte as usize & 0x3F; (number, size, 1) } }, _ => return Err(InfocomError::Version(mem.version)) }; let mut data:Vec<u8> = Vec::new(); for i in 0..size { data.push(mem.get_byte(prop_addr + skip + i as usize)?); } Ok(Some(Property { number, address: prop_addr, size, data_address: prop_addr + skip, data })) } fn save(&self, state: &mut FrameStack) -> Result<(), InfocomError> { for (i, d) in self.data.iter().enumerate() { state.set_byte(self.data_address + i, *d)?; } Ok(()) } } #[derive(Serialize, Deserialize, Clone)] struct PropertyTable { address: usize, short_name: String, properties: Vec<Property>, } #[derive(Serialize, Deserialize)] pub struct Object { number: usize, address: usize, attribute_count: usize, attributes: u64, parent: u16, sibling: u16, child: u16, property_table: PropertyTable } pub struct ObjectTable { address: usize, default_properties: Vec<u16>, } impl PropertyTable { fn load(mem: &MemoryMap, address: usize) -> Result<PropertyTable, InfocomError> { let short_name_size = mem.get_byte(address)? as usize; let decoder = Decoder::new(mem)?; let short_name = if short_name_size > 0 { decoder.decode(address + 1)? } else { String::new() }; let mut properties: Vec<Property> = Vec::new(); let mut prop_addr = address + 1 + (short_name_size * 2); loop { match Property::load(mem, prop_addr)? { Some(p) => { prop_addr = p.data_address + p.size as usize; properties.push(p); } None => { break; } } }; Ok(PropertyTable { address, short_name, properties }) } fn get_property(&self, property_number: usize) -> Option<&Property> { for p in self.properties.iter() { if p.number == property_number { return Some(p); } } None } fn set_property(&mut self, property_number: usize, value: u16) -> Result<(), InfocomError> { if let Some(p) = self.get_property(property_number) { if p.size < 3 { // Rebuild the property table, replacing the updated Property data let mut new_t:Vec<Property> = Vec::new(); for o_p in self.properties.iter() { if o_p.number != property_number { new_t.push(Property { data: Vec::from(o_p.data.clone()), .. *o_p}); } else { new_t.push(Property { data: if p.size == 1 { vec![value as u8 & 0xFF] } else { vec![((value >> 8) as u8 & 0xFF), value as u8 & 0xFF] }, .. *p }); } } self.properties = new_t; Ok(()) } else { Err(InfocomError::Memory(format!("Write to property ${:02x} with length greater than 2", property_number))) } } else { Err(InfocomError::Memory(format!("Write to property ${:02x} that does not exist", property_number))) } } fn save_property(&self, state: &mut FrameStack, property_number: usize) -> Result<(), InfocomError> { for p in &self.properties { if p.number == property_number { return p.save(state) } } Err(InfocomError::Memory(format!("Save of unowned property: ${:02}", property_number))) } } impl Object { fn load(mem: &MemoryMap, number: usize, address: usize) -> Result<Object, InfocomError> { match mem.version { Version::V(1) | Version::V(2) | Version::V(3) => { let attr_1 = mem.get_word(address)?; let attr_2 = mem.get_word(address + 2)?; let attributes:u64 = (((attr_1 as u64) << 16) & 0xFFFF0000) | ((attr_2 as u64) & 0xFFFF); let parent = mem.get_byte(address + 4)? as u16; let sibling = mem.get_byte(address + 5)? as u16; let child = mem.get_byte(address + 6)? as u16; let prop_addr = mem.get_word(address + 7)? as usize; let property_table = PropertyTable::load(mem, prop_addr)?; Ok(Object{ number, address, attribute_count: 32, attributes, parent, sibling, child, property_table}) }, _ => { let attr_1 = mem.get_word(address)?; let attr_2 = mem.get_word(address + 2)?; let attr_3 = mem.get_word(address + 4)?; let attributes:u64 = (((attr_1 as u64) << 32) & 0xFFFF00000000) | (((attr_2 as u64) << 16)& 0xFFFF0000) | (attr_3 as u64) & 0xFFFF; let parent = mem.get_word(address + 6)? as u16; let sibling = mem.get_word(address + 8)? as u16; let child = mem.get_word(address + 10)? as u16; let prop_addr = mem.get_word(address + 12)? as usize; let property_table = PropertyTable::load(mem, prop_addr)?; Ok(Object{ number, address, attribute_count: 48, attributes, parent, sibling, child, property_table}) } } } pub fn save_family(&self, state: &mut FrameStack) -> Result<(), InfocomError> { match state.get_memory().version { Version::V(1) | Version::V(2) | Version::V(3) => { state.set_byte(self.address + 4, self.parent as u8)?; state.set_byte(self.address + 5, self.sibling as u8)?; state.set_byte(self.address + 6, self.child as u8)?; }, _ => { state.set_word(self.address + 6, self.parent)?; state.set_word(self.address + 8, self.sibling)?; state.set_word(self.address + 10, self.child)?; } } Ok(()) } pub fn save_attributes(&self, state: &mut FrameStack) -> Result<(), InfocomError> { match state.get_memory().version { Version::V(1) | Version::V(2) | Version::V(3) => { let attr_1:u16 = ((self.attributes >> 16) & 0xFFFF) as u16; let attr_2:u16 = (self.attributes & 0xFFFF) as u16; state.set_word(self.address, attr_1)?; state.set_word(self.address + 2, attr_2)?; }, _ => { let attr_1 = ((self.attributes >> 32) & 0xFFFF) as u16; let attr_2 = ((self.attributes >> 16) & 0xFFFF) as u16; let attr_3 = (self.attributes & 0xFFFF) as u16; state.set_word(self.address, attr_1)?; state.set_word(self.address + 2, attr_2)?; state.set_word(self.address + 4, attr_3)?; } } Ok(()) } pub fn save_property(&self, state: &mut FrameStack, property_number: usize) -> Result<(), InfocomError> { self.property_table.save_property(state, property_number) } pub fn get_short_name(&self) -> String { self.property_table.short_name.clone() } pub fn get_parent(&self) -> u16 { self.parent } pub fn get_sibling(&self) -> u16 { self.sibling } pub fn get_child(&self) -> u16 { self.child } pub fn has_attribute(&self, attribute: usize) -> Result<bool, InfocomError> { if attribute <= self.attribute_count { Ok(self.attributes >> (self.attribute_count - attribute - 1) & 0x1 == 0x1) } else { Err(InfocomError::Memory(format!("Invalid attribute ${:02x}", attribute))) } } pub fn set_attribute(&mut self, attribute: usize) -> Result<u64, InfocomError> { if attribute <= self.attribute_count { let mask:u64 = 1 << (self.attribute_count - attribute - 1); let attributes = self.attributes | mask; self.attributes = attributes; Ok(attributes) } else { warn!("Attempt to set an invalid attribute: ${:02x}", attribute); Ok(self.attributes) } } pub fn clear_attribute(&mut self, attribute: usize) -> Result<u64, InfocomError> { if attribute <= self.attribute_count { let mut mask:u64 = 0; for _ in 0..(self.attribute_count / 8) { mask = mask << 8 | 0xFF; } let bit:u64 = 1 << (self.attribute_count - attribute - 1); mask ^= bit; let attributes = self.attributes & mask; self.attributes = attributes; Ok(attributes) } else { warn!("Attempt to set an invalid attribute: ${:02x}", attribute); Ok(self.attributes) } } fn get_property(&self, property: usize) -> Option<&Property> { self.property_table.get_property(property) } fn set_property(&mut self, property_number: usize, value: u16) -> Result<(), InfocomError> { self.property_table.set_property(property_number, value) } fn next_property_number(&self, property: usize) -> Result<u8, InfocomError> { let mut i = self.property_table.properties.iter(); if property == 0 { if let Some(r) = i.next() { return Ok(r.number as u8); } else { return Ok(0); } } while let Some(p) = i.next() { if p.number == property { if let Some(r) = i.next() { return Ok(r.number as u8); } else { return Ok(0); } } } Err(InfocomError::Memory(format!("Next property for object ${:04x} after ${:02x} - starting property not found", self.number, property))) } } impl ObjectTable { pub fn new(mem: &MemoryMap) -> Result<ObjectTable, InfocomError> { let address = mem.get_word(0x0a)? as usize; let mut default_properties:Vec<u16> = Vec::new(); match mem.version { Version::V(1) | Version::V(2) | Version::V(3) => { for i in 0..31 { let v = mem.get_word(address + (2 * i))?; default_properties.push(v); } }, Version::V(4) | Version::V(5) | Version::V(6) | Version::V(7) | Version::V(8) => { for i in 0..63 { let v = mem.get_word(address + (2 * i))?; default_properties.push(v); } }, _ => return Err(InfocomError::Version(mem.version)) } debug!("${:04x}, default properties: {:?}", address, default_properties); Ok(ObjectTable { address, default_properties }) } pub fn get_object(&self, memory: &MemoryMap, object_number: usize) -> Result<Object, InfocomError> { let object_address = match memory.version { Version::V(1) | Version::V(2) | Version::V(3) => { self.address + 62 + ((object_number - 1) * 9) }, _ => self.address + 126 + ((object_number - 1) * 14) }; let o = Object::load(memory, object_number, object_address)?; Ok(o) } pub fn remove_object(&mut self, state: &mut FrameStack, object_number: usize) -> Result<Object, InfocomError> { let mut o = self.get_object(state.get_memory(), object_number)?; debug!("remove object: {}, having sibling {}, from {}", object_number, o.sibling, o.parent); if o.parent != 0 { let mut p = self.get_object(state.get_memory(), o.parent as usize)?; if p.child == object_number as u16 { // Object is first child of parent, replace parent's child with this object's sibling debug!("first child"); p.child = o.sibling; p.save_family(state)?; } else { // Object is a sibling, replace sibling reference let mut prev = self.get_object(state.get_memory(), p.child as usize)?; while prev.sibling != object_number as u16 { prev = self.get_object(state.get_memory(), prev.sibling as usize)?; } debug!("Sibling of {}", prev.number); prev.sibling = o.sibling; prev.save_family(state)?; } o.parent = 0; o.sibling = 0; debug!("save object"); o.save_family(state)?; } Ok(o) } pub fn insert_object(&mut self, state: &mut FrameStack, object_number: usize, new_parent: usize) -> Result<Object, InfocomError> { let mut o = self.remove_object(state, object_number)?; let mut p = self.get_object(state.get_memory(), new_parent)?; debug!("insert object {} into {}, having child {}", o.number, p.parent, p.sibling); o.sibling = p.child; o.parent = new_parent as u16; p.child = object_number as u16; debug!("save object"); o.save_family(state)?; debug!("save parent"); p.save_family(state)?; Ok(o) } pub fn has_attribute(&self, memory: &MemoryMap, object_number: usize, attribute_number: usize) -> Result<bool, InfocomError> { let o = self.get_object(memory, object_number)?; o.has_attribute(attribute_number) } pub fn set_attribute(&mut self, state: &mut FrameStack, object_number: usize, attribute_number: usize) -> Result<Object, InfocomError> { let mut o = self.get_object(state.get_memory(), object_number)?; o.set_attribute(attribute_number)?; o.save_attributes(state)?; Ok(o) } pub fn clear_attribute(&mut self, state: &mut FrameStack, object_number: usize, attribute_number: usize) -> Result<Object, InfocomError> { let mut o = self.get_object(state.get_memory(), object_number)?; o.clear_attribute(attribute_number)?; o.save_attributes(state)?; Ok(o) } pub fn read_property_data(&self, memory: &MemoryMap, object_number: usize, property_number: usize) -> Result<Vec<u8>, InfocomError> { let o = self.get_object(memory, object_number)?; if let Some(p) = o.get_property(property_number) { Ok(p.data.to_vec()) } else { if let Some(v) = self.default_properties.get(property_number - 1) { let b1 = ((v >> 8) & 0xFF) as u8; let b2 = (v & 0xFF) as u8; Ok(vec![b1, b2]) } else { Err(InfocomError::Memory(format!("Invalid property number: ${:02x}", property_number))) } } } fn get_default_property(&self, property_number: usize) -> Result<Vec<u8>, InfocomError> { if let Some(v) = self.default_properties.get(property_number - 1) { let b1 = ((v >> 8) & 0xFF) as u8; let b2 = (v & 0xFF) as u8; Ok(vec![b1, b2]) } else { Err(InfocomError::Memory(format!("Invalid property number: ${:02x}", property_number))) } } pub fn get_property_value(&self, memory: &MemoryMap, object_number: usize, property_number: usize) -> Result<u16, InfocomError> { match self.get_object(memory, object_number)?.get_property(property_number) { Some(p) => if p.size == 1 { Ok(p.data[0] as u16) } else if p.size == 2 { Ok(((p.data[0] as u16) << 8) & 0xFF00 | (p.data[1] as u16 & 0xFF)) } else { Err(InfocomError::Memory(format!("Attempt to read property ${:02x} data on object ${:04x} with length ${:02x}", property_number, object_number, p.size))) }, None => { if let Some(v) = self.default_properties.get(property_number - 1) { debug!("Read default property {:02x}: ${:04x}", property_number, v); Ok(*v) } else { Err(InfocomError::Memory(format!("Invalid property number: ${:02x}", property_number))) } } } } pub fn put_property_data(&mut self, state: &mut FrameStack, object_number: usize, property_number: usize, value: u16) -> Result<Object, InfocomError> { let mut o = self.get_object(state.get_memory(), object_number)?; match o.get_property(property_number) { Some(p) => { if p.size > 2 { return Err(InfocomError::Memory(format!("Attempt to write property ${:02x} on object ${:04x} with length ${:02x}", property_number, object_number, p.size))) } o.set_property(property_number, value)?; o.save_property(state, property_number)?; Ok(o) }, None => Err(InfocomError::Memory(format!("Set property ${:02x} on object ${:04x} that doesn't have the specified property", property_number, object_number))) } } pub fn get_next_property(&self, memory: &MemoryMap, object_number: usize, property_number: usize) -> Result<u8, InfocomError> { self.get_object(memory, object_number)?.next_property_number(property_number) } pub fn get_property_address(&self, memory: &MemoryMap, object_number: usize, property_number: usize) -> Result<usize, InfocomError> { match self.get_object(memory, object_number)?.get_property(property_number) { Some(p) => Ok(p.data_address), None => Ok(0) } } pub fn get_property_len(&self, memory: &MemoryMap, property_address: usize) -> Result<usize, InfocomError> { let b = memory.get_byte(property_address - 1)?; match memory.version { Version::V(1) | Version::V(2) | Version::V(3) => { Ok(((b as usize / 32) & 0x7) + 1) }, _ => { if b & 0x80 == 0x80 { let l = b as usize & 0x3F; if l == 0 { Ok(64) } else { Ok(l) } } else { if b & 0x40 == 0x40 { Ok(2) } else { Ok(1) } } } } } }
use youchoose; fn main(){ let mut menu = youchoose::Menu::new(0..100).preview(multiples); let choice = menu.show(); println!("Chose {:?}", choice); } fn multiples(num: i32) -> String { let mut buffer = String::new(); for i in 0..20 { buffer.push_str( &format!("{} times {} is equal to {}!\n", num, i, num * i) ); } buffer }
use log::info; use std::fs::File; use std::io::Read; use std::path::Path; #[derive(Debug, serde::Deserialize)] pub struct Configuration { #[serde(skip)] pub websites: Vec<String>, pub parallel_fetch: usize, pub interval_between_fetch: u64, pub stop_after_iteration: usize, pub run_forever: bool, } #[derive(Debug, serde::Deserialize)] struct ConfigurationFromEnvironment { parallel_fetch: Option<usize>, interval_between_fetch: Option<u64>, stop_after_iteration: Option<usize>, run_forever: Option<bool>, } const CONFIG_PATH: &str = "./Configuration.toml"; pub fn load_configuration() -> Result<Configuration, String> { let path = Path::new(CONFIG_PATH); if !path.is_file() { return Err(format!("Configuration file is absent: {}", CONFIG_PATH)); } let mut file = File::open(path).expect("Path should exists"); let mut contents = String::new(); file.read_to_string(&mut contents) .expect("reading file should be OK"); let config_parsing_res = toml::from_str(&contents) .or_else(|err| Err(format!("Couldn't decode the Toml configuration: {}", err))); let default_config: Configuration = config_parsing_res?; let config_from_env: ConfigurationFromEnvironment = envy::prefixed("APP_") .from_env() .expect("Environment should be readable"); // TODO handle error nicely let websites_from_db = crate::infrastructure::database::fetch_websites_to_crawl().expect("Should not have failed"); let configuration = Configuration { interval_between_fetch: config_from_env .interval_between_fetch .unwrap_or(default_config.interval_between_fetch), parallel_fetch: config_from_env .parallel_fetch .unwrap_or(default_config.parallel_fetch), run_forever: config_from_env .run_forever .unwrap_or(default_config.run_forever), stop_after_iteration: config_from_env .stop_after_iteration .unwrap_or(default_config.stop_after_iteration), websites: websites_from_db, }; info!("Configuration: {:#?}", configuration); Ok(configuration) }
#[macro_use] extern crate clap; #[macro_use] extern crate failure; #[macro_use] extern crate log; use ark_auth::{cli, core, driver, driver::Driver, server}; use clap::{App, Arg, SubCommand}; use sentry::integrations::log::LoggerOptions; const COMMAND_CREATE_ROOT_KEY: &str = "create-root-key"; const COMMAND_DELETE_ROOT_KEYS: &str = "delete-root-keys"; const COMMAND_CREATE_SERVICE_WITH_KEY: &str = "create-service-with-key"; const COMMAND_START_SERVER: &str = "start-server"; const ARG_NAME: &str = "NAME"; const ARG_URL: &str = "URL"; /// Main errors. #[derive(Debug, Fail)] enum Error { /// Command invalid. #[fail(display = "MainError::CommandInvalid")] CommandInvalid, /// Core error wrapper. #[fail(display = "MainError::Core {}", _0)] Core(#[fail(cause)] core::Error), /// Server error wrapper. #[fail(display = "MainError::Server {}", _0)] Server(#[fail(cause)] server::Error), /// Standard environment variable error wrapper. #[fail(display = "MainError::StdEnvVar {}", _0)] StdEnvVar(#[fail(cause)] std::env::VarError), } struct Configuration { database_url: String, server_configuration: server::Configuration, } fn main() { // Configure logging environment variables. std::env::set_var("RUST_BACKTRACE", "1"); std::env::set_var("RUST_LOG", "info"); // If SENTRY_URL is defined, enable logging and panic handler integration. let _guard = match std::env::var("SENTRY_URL") { Ok(sentry_url) => { let guard = sentry::init(sentry_url); let mut options = LoggerOptions::default(); options.emit_warning_events = true; sentry::integrations::env_logger::init(None, options); sentry::integrations::panic::register_panic_handler(); Some(guard) } Err(e) => { env_logger::init(); warn!("SENTRY_URL is undefined, integration is disabled ({})", e); None } }; // Command line argument parser. let matches = App::new(crate_name!()) .version(crate_version!()) .about(crate_description!()) .author(crate_authors!("\n")) .subcommands(vec![ SubCommand::with_name(COMMAND_CREATE_ROOT_KEY) .version(crate_version!()) .about("Create a root key") .author(crate_authors!("\n")) .arg( Arg::with_name(ARG_NAME) .help("Key name") .required(true) .index(1), ), SubCommand::with_name(COMMAND_DELETE_ROOT_KEYS) .version(crate_version!()) .about("Delete all root keys") .author(crate_authors!("\n")), SubCommand::with_name(COMMAND_CREATE_SERVICE_WITH_KEY) .version(crate_version!()) .about("Create service with service key") .author(crate_authors!("\n")) .args(&[ Arg::with_name(ARG_NAME) .help("Service name") .required(true) .index(1), Arg::with_name(ARG_URL) .help("Service URL") .required(true) .index(2), ]), SubCommand::with_name(COMMAND_START_SERVER) .version(crate_version!()) .about("Start server") .author(crate_authors!("\n")), ]) .get_matches(); // Build configuration from environment and initialise driver. let configuration = configuration_from_environment().unwrap(); let driver = initialise_driver(&configuration.database_url).box_clone(); // Call library functions with command line arguments. let result = match matches.subcommand() { (COMMAND_CREATE_ROOT_KEY, Some(submatches)) => { let name = submatches.value_of(ARG_NAME).unwrap(); cli::create_root_key(driver, name) .map_err(Error::Core) .map(|key| { println!("key.id: {}", key.id); println!("key.value: {}", key.value); 0 }) } (COMMAND_DELETE_ROOT_KEYS, Some(_submatches)) => cli::delete_root_keys(driver) .map_err(Error::Core) .map(|_| 0), (COMMAND_CREATE_SERVICE_WITH_KEY, Some(submatches)) => { let name = submatches.value_of(ARG_NAME).unwrap(); let url = submatches.value_of(ARG_URL).unwrap(); cli::create_service_with_key(driver, name, url) .map_err(Error::Core) .map(|(service, key)| { println!("service.id: {}", service.id); println!("service.name: {}", service.name); println!("key.id: {}", key.id); println!("key.value: {}", key.value); 0 }) } (COMMAND_START_SERVER, Some(_submatches)) => { cli::start_server(driver, configuration.server_configuration) .map_err(Error::Server) .map(|_| 0) } _ => Err(Error::CommandInvalid), }; // Handle errors and exit with code. match result { Ok(code) => std::process::exit(code), Err(e) => { error!("Error: {}", e); std::process::exit(1); } } } /// Build configuration from environment. fn configuration_from_environment() -> Result<Configuration, Error> { // TODO(refactor): Clean this up. let database_url = std::env::var("DATABASE_URL").unwrap(); let server_bind = std::env::var("SERVER_BIND").unwrap(); let mut server_configuration = server::Configuration::new(server_bind).set_password_pwned_enabled(true); let smtp_host = std::env::var("SMTP_HOST").map_err(Error::StdEnvVar); let smtp_port = std::env::var("SMTP_PORT").map_err(Error::StdEnvVar); let smtp_user = std::env::var("SMTP_USER").map_err(Error::StdEnvVar); let smtp_password = std::env::var("SMTP_PASSWORD").map_err(Error::StdEnvVar); if smtp_host.is_ok() || smtp_port.is_ok() || smtp_user.is_ok() || smtp_password.is_ok() { let smtp_port = smtp_port?.parse::<u16>().unwrap(); server_configuration = server_configuration.set_smtp(smtp_host?, smtp_port, smtp_user?, smtp_password?); } let gh_client_id = std::env::var("GITHUB_CLIENT_ID").map_err(Error::StdEnvVar); let gh_client_secret = std::env::var("GITHUB_CLIENT_SECRET").map_err(Error::StdEnvVar); let gh_redirect_url = std::env::var("GITHUB_REDIRECT_URL").map_err(Error::StdEnvVar); if gh_client_id.is_ok() || gh_client_secret.is_ok() || gh_redirect_url.is_ok() { server_configuration = server_configuration.set_oauth2_github( gh_client_id?, gh_client_secret?, gh_redirect_url?, ); } let ms_client_id = std::env::var("MICROSOFT_CLIENT_ID").map_err(Error::StdEnvVar); let ms_client_secret = std::env::var("MICROSOFT_CLIENT_SECRET").map_err(Error::StdEnvVar); let ms_redirect_url = std::env::var("MICROSOFT_REDIRECT_URL").map_err(Error::StdEnvVar); if ms_client_id.is_ok() || ms_client_secret.is_ok() || ms_redirect_url.is_ok() { server_configuration = server_configuration.set_oauth2_microsoft( ms_client_id?, ms_client_secret?, ms_redirect_url?, ); } Ok(Configuration { database_url, server_configuration, }) } #[cfg(all(feature = "postgres", not(feature = "sqlite")))] fn initialise_driver(database_url: &str) -> impl Driver { // TODO(refactor): Configurable number of connections. driver::postgres::Driver::initialise(database_url, 10).unwrap() } #[cfg(all(feature = "sqlite", not(feature = "postgres")))] fn initialise_driver(database_url: &str) -> impl Driver { driver::sqlite::Driver::initialise(database_url).unwrap() }
//! The `retransmit_stage` retransmits shreds between validators #![allow(clippy::rc_buffer)] use { crate::{ ancestor_hashes_service::AncestorHashesReplayUpdateReceiver, cluster_info_vote_listener::VerifiedVoteReceiver, cluster_nodes::ClusterNodesCache, cluster_slots::ClusterSlots, cluster_slots_service::{ClusterSlotsService, ClusterSlotsUpdateReceiver}, completed_data_sets_service::CompletedDataSetsSender, packet_hasher::PacketHasher, repair_service::{DuplicateSlotsResetSender, RepairInfo}, result::{Error, Result}, window_service::{should_retransmit_and_persist, WindowService}, }, crossbeam_channel::{Receiver, Sender}, lru::LruCache, solana_client::rpc_response::SlotUpdate, solana_gossip::cluster_info::{ClusterInfo, DATA_PLANE_FANOUT}, solana_ledger::{ shred::Shred, {blockstore::Blockstore, leader_schedule_cache::LeaderScheduleCache}, }, solana_measure::measure::Measure, solana_metrics::inc_new_counter_error, solana_perf::packet::Packets, solana_rpc::{max_slots::MaxSlots, rpc_subscriptions::RpcSubscriptions}, solana_runtime::{bank::Bank, bank_forks::BankForks}, solana_sdk::{ clock::Slot, epoch_schedule::EpochSchedule, pubkey::Pubkey, timing::{timestamp, AtomicInterval}, }, std::{ collections::{BTreeSet, HashSet}, net::UdpSocket, ops::DerefMut, sync::{ atomic::{AtomicBool, AtomicU64, Ordering}, mpsc::{self, channel, RecvTimeoutError}, Arc, Mutex, RwLock, }, thread::{self, Builder, JoinHandle}, time::Duration, }, }; const MAX_DUPLICATE_COUNT: usize = 2; const DEFAULT_LRU_SIZE: usize = 10_000; // Limit a given thread to consume about this many shreds so that // it doesn't pull up too much work. const MAX_SHREDS_BATCH_SIZE: usize = 100; const CLUSTER_NODES_CACHE_NUM_EPOCH_CAP: usize = 8; const CLUSTER_NODES_CACHE_TTL: Duration = Duration::from_secs(5); #[derive(Default)] struct RetransmitStats { num_shreds: AtomicU64, num_shreds_skipped: AtomicU64, total_batches: AtomicU64, total_time: AtomicU64, epoch_fetch: AtomicU64, epoch_cache_update: AtomicU64, retransmit_total: AtomicU64, last_ts: AtomicInterval, compute_turbine_peers_total: AtomicU64, } #[allow(clippy::too_many_arguments)] fn update_retransmit_stats( stats: &RetransmitStats, total_time: u64, num_shreds: usize, num_shreds_skipped: usize, retransmit_total: u64, compute_turbine_peers_total: u64, peers_len: usize, epoch_fetch: u64, epoch_cach_update: u64, ) { stats.total_time.fetch_add(total_time, Ordering::Relaxed); stats .num_shreds .fetch_add(num_shreds as u64, Ordering::Relaxed); stats .num_shreds_skipped .fetch_add(num_shreds_skipped as u64, Ordering::Relaxed); stats .retransmit_total .fetch_add(retransmit_total, Ordering::Relaxed); stats .compute_turbine_peers_total .fetch_add(compute_turbine_peers_total, Ordering::Relaxed); stats.total_batches.fetch_add(1, Ordering::Relaxed); stats.epoch_fetch.fetch_add(epoch_fetch, Ordering::Relaxed); stats .epoch_cache_update .fetch_add(epoch_cach_update, Ordering::Relaxed); if stats.last_ts.should_update(2000) { datapoint_info!("retransmit-num_nodes", ("count", peers_len, i64)); datapoint_info!( "retransmit-stage", ( "total_time", stats.total_time.swap(0, Ordering::Relaxed) as i64, i64 ), ( "epoch_fetch", stats.epoch_fetch.swap(0, Ordering::Relaxed) as i64, i64 ), ( "epoch_cache_update", stats.epoch_cache_update.swap(0, Ordering::Relaxed) as i64, i64 ), ( "total_batches", stats.total_batches.swap(0, Ordering::Relaxed) as i64, i64 ), ( "num_shreds", stats.num_shreds.swap(0, Ordering::Relaxed) as i64, i64 ), ( "num_shreds_skipped", stats.num_shreds_skipped.swap(0, Ordering::Relaxed) as i64, i64 ), ( "retransmit_total", stats.retransmit_total.swap(0, Ordering::Relaxed) as i64, i64 ), ( "compute_turbine", stats.compute_turbine_peers_total.swap(0, Ordering::Relaxed) as i64, i64 ), ); } } // Map of shred (slot, index, is_data) => list of hash values seen for that key. type ShredFilter = LruCache<(Slot, u32, bool), Vec<u64>>; type ShredFilterAndHasher = (ShredFilter, PacketHasher); // Returns true if shred is already received and should skip retransmit. fn should_skip_retransmit(shred: &Shred, shreds_received: &Mutex<ShredFilterAndHasher>) -> bool { let key = (shred.slot(), shred.index(), shred.is_data()); let mut shreds_received = shreds_received.lock().unwrap(); let (cache, hasher) = shreds_received.deref_mut(); match cache.get_mut(&key) { Some(sent) if sent.len() >= MAX_DUPLICATE_COUNT => true, Some(sent) => { let hash = hasher.hash_shred(shred); if sent.contains(&hash) { true } else { sent.push(hash); false } } None => { let hash = hasher.hash_shred(shred); cache.put(key, vec![hash]); false } } } // Returns true if this is the first time receiving a shred for `shred_slot`. fn check_if_first_shred_received( shred_slot: Slot, first_shreds_received: &Mutex<BTreeSet<Slot>>, root_bank: &Bank, ) -> bool { if shred_slot <= root_bank.slot() { return false; } let mut first_shreds_received_locked = first_shreds_received.lock().unwrap(); if !first_shreds_received_locked.contains(&shred_slot) { datapoint_info!("retransmit-first-shred", ("slot", shred_slot, i64)); first_shreds_received_locked.insert(shred_slot); if first_shreds_received_locked.len() > 100 { let mut slots_before_root = first_shreds_received_locked.split_off(&(root_bank.slot() + 1)); // `slots_before_root` now contains all slots <= root std::mem::swap(&mut slots_before_root, &mut first_shreds_received_locked); } true } else { false } } fn maybe_reset_shreds_received_cache( shreds_received: &Mutex<ShredFilterAndHasher>, hasher_reset_ts: &AtomicU64, ) { const UPDATE_INTERVAL_MS: u64 = 1000; let now = timestamp(); let prev = hasher_reset_ts.load(Ordering::Acquire); if now.saturating_sub(prev) > UPDATE_INTERVAL_MS && hasher_reset_ts .compare_exchange(prev, now, Ordering::AcqRel, Ordering::Acquire) .is_ok() { let mut shreds_received = shreds_received.lock().unwrap(); let (cache, hasher) = shreds_received.deref_mut(); cache.clear(); hasher.reset(); } } #[allow(clippy::too_many_arguments)] fn retransmit( bank_forks: &RwLock<BankForks>, leader_schedule_cache: &LeaderScheduleCache, cluster_info: &ClusterInfo, shreds_receiver: &Mutex<mpsc::Receiver<Vec<Shred>>>, sock: &UdpSocket, id: u32, stats: &RetransmitStats, cluster_nodes_cache: &ClusterNodesCache<RetransmitStage>, hasher_reset_ts: &AtomicU64, shreds_received: &Mutex<ShredFilterAndHasher>, max_slots: &MaxSlots, first_shreds_received: &Mutex<BTreeSet<Slot>>, rpc_subscriptions: Option<&RpcSubscriptions>, ) -> Result<()> { const RECV_TIMEOUT: Duration = Duration::from_secs(1); let shreds_receiver = shreds_receiver.lock().unwrap(); let mut shreds = shreds_receiver.recv_timeout(RECV_TIMEOUT)?; let mut timer_start = Measure::start("retransmit"); while let Ok(more_shreds) = shreds_receiver.try_recv() { shreds.extend(more_shreds); if shreds.len() >= MAX_SHREDS_BATCH_SIZE { break; } } drop(shreds_receiver); let mut epoch_fetch = Measure::start("retransmit_epoch_fetch"); let (working_bank, root_bank) = { let bank_forks = bank_forks.read().unwrap(); (bank_forks.working_bank(), bank_forks.root_bank()) }; epoch_fetch.stop(); let mut epoch_cache_update = Measure::start("retransmit_epoch_cach_update"); maybe_reset_shreds_received_cache(shreds_received, hasher_reset_ts); epoch_cache_update.stop(); let num_shreds = shreds.len(); let my_id = cluster_info.id(); let socket_addr_space = cluster_info.socket_addr_space(); let mut retransmit_total = 0; let mut num_shreds_skipped = 0; let mut compute_turbine_peers_total = 0; let mut max_slot = 0; for shred in shreds { if should_skip_retransmit(&shred, shreds_received) { num_shreds_skipped += 1; continue; } let shred_slot = shred.slot(); max_slot = max_slot.max(shred_slot); if let Some(rpc_subscriptions) = rpc_subscriptions { if check_if_first_shred_received(shred_slot, first_shreds_received, &root_bank) { rpc_subscriptions.notify_slot_update(SlotUpdate::FirstShredReceived { slot: shred_slot, timestamp: timestamp(), }); } } let mut compute_turbine_peers = Measure::start("turbine_start"); // TODO: consider using root-bank here for leader lookup! // Shreds' signatures should be verified before they reach here, and if // the leader is unknown they should fail signature check. So here we // should expect to know the slot leader and otherwise skip the shred. let slot_leader = match leader_schedule_cache.slot_leader_at(shred_slot, Some(&working_bank)) { Some(pubkey) => pubkey, None => continue, }; let cluster_nodes = cluster_nodes_cache.get(shred_slot, &root_bank, &working_bank, cluster_info); let shred_seed = shred.seed(slot_leader, &root_bank); let (neighbors, children) = cluster_nodes.get_retransmit_peers(shred_seed, DATA_PLANE_FANOUT, slot_leader); let anchor_node = neighbors[0].id == my_id; compute_turbine_peers.stop(); compute_turbine_peers_total += compute_turbine_peers.as_us(); let mut retransmit_time = Measure::start("retransmit_to"); // If the node is on the critical path (i.e. the first node in each // neighborhood), it should send the packet to tvu socket of its // children and also tvu_forward socket of its neighbors. Otherwise it // should only forward to tvu_forward socket of its children. if anchor_node { // First neighbor is this node itself, so skip it. ClusterInfo::retransmit_to( &neighbors[1..], &shred.payload, sock, true, // forward socket socket_addr_space, ); } ClusterInfo::retransmit_to( &children, &shred.payload, sock, !anchor_node, // send to forward socket! socket_addr_space, ); retransmit_time.stop(); retransmit_total += retransmit_time.as_us(); } max_slots.retransmit.fetch_max(max_slot, Ordering::Relaxed); timer_start.stop(); debug!( "retransmitted {} shreds in {}ms retransmit_time: {}ms id: {}", num_shreds, timer_start.as_ms(), retransmit_total, id, ); let cluster_nodes = cluster_nodes_cache.get(root_bank.slot(), &root_bank, &working_bank, cluster_info); update_retransmit_stats( stats, timer_start.as_us(), num_shreds, num_shreds_skipped, retransmit_total, compute_turbine_peers_total, cluster_nodes.num_peers(), epoch_fetch.as_us(), epoch_cache_update.as_us(), ); Ok(()) } /// Service to retransmit messages from the leader or layer 1 to relevant peer nodes. /// See `cluster_info` for network layer definitions. /// # Arguments /// * `sockets` - Sockets to read from. /// * `bank_forks` - The BankForks structure /// * `leader_schedule_cache` - The leader schedule to verify shreds /// * `cluster_info` - This structure needs to be updated and populated by the bank and via gossip. /// * `r` - Receive channel for shreds to be retransmitted to all the layer 1 nodes. pub fn retransmitter( sockets: Arc<Vec<UdpSocket>>, bank_forks: Arc<RwLock<BankForks>>, leader_schedule_cache: Arc<LeaderScheduleCache>, cluster_info: Arc<ClusterInfo>, shreds_receiver: Arc<Mutex<mpsc::Receiver<Vec<Shred>>>>, max_slots: Arc<MaxSlots>, rpc_subscriptions: Option<Arc<RpcSubscriptions>>, ) -> Vec<JoinHandle<()>> { let cluster_nodes_cache = Arc::new(ClusterNodesCache::<RetransmitStage>::new( CLUSTER_NODES_CACHE_NUM_EPOCH_CAP, CLUSTER_NODES_CACHE_TTL, )); let hasher_reset_ts = Arc::default(); let stats = Arc::new(RetransmitStats::default()); let shreds_received = Arc::new(Mutex::new(( LruCache::new(DEFAULT_LRU_SIZE), PacketHasher::default(), ))); let first_shreds_received = Arc::new(Mutex::new(BTreeSet::new())); (0..sockets.len()) .map(|s| { let sockets = sockets.clone(); let bank_forks = bank_forks.clone(); let leader_schedule_cache = leader_schedule_cache.clone(); let shreds_receiver = shreds_receiver.clone(); let cluster_info = cluster_info.clone(); let stats = stats.clone(); let cluster_nodes_cache = Arc::clone(&cluster_nodes_cache); let hasher_reset_ts = Arc::clone(&hasher_reset_ts); let shreds_received = shreds_received.clone(); let max_slots = max_slots.clone(); let first_shreds_received = first_shreds_received.clone(); let rpc_subscriptions = rpc_subscriptions.clone(); Builder::new() .name("solana-retransmitter".to_string()) .spawn(move || { trace!("retransmitter started"); loop { if let Err(e) = retransmit( &bank_forks, &leader_schedule_cache, &cluster_info, &shreds_receiver, &sockets[s], s as u32, &stats, &cluster_nodes_cache, &hasher_reset_ts, &shreds_received, &max_slots, &first_shreds_received, rpc_subscriptions.as_deref(), ) { match e { Error::RecvTimeout(RecvTimeoutError::Disconnected) => break, Error::RecvTimeout(RecvTimeoutError::Timeout) => (), _ => { inc_new_counter_error!("streamer-retransmit-error", 1, 1); } } } } trace!("exiting retransmitter"); }) .unwrap() }) .collect() } pub(crate) struct RetransmitStage { thread_hdls: Vec<JoinHandle<()>>, window_service: WindowService, cluster_slots_service: ClusterSlotsService, } impl RetransmitStage { #[allow(clippy::new_ret_no_self)] #[allow(clippy::too_many_arguments)] pub(crate) fn new( bank_forks: Arc<RwLock<BankForks>>, leader_schedule_cache: Arc<LeaderScheduleCache>, blockstore: Arc<Blockstore>, cluster_info: Arc<ClusterInfo>, retransmit_sockets: Arc<Vec<UdpSocket>>, repair_socket: Arc<UdpSocket>, verified_receiver: Receiver<Vec<Packets>>, exit: Arc<AtomicBool>, cluster_slots_update_receiver: ClusterSlotsUpdateReceiver, epoch_schedule: EpochSchedule, cfg: Option<Arc<AtomicBool>>, shred_version: u16, cluster_slots: Arc<ClusterSlots>, duplicate_slots_reset_sender: DuplicateSlotsResetSender, verified_vote_receiver: VerifiedVoteReceiver, repair_validators: Option<HashSet<Pubkey>>, completed_data_sets_sender: CompletedDataSetsSender, max_slots: Arc<MaxSlots>, rpc_subscriptions: Option<Arc<RpcSubscriptions>>, duplicate_slots_sender: Sender<Slot>, ancestor_hashes_replay_update_receiver: AncestorHashesReplayUpdateReceiver, ) -> Self { let (retransmit_sender, retransmit_receiver) = channel(); // https://github.com/rust-lang/rust/issues/39364#issuecomment-634545136 let _retransmit_sender = retransmit_sender.clone(); let retransmit_receiver = Arc::new(Mutex::new(retransmit_receiver)); let thread_hdls = retransmitter( retransmit_sockets, bank_forks.clone(), leader_schedule_cache.clone(), cluster_info.clone(), retransmit_receiver, max_slots, rpc_subscriptions, ); let cluster_slots_service = ClusterSlotsService::new( blockstore.clone(), cluster_slots.clone(), bank_forks.clone(), cluster_info.clone(), cluster_slots_update_receiver, exit.clone(), ); let leader_schedule_cache_clone = leader_schedule_cache.clone(); let repair_info = RepairInfo { bank_forks, epoch_schedule, duplicate_slots_reset_sender, repair_validators, cluster_info, cluster_slots, }; let window_service = WindowService::new( blockstore, verified_receiver, retransmit_sender, repair_socket, exit, repair_info, leader_schedule_cache, move |id, shred, working_bank, last_root| { let is_connected = cfg .as_ref() .map(|x| x.load(Ordering::Relaxed)) .unwrap_or(true); let rv = should_retransmit_and_persist( shred, working_bank, &leader_schedule_cache_clone, id, last_root, shred_version, ); rv && is_connected }, verified_vote_receiver, completed_data_sets_sender, duplicate_slots_sender, ancestor_hashes_replay_update_receiver, ); Self { thread_hdls, window_service, cluster_slots_service, } } pub(crate) fn join(self) -> thread::Result<()> { for thread_hdl in self.thread_hdls { thread_hdl.join()?; } self.window_service.join()?; self.cluster_slots_service.join()?; Ok(()) } } #[cfg(test)] mod tests { use { super::*, solana_gossip::contact_info::ContactInfo, solana_ledger::{ blockstore_processor::{process_blockstore, ProcessOptions}, create_new_tmp_ledger, genesis_utils::{create_genesis_config, GenesisConfigInfo}, }, solana_net_utils::find_available_port_in_range, solana_sdk::signature::Keypair, solana_streamer::socket::SocketAddrSpace, std::net::{IpAddr, Ipv4Addr}, }; #[test] fn test_skip_repair() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, .. } = create_genesis_config(123); let (ledger_path, _blockhash) = create_new_tmp_ledger!(&genesis_config); let blockstore = Blockstore::open(&ledger_path).unwrap(); let opts = ProcessOptions { accounts_db_test_hash_calculation: true, full_leader_cache: true, ..ProcessOptions::default() }; let (bank_forks, cached_leader_schedule) = process_blockstore(&genesis_config, &blockstore, Vec::new(), opts, None).unwrap(); let leader_schedule_cache = Arc::new(cached_leader_schedule); let bank_forks = Arc::new(RwLock::new(bank_forks)); let mut me = ContactInfo::new_localhost(&solana_sdk::pubkey::new_rand(), 0); let ip_addr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)); let port = find_available_port_in_range(ip_addr, (8000, 10000)).unwrap(); let me_retransmit = UdpSocket::bind(format!("127.0.0.1:{}", port)).unwrap(); // need to make sure tvu and tpu are valid addresses me.tvu_forwards = me_retransmit.local_addr().unwrap(); let port = find_available_port_in_range(ip_addr, (8000, 10000)).unwrap(); me.tvu = UdpSocket::bind(format!("127.0.0.1:{}", port)) .unwrap() .local_addr() .unwrap(); // This fixes the order of nodes returned by shuffle_peers_and_index, // and makes turbine retransmit tree deterministic for the purpose of // the test. let other = std::iter::repeat_with(solana_sdk::pubkey::new_rand) .find(|pk| me.id < *pk) .unwrap(); let other = ContactInfo::new_localhost(&other, 0); let cluster_info = ClusterInfo::new( other, Arc::new(Keypair::new()), SocketAddrSpace::Unspecified, ); cluster_info.insert_info(me); let retransmit_socket = Arc::new(vec![UdpSocket::bind("0.0.0.0:0").unwrap()]); let cluster_info = Arc::new(cluster_info); let (retransmit_sender, retransmit_receiver) = channel(); let _retransmit_sender = retransmit_sender.clone(); let _t_retransmit = retransmitter( retransmit_socket, bank_forks, leader_schedule_cache, cluster_info, Arc::new(Mutex::new(retransmit_receiver)), Arc::default(), // MaxSlots None, ); let shred = Shred::new_from_data(0, 0, 0, None, true, true, 0, 0x20, 0); // it should send this over the sockets. retransmit_sender.send(vec![shred]).unwrap(); let mut packets = Packets::new(vec![]); solana_streamer::packet::recv_from(&mut packets, &me_retransmit, 1).unwrap(); assert_eq!(packets.packets.len(), 1); assert!(!packets.packets[0].meta.repair); } #[test] fn test_already_received() { let slot = 1; let index = 5; let version = 0x40; let shred = Shred::new_from_data(slot, index, 0, None, true, true, 0, version, 0); let shreds_received = Arc::new(Mutex::new((LruCache::new(100), PacketHasher::default()))); // unique shred for (1, 5) should pass assert!(!should_skip_retransmit(&shred, &shreds_received)); // duplicate shred for (1, 5) blocked assert!(should_skip_retransmit(&shred, &shreds_received)); let shred = Shred::new_from_data(slot, index, 2, None, true, true, 0, version, 0); // first duplicate shred for (1, 5) passed assert!(!should_skip_retransmit(&shred, &shreds_received)); // then blocked assert!(should_skip_retransmit(&shred, &shreds_received)); let shred = Shred::new_from_data(slot, index, 8, None, true, true, 0, version, 0); // 2nd duplicate shred for (1, 5) blocked assert!(should_skip_retransmit(&shred, &shreds_received)); assert!(should_skip_retransmit(&shred, &shreds_received)); let shred = Shred::new_empty_coding(slot, index, 0, 1, 1, version); // Coding at (1, 5) passes assert!(!should_skip_retransmit(&shred, &shreds_received)); // then blocked assert!(should_skip_retransmit(&shred, &shreds_received)); let shred = Shred::new_empty_coding(slot, index, 2, 1, 1, version); // 2nd unique coding at (1, 5) passes assert!(!should_skip_retransmit(&shred, &shreds_received)); // same again is blocked assert!(should_skip_retransmit(&shred, &shreds_received)); let shred = Shred::new_empty_coding(slot, index, 3, 1, 1, version); // Another unique coding at (1, 5) always blocked assert!(should_skip_retransmit(&shred, &shreds_received)); assert!(should_skip_retransmit(&shred, &shreds_received)); } }
#![cfg_attr(target_arch = "wasm32", no_std)] //! Provide minimalist debug tracing that works even in wasm32. Since wasm //! browser sandboxes currently do not have stderr, debug logging must go //! through a javascript function binding. Passing strings from wasm to //! javascript is possible, but it adds lots of complexity. Simplest option is //! function call with i32 argument. /// For wasm32 build, bind debug trace to a javascript function call #[cfg(target_arch = "wasm32")] #[link(wasm_import_module = "js")] extern "C" { pub fn js_log_trace(code: i32); } /// For non-wasm32 builds, replace javascript call with eprintln! #[cfg(not(target_arch = "wasm32"))] unsafe fn js_log_trace(code: i32) { eprintln!("{}", code); } /// For logging control flow (printf style debugging) #[allow(dead_code)] pub fn log(n: i32) { unsafe { js_log_trace(n as i32); } } /// For logging error and status codes pub fn log_code(code: Code) { unsafe { js_log_trace(code as i32); } } /// Error and status codes pub enum Code { BadKeyIndex = -1, BadModkeyDownR = -2, }
mod config_files; mod logger; mod test_bins; #[cfg(test)] mod tests; #[cfg(feature = "plugin")] use crate::config_files::NUSHELL_FOLDER; use crate::logger::{configure, logger}; use log::info; use miette::Result; #[cfg(feature = "plugin")] use nu_cli::read_plugin_file; use nu_cli::{ evaluate_commands, evaluate_file, evaluate_repl, gather_parent_env_vars, get_init_cwd, report_error, }; use nu_command::{create_default_context, BufferedReader}; use nu_engine::{get_full_help, CallExt}; use nu_parser::parse; use nu_protocol::{ ast::{Call, Expr, Expression}, engine::{Command, EngineState, Stack, StateWorkingSet}, Category, Example, IntoPipelineData, PipelineData, RawStream, ShellError, Signature, Span, Spanned, SyntaxShape, Value, CONFIG_VARIABLE_ID, }; use std::cell::RefCell; use std::{ io::{BufReader, Write}, path::Path, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, }; thread_local! { static IS_PERF: RefCell<bool> = RefCell::new(false) } fn main() -> Result<()> { // miette::set_panic_hook(); let miette_hook = std::panic::take_hook(); std::panic::set_hook(Box::new(move |x| { crossterm::terminal::disable_raw_mode().expect("unable to disable raw mode"); miette_hook(x); })); // Get initial current working directory. let init_cwd = get_init_cwd(); let mut engine_state = create_default_context(&init_cwd); // Custom additions let delta = { let mut working_set = nu_protocol::engine::StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(nu_cli::NuHighlight)); working_set.add_decl(Box::new(nu_cli::Print)); working_set.render() }; let _ = engine_state.merge_delta(delta, None, &init_cwd); // TODO: make this conditional in the future // Ctrl-c protection section let ctrlc = Arc::new(AtomicBool::new(false)); let handler_ctrlc = ctrlc.clone(); let engine_state_ctrlc = ctrlc.clone(); ctrlc::set_handler(move || { handler_ctrlc.store(true, Ordering::SeqCst); }) .expect("Error setting Ctrl-C handler"); engine_state.ctrlc = Some(engine_state_ctrlc); // End ctrl-c protection section let mut args_to_nushell = vec![]; let mut script_name = String::new(); let mut args_to_script = vec![]; // Would be nice if we had a way to parse this. The first flags we see will be going to nushell // then it'll be the script name // then the args to the script let mut collect_arg_nushell = false; for arg in std::env::args().skip(1) { if !script_name.is_empty() { args_to_script.push(if arg.contains(' ') { format!("'{}'", arg) } else { arg }); } else if collect_arg_nushell { args_to_nushell.push(if arg.contains(' ') { format!("'{}'", arg) } else { arg }); collect_arg_nushell = false; } else if arg.starts_with('-') { // Cool, it's a flag if arg == "-c" || arg == "--commands" || arg == "--testbin" || arg == "--log-level" || arg == "--config" || arg == "--env-config" || arg == "--threads" || arg == "-t" { collect_arg_nushell = true; } args_to_nushell.push(arg); } else { // Our script file script_name = arg; } } args_to_nushell.insert(0, "nu".into()); let nushell_commandline_args = args_to_nushell.join(" "); let parsed_nu_cli_args = parse_commandline_args(&nushell_commandline_args, &init_cwd, &mut engine_state); match parsed_nu_cli_args { Ok(binary_args) => { if let Some(t) = binary_args.threads { // 0 means to let rayon decide how many threads to use let threads = t.as_i64().unwrap_or(0); rayon::ThreadPoolBuilder::new() .num_threads(threads as usize) .build_global() .expect("error setting number of threads"); } set_is_perf_value(binary_args.perf); if binary_args.perf || binary_args.log_level.is_some() { // since we're in this section, either perf is true or log_level has been set // if log_level is set, just use it // otherwise if perf is true, set the log_level to `info` which is what // the perf calls are set to. let level = binary_args .log_level .map(|level| level.item) .unwrap_or_else(|| "info".to_string()); logger(|builder| { configure(level.as_str(), builder)?; Ok(()) })?; info!("start logging {}:{}:{}", file!(), line!(), column!()); } if let Some(testbin) = &binary_args.testbin { // Call out to the correct testbin match testbin.item.as_str() { "echo_env" => test_bins::echo_env(), "cococo" => test_bins::cococo(), "meow" => test_bins::meow(), "meowb" => test_bins::meowb(), "relay" => test_bins::relay(), "iecho" => test_bins::iecho(), "fail" => test_bins::fail(), "nonu" => test_bins::nonu(), "chop" => test_bins::chop(), "repeater" => test_bins::repeater(), _ => std::process::exit(1), } std::process::exit(0) } let input = if let Some(redirect_stdin) = &binary_args.redirect_stdin { let stdin = std::io::stdin(); let buf_reader = BufReader::new(stdin); PipelineData::ExternalStream { stdout: Some(RawStream::new( Box::new(BufferedReader::new(buf_reader)), Some(ctrlc), redirect_stdin.span, )), stderr: None, exit_code: None, span: redirect_stdin.span, metadata: None, } } else { PipelineData::new(Span::new(0, 0)) }; if is_perf_true() { info!("redirect_stdin {}:{}:{}", file!(), line!(), column!()); } // First, set up env vars as strings only gather_parent_env_vars(&mut engine_state); let mut stack = nu_protocol::engine::Stack::new(); stack.vars.insert( CONFIG_VARIABLE_ID, Value::Record { cols: vec![], vals: vec![], span: Span::new(0, 0), }, ); if let Some(commands) = &binary_args.commands { #[cfg(feature = "plugin")] read_plugin_file( &mut engine_state, &mut stack, NUSHELL_FOLDER, is_perf_true(), ); let ret_val = evaluate_commands( commands, &init_cwd, &mut engine_state, &mut stack, input, is_perf_true(), ); if is_perf_true() { info!("-c command execution {}:{}:{}", file!(), line!(), column!()); } ret_val } else if !script_name.is_empty() && binary_args.interactive_shell.is_none() { #[cfg(feature = "plugin")] read_plugin_file( &mut engine_state, &mut stack, NUSHELL_FOLDER, is_perf_true(), ); let ret_val = evaluate_file( script_name, &args_to_script, &mut engine_state, &mut stack, input, is_perf_true(), ); if is_perf_true() { info!("eval_file execution {}:{}:{}", file!(), line!(), column!()); } ret_val } else { setup_config( &mut engine_state, &mut stack, binary_args.config_file, binary_args.env_file, ); let history_path = config_files::create_history_path(); let ret_val = evaluate_repl(&mut engine_state, &mut stack, history_path, is_perf_true()); if is_perf_true() { info!("repl eval {}:{}:{}", file!(), line!(), column!()); } ret_val } } Err(_) => std::process::exit(1), } } fn setup_config( engine_state: &mut EngineState, stack: &mut Stack, config_file: Option<Spanned<String>>, env_file: Option<Spanned<String>>, ) { #[cfg(feature = "plugin")] read_plugin_file(engine_state, stack, NUSHELL_FOLDER, is_perf_true()); if is_perf_true() { info!("read_config_file {}:{}:{}", file!(), line!(), column!()); } config_files::read_config_file(engine_state, stack, env_file, is_perf_true(), true); config_files::read_config_file(engine_state, stack, config_file, is_perf_true(), false); } fn parse_commandline_args( commandline_args: &str, init_cwd: &Path, engine_state: &mut EngineState, ) -> Result<NushellCliArgs, ShellError> { let (block, delta) = { let mut working_set = StateWorkingSet::new(engine_state); working_set.add_decl(Box::new(Nu)); let (output, err) = parse( &mut working_set, None, commandline_args.as_bytes(), false, &[], ); if let Some(err) = err { report_error(&working_set, &err); std::process::exit(1); } working_set.hide_decl(b"nu"); (output, working_set.render()) }; let _ = engine_state.merge_delta(delta, None, init_cwd); let mut stack = Stack::new(); stack.add_var( CONFIG_VARIABLE_ID, Value::Record { cols: vec![], vals: vec![], span: Span::new(0, 0), }, ); // We should have a successful parse now if let Some(pipeline) = block.pipelines.get(0) { if let Some(Expression { expr: Expr::Call(call), .. }) = pipeline.expressions.get(0) { let redirect_stdin = call.get_named_arg("stdin"); let login_shell = call.get_named_arg("login"); let interactive_shell = call.get_named_arg("interactive"); let commands: Option<Expression> = call.get_flag_expr("commands"); let testbin: Option<Expression> = call.get_flag_expr("testbin"); let perf = call.has_flag("perf"); let config_file: Option<Expression> = call.get_flag_expr("config"); let env_file: Option<Expression> = call.get_flag_expr("env-config"); let log_level: Option<Expression> = call.get_flag_expr("log-level"); let threads: Option<Value> = call.get_flag(engine_state, &mut stack, "threads")?; fn extract_contents( expression: Option<Expression>, engine_state: &mut EngineState, ) -> Option<Spanned<String>> { expression.map(|expr| { let contents = engine_state.get_span_contents(&expr.span); Spanned { item: String::from_utf8_lossy(contents).to_string(), span: expr.span, } }) } let commands = extract_contents(commands, engine_state); let testbin = extract_contents(testbin, engine_state); let config_file = extract_contents(config_file, engine_state); let env_file = extract_contents(env_file, engine_state); let log_level = extract_contents(log_level, engine_state); let help = call.has_flag("help"); if help { let full_help = get_full_help(&Nu.signature(), &Nu.examples(), engine_state, &mut stack); let _ = std::panic::catch_unwind(move || { let stdout = std::io::stdout(); let mut stdout = stdout.lock(); let _ = stdout.write_all(full_help.as_bytes()); }); std::process::exit(1); } if call.has_flag("version") { let version = env!("CARGO_PKG_VERSION").to_string(); let _ = std::panic::catch_unwind(move || { let stdout = std::io::stdout(); let mut stdout = stdout.lock(); let _ = stdout.write_all(format!("{}\n", version).as_bytes()); }); std::process::exit(0); } return Ok(NushellCliArgs { redirect_stdin, login_shell, interactive_shell, commands, testbin, config_file, env_file, log_level, perf, threads, }); } } // Just give the help and exit if the above fails let full_help = get_full_help(&Nu.signature(), &Nu.examples(), engine_state, &mut stack); print!("{}", full_help); std::process::exit(1); } struct NushellCliArgs { redirect_stdin: Option<Spanned<String>>, #[allow(dead_code)] login_shell: Option<Spanned<String>>, interactive_shell: Option<Spanned<String>>, commands: Option<Spanned<String>>, testbin: Option<Spanned<String>>, config_file: Option<Spanned<String>>, env_file: Option<Spanned<String>>, log_level: Option<Spanned<String>>, perf: bool, threads: Option<Value>, } #[derive(Clone)] struct Nu; impl Command for Nu { fn name(&self) -> &str { "nu" } fn signature(&self) -> Signature { Signature::build("nu") .usage("The nushell language and shell.") .switch("stdin", "redirect the stdin", None) .switch("login", "start as a login shell", Some('l')) .switch("interactive", "start as an interactive shell", Some('i')) .switch("version", "print the version", Some('v')) .switch( "perf", "start and print performance metrics during startup", Some('p'), ) .named( "testbin", SyntaxShape::String, "run internal test binary", None, ) .named( "commands", SyntaxShape::String, "run the given commands and then exit", Some('c'), ) .named( "config", SyntaxShape::String, "start with an alternate config file", None, ) .named( "env-config", SyntaxShape::String, "start with an alternate environment config file", None, ) .named( "log-level", SyntaxShape::String, "log level for performance logs", None, ) .named( "threads", SyntaxShape::Int, "threads to use for parallel commands", Some('t'), ) .optional( "script file", SyntaxShape::Filepath, "name of the optional script file to run", ) .rest( "script args", SyntaxShape::String, "parameters to the script file", ) .category(Category::System) } fn usage(&self) -> &str { "The nushell language and shell." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { Ok(Value::String { val: get_full_help(&Nu.signature(), &Nu.examples(), engine_state, stack), span: call.head, } .into_pipeline_data()) } fn examples(&self) -> Vec<nu_protocol::Example> { vec![ Example { description: "Run a script", example: "nu myfile.nu", result: None, }, Example { description: "Run nushell interactively (as a shell or REPL)", example: "nu", result: None, }, ] } } pub fn is_perf_true() -> bool { IS_PERF.with(|value| *value.borrow()) } // #[allow(dead_code)] // fn is_perf_value() -> bool { // IS_PERF.with(|value| *value.borrow()) // } fn set_is_perf_value(value: bool) { IS_PERF.with(|new_value| { *new_value.borrow_mut() = value; }); }
use crate::api::consts::*; use crate::state::lua_value::LuaValue; use crate::state::math; fn iadd(a: i64, b: i64) -> i64 { a + b } fn fadd(a: f64, b: f64) -> f64 { a + b } fn isub(a: i64, b: i64) -> i64 { a - b } fn fsub(a: f64, b: f64) -> f64 { a - b } fn imul(a: i64, b: i64) -> i64 { a * b } fn fmul(a: f64, b: f64) -> f64 { a * b } fn imod(a: i64, b: i64) -> i64 { math::integer_mod(a, b) } fn fmod(a: f64, b: f64) -> f64 { math::float_mod(a, b) } fn pow(a: f64, b: f64) -> f64 { a.powf(b) } fn div(a: f64, b: f64) -> f64 { a / b } fn iidiv(a: i64, b: i64) -> i64 { math::integer_floor_div(a, b) } fn fidiv(a: f64, b: f64) -> f64 { math::float_floor_div(a, b) } fn band(a: i64, b: i64) -> i64 { a & b } fn bor(a: i64, b: i64) -> i64 { a | b } fn bxor(a: i64, b: i64) -> i64 { a ^ b } fn shl(a: i64, b: i64) -> i64 { math::shift_left(a, b) } fn shr(a: i64, b: i64) -> i64 { math::shift_right(a, b) } fn iunm(a: i64, _: i64) -> i64 { -a } fn funm(a: f64, _: f64) -> f64 { -a } fn bnot(a: i64, _: i64) -> i64 { !a } fn inone(_: i64, _: i64) -> i64 { 0 } fn fnone(_: f64, _: f64) -> f64 { 0.0 } pub const OPS: &'static [(fn(i64, i64) -> i64, fn(f64, f64) -> f64)] = &[ (iadd, fadd), (isub, fsub), (imul, fmul), (imod, fmod), (inone, pow), (inone, div), (iidiv, fidiv), (band, fnone), (bor, fnone), (bxor, fnone), (shl, fnone), (shr, fnone), (iunm, funm), (bnot, fnone), ]; pub fn arith(a: &LuaValue, b: &LuaValue, op: u8) -> Option<LuaValue> { let iop = OPS[op as usize].0; let fop = OPS[op as usize].1; if fop == fnone { // bitwise if let Some(x) = a.to_integer() { if let Some(y) = b.to_integer() { return Some(LuaValue::Integer(iop(x, y))); } } } else { // arith if iop != inone { // add,sub,mul,mod,idiv,unm if let LuaValue::Integer(x) = a { if let LuaValue::Integer(y) = b { return Some(LuaValue::Integer(iop(*x, *y))); } } } if let Some(x) = a.to_number() { if let Some(y) = b.to_number() { return Some(LuaValue::Number(fop(x, y))); } } } None } pub fn compare(a: &LuaValue, b: &LuaValue, op: u8) -> Option<bool> { match op { LUA_OPEQ => Some(eq(a, b)), LUA_OPLT => lt(a, b), LUA_OPLE => le(a, b), _ => None, } } macro_rules! cmp { ($a:ident $op:tt $b:ident) => { match $a { LuaValue::String(x) => match $b { LuaValue::String(y) => Some(x $op y), _ => None, }, LuaValue::Integer(x) => match $b { LuaValue::Integer(y) => Some(x $op y), LuaValue::Number(y) => Some((*x as f64) $op *y), _ => None, }, LuaValue::Number(x) => match $b { LuaValue::Number(y) => Some(x $op y), LuaValue::Integer(y) => Some(*x $op (*y as f64)), _ => None, }, _ => None, } } } fn eq(a: &LuaValue, b: &LuaValue) -> bool { if let Some(x) = cmp!(a == b) { x } else { match a { LuaValue::Nil => match b { LuaValue::Nil => true, _ => false, }, LuaValue::Boolean(x) => match b { LuaValue::Boolean(y) => x == y, _ => false, }, _ => false, } } } fn lt(a: &LuaValue, b: &LuaValue) -> Option<bool> { cmp!(a < b) } fn le(a: &LuaValue, b: &LuaValue) -> Option<bool> { cmp!(a <= b) }
extern crate error_chain; extern crate kvdemo; extern crate rand; use rand::prelude::random; use kvdemo::client::{ConnectOptions, KVGrpcClient}; use kvdemo::codec::BytesSerializer; use kvdemo::errors::Result; fn rand_int_array(count: usize) -> Vec<u32> { let mut v: Vec<u32> = (0..100u32).collect(); for i in 0..100 { let idx = (random::<u32>() % 100) as usize; let tmp = v[i]; v[i] = v[idx]; v[idx] = tmp; } v.truncate(count); v } fn main() -> Result<()> { let options = ConnectOptions::new("127.0.0.1:8000".into(), 10); let client = KVGrpcClient::open(options); let values = rand_int_array(10); println!("test values: {:?}", &values); let gen_key = |s: u32| { let mut k = "s_".to_string(); k.push_str(&s.to_string()); k }; for v in &values { let k = gen_key(*v); client.put(&k, v)?; println!("put action! key: {}, value: {}", k, *v); } for v in &values { let k = gen_key(*v); let v: Option<u32> = client.get(&k)?; println!("fetch key {}, result {:?}", k, v); } println!("\ntest scan:"); { let mut iter = client.scan::<String>(None)?; loop { if let Some(next) = iter.next() { let key: String = BytesSerializer::from_bytes(&next.key)?; let value: u32 = BytesSerializer::from_bytes(&next.value)?; println!("scan by key {}, value {}", key, value); } else { break; } } } println!("\ntest remove action:"); let v = values[0]; let key = gen_key(v); let v: Option<u32> = client.get(&key)?; println!("fetch key {}, result {:?}", &key, v); client.remove(&key)?; println!("remove action! key: {}", &key); let v: Option<u32> = client.get(&key)?; println!("after remove, fetch key {}, result {:?}", key, v); Ok(()) }
pub mod iser0 { pub mod setena { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E100u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E100u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0xE000E100u32 as *mut u32, reg); } } } } pub mod iser1 { pub mod setena { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E104u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E104u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0xE000E104u32 as *mut u32, reg); } } } } pub mod icer0 { pub mod clrena { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E180u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E180u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0xE000E180u32 as *mut u32, reg); } } } } pub mod icer1 { pub mod clrena { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E184u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E184u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0xE000E184u32 as *mut u32, reg); } } } } pub mod ispr0 { pub mod setpend { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E200u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E200u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0xE000E200u32 as *mut u32, reg); } } } } pub mod ispr1 { pub mod setpend { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E204u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E204u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0xE000E204u32 as *mut u32, reg); } } } } pub mod icpr0 { pub mod clrpend { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E280u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E280u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0xE000E280u32 as *mut u32, reg); } } } } pub mod icpr1 { pub mod clrpend { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E284u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E284u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0xE000E284u32 as *mut u32, reg); } } } } pub mod iabr0 { pub mod active { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E300u32 as *const u32) & 0xFFFFFFFF } } } } pub mod iabr1 { pub mod active { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E304u32 as *const u32) & 0xFFFFFFFF } } } } pub mod ipr0 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E400u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E400u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E400u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E400u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E400u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E400u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E400u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E400u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E400u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E400u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E400u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E400u32 as *mut u32, reg); } } } } pub mod ipr1 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E404u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E404u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E404u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E404u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E404u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E404u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E404u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E404u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E404u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E404u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E404u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E404u32 as *mut u32, reg); } } } } pub mod ipr2 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E408u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E408u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E408u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E408u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E408u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E408u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E408u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E408u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E408u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E408u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E408u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E408u32 as *mut u32, reg); } } } } pub mod ipr3 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E40Cu32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E40Cu32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E40Cu32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E40Cu32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E40Cu32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E40Cu32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E40Cu32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E40Cu32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E40Cu32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E40Cu32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E40Cu32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E40Cu32 as *mut u32, reg); } } } } pub mod ipr4 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E410u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E410u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E410u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E410u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E410u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E410u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E410u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E410u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E410u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E410u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E410u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E410u32 as *mut u32, reg); } } } } pub mod ipr5 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E414u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E414u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E414u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E414u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E414u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E414u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E414u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E414u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E414u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E414u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E414u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E414u32 as *mut u32, reg); } } } } pub mod ipr6 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E418u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E418u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E418u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E418u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E418u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E418u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E418u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E418u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E418u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E418u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E418u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E418u32 as *mut u32, reg); } } } } pub mod ipr7 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E41Cu32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E41Cu32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E41Cu32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E41Cu32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E41Cu32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E41Cu32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E41Cu32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E41Cu32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E41Cu32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E41Cu32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E41Cu32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E41Cu32 as *mut u32, reg); } } } } pub mod ipr8 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E420u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E420u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E420u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E420u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E420u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E420u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E420u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E420u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E420u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E420u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E420u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E420u32 as *mut u32, reg); } } } } pub mod ipr9 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E424u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E424u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E424u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E424u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E424u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E424u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E424u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E424u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E424u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E424u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E424u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E424u32 as *mut u32, reg); } } } } pub mod ipr10 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E428u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E428u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E428u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E428u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E428u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E428u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E428u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E428u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E428u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E428u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E428u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E428u32 as *mut u32, reg); } } } } pub mod ipr11 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E42Cu32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E42Cu32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E42Cu32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E42Cu32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E42Cu32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E42Cu32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E42Cu32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E42Cu32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E42Cu32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E42Cu32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E42Cu32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E42Cu32 as *mut u32, reg); } } } } pub mod ipr12 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E430u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E430u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E430u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E430u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E430u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E430u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E430u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E430u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E430u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E430u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E430u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E430u32 as *mut u32, reg); } } } } pub mod ipr13 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E434u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E434u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E434u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E434u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E434u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E434u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E434u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E434u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E434u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E434u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E434u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E434u32 as *mut u32, reg); } } } } pub mod ipr14 { pub mod ipr_n0 { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E438u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E438u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0xE000E438u32 as *mut u32, reg); } } } pub mod ipr_n1 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E438u32 as *const u32) >> 8) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E438u32 as *const u32); reg &= 0xFFFF00FFu32; reg |= (val & 0xFF) << 8; core::ptr::write_volatile(0xE000E438u32 as *mut u32, reg); } } } pub mod ipr_n2 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E438u32 as *const u32) >> 16) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E438u32 as *const u32); reg &= 0xFF00FFFFu32; reg |= (val & 0xFF) << 16; core::ptr::write_volatile(0xE000E438u32 as *mut u32, reg); } } } pub mod ipr_n3 { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0xE000E438u32 as *const u32) >> 24) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E438u32 as *const u32); reg &= 0xFFFFFFu32; reg |= (val & 0xFF) << 24; core::ptr::write_volatile(0xE000E438u32 as *mut u32, reg); } } } }
//! clap App for command cli use clap::{App, Arg, ValueHint}; const COMMAND: &str = "cli-completion"; const VERSION: &str = "0.1.0"; pub fn build_app() -> App<'static> { // init Clap App::new(COMMAND) .version(VERSION) .author("linux_china, https://twitter.com/linux_china") .about("CLI completion for bash, zsh, fish and powershell.") .arg( Arg::new("zsh") .long("zsh") .takes_value(false) .about("Zsh completion") .required(false), ) .arg( Arg::new("powershell") .long("powershell") .takes_value(false) .about("PowerShell completion") .required(false), ) .arg( Arg::new("bash") .long("bash") .takes_value(false) .about("Bash completion") .required(false), ) .arg( Arg::new("fish") .long("fish") .takes_value(false) .about("Fish completion") .required(false), ) .arg( Arg::new("yaml") .takes_value(true) .required(true) .value_name("FILE") .value_hint(ValueHint::FilePath) .about("CLI clap-rs yaml file"), ) }
#[doc = "Register `FDCAN_RWD` reader"] pub type R = crate::R<FDCAN_RWD_SPEC>; #[doc = "Register `FDCAN_RWD` writer"] pub type W = crate::W<FDCAN_RWD_SPEC>; #[doc = "Field `WDC` reader - WDC"] pub type WDC_R = crate::FieldReader; #[doc = "Field `WDC` writer - WDC"] pub type WDC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `WDV` reader - WDV"] pub type WDV_R = crate::FieldReader; impl R { #[doc = "Bits 0:7 - WDC"] #[inline(always)] pub fn wdc(&self) -> WDC_R { WDC_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - WDV"] #[inline(always)] pub fn wdv(&self) -> WDV_R { WDV_R::new(((self.bits >> 8) & 0xff) as u8) } } impl W { #[doc = "Bits 0:7 - WDC"] #[inline(always)] #[must_use] pub fn wdc(&mut self) -> WDC_W<FDCAN_RWD_SPEC, 0> { WDC_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 = "The RAM watchdog monitors the READY output of the message RAM. A message RAM access starts the message RAM watchdog counter with the value configured by the FDCAN_RWD.WDC bits. The counter is reloaded with FDCAN_RWD.WDC bits when the message RAM signals successful completion by activating its READY output. In case there is no response from the message RAM until the counter has counted down to 0, the counter stops and interrupt flag FDCAN_IR.WDI bit is set. The RAM watchdog counter is clocked by the fdcan_pclk clock.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fdcan_rwd::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 [`fdcan_rwd::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FDCAN_RWD_SPEC; impl crate::RegisterSpec for FDCAN_RWD_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fdcan_rwd::R`](R) reader structure"] impl crate::Readable for FDCAN_RWD_SPEC {} #[doc = "`write(|w| ..)` method takes [`fdcan_rwd::W`](W) writer structure"] impl crate::Writable for FDCAN_RWD_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets FDCAN_RWD to value 0"] impl crate::Resettable for FDCAN_RWD_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std; use std::fs::File; use std::io::{self, Read}; pub fn create(filename: String) -> Box<DataReader> { if filename.is_empty() { Box::new(StandardInputReader::new()) } else { Box::new(FileReader::new(filename)) } } pub trait DataReader { fn read_data(&mut self) -> Result<Vec<u8>, std::io::Error>; } pub struct FileReader { filename: String, read: bool, } impl FileReader { pub fn new(filename: String) -> FileReader { FileReader { filename, read: false, } } } impl DataReader for FileReader { fn read_data(&mut self) -> Result<Vec<u8>, std::io::Error> { if self.read == true { return Err(std::io::Error::new( std::io::ErrorKind::Other, "Already Read", )); } let mut out = Vec::<u8>::new(); let mut file = File::open(self.filename.as_str())?; file.read_to_end(&mut out)?; self.read = true; Ok(out) } } pub struct StandardInputReader {} impl StandardInputReader { pub fn new() -> StandardInputReader { StandardInputReader {} } } impl DataReader for StandardInputReader { fn read_data(&mut self) -> Result<Vec<u8>, std::io::Error> { let mut line = String::new(); io::stdin().read_line(&mut line)?; Ok(line.into_bytes()) } }
use ossdev_01_485516::*; #[test] fn test_basic_primes() { vec![2, 3, 5, 7, 11, 13, 17, 19] .iter() .for_each(|x| assert_eq!(is_prime(*x as u32), true)) } #[test] fn test_not_primes() { vec![4, 6, 9, 15, 27, 81, 64] .iter() .for_each(|x| assert_ne!(is_prime(*x as u32), true)) } #[test] fn test_non_trivial_not_primes() { vec![9059 * 6841, 2617 * 9949, 9887 * 9839, 4451 * 2, 4093 * 4099] .iter() .for_each(|x| assert_ne!(is_prime(*x as u32), true)) } #[test] fn test_get_few_primes() { assert_eq!(get_primes(1, 10), vec![2, 3, 5, 7]) } #[test] fn test_get_more_primes() { assert_eq!( get_primes(1000, 1050), vec![1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049] ) } #[test] fn test_get_no_primes() { assert_eq!(get_primes(20, 22), vec![]) }
#[doc = "Register `CICR` writer"] pub type W = crate::W<CICR_SPEC>; #[doc = "LSI ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LSIRDYC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<LSIRDYC_AW> for bool { #[inline(always)] fn from(variant: LSIRDYC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `LSIRDYC` writer - LSI ready interrupt clear"] pub type LSIRDYC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LSIRDYC_AW>; impl<'a, REG, const O: u8> LSIRDYC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(LSIRDYC_AW::Clear) } } #[doc = "LSE ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LSERDYC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<LSERDYC_AW> for bool { #[inline(always)] fn from(variant: LSERDYC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `LSERDYC` writer - LSE ready interrupt clear"] pub type LSERDYC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LSERDYC_AW>; impl<'a, REG, const O: u8> LSERDYC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(LSERDYC_AW::Clear) } } #[doc = "MSI ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MSIRDYC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<MSIRDYC_AW> for bool { #[inline(always)] fn from(variant: MSIRDYC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `MSIRDYC` writer - MSI ready interrupt clear"] pub type MSIRDYC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MSIRDYC_AW>; impl<'a, REG, const O: u8> MSIRDYC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(MSIRDYC_AW::Clear) } } #[doc = "HSI16 ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSIRDYC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<HSIRDYC_AW> for bool { #[inline(always)] fn from(variant: HSIRDYC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `HSIRDYC` writer - HSI16 ready interrupt clear"] pub type HSIRDYC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSIRDYC_AW>; impl<'a, REG, const O: u8> HSIRDYC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(HSIRDYC_AW::Clear) } } #[doc = "HSE32 ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSERDYC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<HSERDYC_AW> for bool { #[inline(always)] fn from(variant: HSERDYC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `HSERDYC` writer - HSE32 ready interrupt clear"] pub type HSERDYC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSERDYC_AW>; impl<'a, REG, const O: u8> HSERDYC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(HSERDYC_AW::Clear) } } #[doc = "PLL ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PLLRDYC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<PLLRDYC_AW> for bool { #[inline(always)] fn from(variant: PLLRDYC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `PLLRDYC` writer - PLL ready interrupt clear"] pub type PLLRDYC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PLLRDYC_AW>; impl<'a, REG, const O: u8> PLLRDYC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(PLLRDYC_AW::Clear) } } #[doc = "HSE32 Clock security system interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CSSC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<CSSC_AW> for bool { #[inline(always)] fn from(variant: CSSC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `CSSC` writer - HSE32 Clock security system interrupt clear"] pub type CSSC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CSSC_AW>; impl<'a, REG, const O: u8> CSSC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(CSSC_AW::Clear) } } #[doc = "LSE Clock security system interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LSECSSC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<LSECSSC_AW> for bool { #[inline(always)] fn from(variant: LSECSSC_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `LSECSSC` writer - LSE Clock security system interrupt clear"] pub type LSECSSC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LSECSSC_AW>; impl<'a, REG, const O: u8> LSECSSC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(LSECSSC_AW::Clear) } } impl W { #[doc = "Bit 0 - LSI ready interrupt clear"] #[inline(always)] #[must_use] pub fn lsirdyc(&mut self) -> LSIRDYC_W<CICR_SPEC, 0> { LSIRDYC_W::new(self) } #[doc = "Bit 1 - LSE ready interrupt clear"] #[inline(always)] #[must_use] pub fn lserdyc(&mut self) -> LSERDYC_W<CICR_SPEC, 1> { LSERDYC_W::new(self) } #[doc = "Bit 2 - MSI ready interrupt clear"] #[inline(always)] #[must_use] pub fn msirdyc(&mut self) -> MSIRDYC_W<CICR_SPEC, 2> { MSIRDYC_W::new(self) } #[doc = "Bit 3 - HSI16 ready interrupt clear"] #[inline(always)] #[must_use] pub fn hsirdyc(&mut self) -> HSIRDYC_W<CICR_SPEC, 3> { HSIRDYC_W::new(self) } #[doc = "Bit 4 - HSE32 ready interrupt clear"] #[inline(always)] #[must_use] pub fn hserdyc(&mut self) -> HSERDYC_W<CICR_SPEC, 4> { HSERDYC_W::new(self) } #[doc = "Bit 5 - PLL ready interrupt clear"] #[inline(always)] #[must_use] pub fn pllrdyc(&mut self) -> PLLRDYC_W<CICR_SPEC, 5> { PLLRDYC_W::new(self) } #[doc = "Bit 8 - HSE32 Clock security system interrupt clear"] #[inline(always)] #[must_use] pub fn cssc(&mut self) -> CSSC_W<CICR_SPEC, 8> { CSSC_W::new(self) } #[doc = "Bit 9 - LSE Clock security system interrupt clear"] #[inline(always)] #[must_use] pub fn lsecssc(&mut self) -> LSECSSC_W<CICR_SPEC, 9> { LSECSSC_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 = "Clock interrupt clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cicr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CICR_SPEC; impl crate::RegisterSpec for CICR_SPEC { type Ux = u32; } #[doc = "`write(|w| ..)` method takes [`cicr::W`](W) writer structure"] impl crate::Writable for CICR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CICR to value 0"] impl crate::Resettable for CICR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::domain::subscriber_name::SubscriberName; use super::subscriber_email::SubscriberEmail; pub struct NewSubscriber { pub name: SubscriberName, pub email: SubscriberEmail, }
#[doc = "Register `TDR` writer"] pub type W = crate::W<TDR_SPEC>; #[doc = "Field `TD` writer - Transmit data"] pub type TD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>; impl W { #[doc = "Bits 0:31 - Transmit data"] #[inline(always)] #[must_use] pub fn td(&mut self) -> TD_W<TDR_SPEC, 0> { TD_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 = "SWPMI Transmit data register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tdr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct TDR_SPEC; impl crate::RegisterSpec for TDR_SPEC { type Ux = u32; } #[doc = "`write(|w| ..)` method takes [`tdr::W`](W) writer structure"] impl crate::Writable for TDR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets TDR to value 0"] impl crate::Resettable for TDR_SPEC { const RESET_VALUE: Self::Ux = 0; }
mod brainfuck; use brainfuck::{BrainfuckContext, Instruction}; use std::error::Error; use std::fs; pub fn run(program_path: &str) -> Result<(), Box<dyn Error>> { let program_string = fs::read_to_string(program_path)?; let program_parsed = parse(&program_string)?; let mut bf_context = BrainfuckContext::new(); bf_context.execute(program_parsed.as_slice())?; Ok(()) } fn parse(program: &str) -> Result<Vec<Instruction>, Box<dyn Error>> { let chars: Vec<char> = program.chars().collect(); let mut result = Vec::new(); let mut index = 0; while index < chars.len() { match chars[index] { '+' => { let last_index = result.len().wrapping_sub(1); if let Some(ins) = result.get_mut(last_index) { if let Instruction::IncreaseCell(n) = ins { *ins = Instruction::IncreaseCell(*n + 1); } else { result.push(Instruction::IncreaseCell(1)); } } else { result.push(Instruction::IncreaseCell(1)); } }, '-' => { let last_index = result.len().wrapping_sub(1); if let Some(ins) = result.get_mut(last_index) { if let Instruction::DecreaseCell(n) = ins { *ins = Instruction::DecreaseCell(*n + 1); } else { result.push(Instruction::DecreaseCell(1)); } } else { result.push(Instruction::DecreaseCell(1)); } }, '>' => { let last_index = result.len().wrapping_sub(1); if let Some(ins) = result.get_mut(last_index) { if let Instruction::NextCell(n) = ins { *ins = Instruction::NextCell(*n + 1); } else { result.push(Instruction::NextCell(1)); } } else { result.push(Instruction::NextCell(1)); } }, '<' => { let last_index = result.len().wrapping_sub(1); if let Some(ins) = result.get_mut(last_index) { if let Instruction::PreviousCell(n) = ins { *ins = Instruction::PreviousCell(*n + 1); } else { result.push(Instruction::PreviousCell(1)); } } else { result.push(Instruction::PreviousCell(1)); } }, '.' => result.push(Instruction::PrintCharacter), ',' => result.push(Instruction::ReadCharacter), '[' => { index += 1; let loop_start = index; let mut false_positives = 0; while chars[index] != ']' || false_positives != 0 { match chars[index] { '[' => false_positives += 1, ']' => false_positives -= 1, _ => (), } index += 1; } let instructions = parse(&program[loop_start..index])?; let loop_instruction = Instruction::Loop(instructions); result.push(loop_instruction); }, ']' => Err("End of loop without beginning.")?, _ => (), } index += 1; } Ok(result) }
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //! A basic chat application demonstrating libp2p with the mDNS and floodsub protocols //! using tokio for all asynchronous tasks and I/O. In order for all used libp2p //! crates to use tokio, it enables tokio-specific features for some crates. //! //! The example is run per node as follows: //! //! ```sh //! cargo run --example chat-tokio --features=full //! ``` use futures::StreamExt; use libp2p::{ core::upgrade, floodsub::{self, Floodsub, FloodsubEvent}, identity, mdns, mplex, noise, swarm::{NetworkBehaviour, SwarmEvent}, tcp, Multiaddr, PeerId, Transport, }; use std::error::Error; use tokio::io::{self, AsyncBufReadExt}; /// The `tokio::main` attribute sets up a tokio runtime. #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { env_logger::init(); // Create a random PeerId let id_keys = identity::Keypair::generate_ed25519(); let peer_id = PeerId::from(id_keys.public()); println!("Local peer id: {peer_id:?}"); // Create a tokio-based TCP transport use noise for authenticated // encryption and Mplex for multiplexing of substreams on a TCP stream. let transport = tcp::tokio::Transport::new(tcp::Config::default().nodelay(true)) .upgrade(upgrade::Version::V1) .authenticate( noise::NoiseAuthenticated::xx(&id_keys) .expect("Signing libp2p-noise static DH keypair failed."), ) .multiplex(mplex::MplexConfig::new()) .boxed(); // Create a Floodsub topic let floodsub_topic = floodsub::Topic::new("chat"); // We create a custom behaviour that combines floodsub and mDNS. // The derive generates a delegating `NetworkBehaviour` impl. #[derive(NetworkBehaviour)] #[behaviour(out_event = "MyBehaviourEvent")] struct MyBehaviour { floodsub: Floodsub, mdns: mdns::tokio::Behaviour, } #[allow(clippy::large_enum_variant)] enum MyBehaviourEvent { Floodsub(FloodsubEvent), Mdns(mdns::Event), } impl From<FloodsubEvent> for MyBehaviourEvent { fn from(event: FloodsubEvent) -> Self { MyBehaviourEvent::Floodsub(event) } } impl From<mdns::Event> for MyBehaviourEvent { fn from(event: mdns::Event) -> Self { MyBehaviourEvent::Mdns(event) } } // Create a Swarm to manage peers and events. let mdns_behaviour = mdns::Behaviour::new(Default::default(), peer_id)?; let mut behaviour = MyBehaviour { floodsub: Floodsub::new(peer_id), mdns: mdns_behaviour, }; behaviour.floodsub.subscribe(floodsub_topic.clone()); let mut swarm = libp2p_swarm::Swarm::with_tokio_executor(transport, behaviour, peer_id); // Reach out to another node if specified if let Some(to_dial) = std::env::args().nth(1) { let addr: Multiaddr = to_dial.parse()?; swarm.dial(addr)?; println!("Dialed {to_dial:?}"); } // Read full lines from stdin let mut stdin = io::BufReader::new(io::stdin()).lines(); // Listen on all interfaces and whatever port the OS assigns swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?; // Kick it off loop { tokio::select! { line = stdin.next_line() => { let line = line?.expect("stdin closed"); swarm.behaviour_mut().floodsub.publish(floodsub_topic.clone(), line.as_bytes()); } event = swarm.select_next_some() => { match event { SwarmEvent::NewListenAddr { address, .. } => { println!("Listening on {address:?}"); } SwarmEvent::Behaviour(MyBehaviourEvent::Floodsub(FloodsubEvent::Message(message))) => { println!( "Received: '{:?}' from {:?}", String::from_utf8_lossy(&message.data), message.source ); } SwarmEvent::Behaviour(MyBehaviourEvent::Mdns(event)) => { match event { mdns::Event::Discovered(list) => { for (peer, _) in list { swarm.behaviour_mut().floodsub.add_node_to_partial_view(peer); } } mdns::Event::Expired(list) => { for (peer, _) in list { if !swarm.behaviour().mdns.has_node(&peer) { swarm.behaviour_mut().floodsub.remove_node_from_partial_view(&peer); } } } } } _ => {} } } } } }
use clap::ArgMatches; use crate::errors::StandardResult; use crate::utils::config::ConfigIO; use crate::INSTALL_DIR; pub fn list(_args: &ArgMatches) -> StandardResult<()> { let io = ConfigIO::new()?; for template in io.iter() { println!("{} {}/{}", template.name, INSTALL_DIR, template.path); } Ok(()) }
use crate::token:: { TokenKind, Token }; #[derive(Debug, Clone)] pub enum Ast { Program { statements: Vec<Box<Ast>> }, Expression { token: Token, }, Identifier { token: Token, value: String, }, LetStatement { token: Token, ident: Box<Ast>, value: Box<Ast>, }, ReturnStatement { token: Token, return_value: Box<Ast>, }, ExpressionStatement { token: Token, expression: Box<Ast>, }, IntegerLiteral { token: Token, value: i64, }, PrefixExpression { token: Token, operator: String, right: Box<Ast>, }, InfixExpression { token: Token, left: Box<Ast>, operator: String, right: Box<Ast>, }, Boolean { token: Token, value: bool, }, IfExpression { token: Token, condition: Box<Ast>, consequence: Box<Ast>, alternative: Box<Ast>, }, BlockStatement { token: Token, statements: Vec<Box<Ast>>, }, FunctionLiteral { token: Token, parameters: Vec<Box<Ast>>, // Ast::Identifier body: Box<Ast>, // Ast::BlockStatement }, CallExpression { token: Token, // '(' token function: Box<Ast>, // Ast::Identifier or Ast::FunctionLiteral arguments: Vec<Box<Ast>>, }, StringLiteral { token: Token, value: String, }, ArrayLiteral { token: Token, elements: Vec<Box<Ast>>, }, IndexExpression { token: Token, left: Box<Ast>, index: Box<Ast>, } } impl Ast { pub fn to_string(&self) -> String { let mut string = String::new(); match self { Ast::Program { statements } => { for statement in statements { string = format!("{}{}", string, statement.to_string() ); } }, Ast::Identifier { value, .. } => { string = format!("{}", value); }, Ast::LetStatement {token, ident, value} => { string = format!("{} {} = {};", token.literal, ident.to_string(), value.to_string()); }, Ast::ReturnStatement { token, return_value } => { string = format!("{} {};", token.literal, return_value.to_string()); }, Ast::ExpressionStatement { expression,.. } => { string = format!("{}", expression.to_string()); }, Ast::Expression { token } => { string = format!("{}", token.literal); }, Ast::IntegerLiteral { token, .. } => { string = format!("{}", token.literal); }, Ast::PrefixExpression { operator, right, ..} => { string = format!("({}{})", operator, right.to_string()); }, Ast::InfixExpression { left, operator, right, .. } => { string = format!("({} {} {})", left.to_string(), operator, right.to_string()); }, Ast::Boolean { value, ..} => { string = format!("{}", value.to_string()); }, Ast::IfExpression { token, condition, consequence, alternative } => { string = format!("{}({}) {{ {} }}", token.literal, condition.to_string(), consequence.to_string()); if let Ast::BlockStatement { ref token, ..} = **alternative { match token.kind { TokenKind::Illegal => (), _ => string = format!("{}else {{ {} }}", string, alternative.to_string()), } }; }, Ast::BlockStatement { statements, .. } => { for statement in statements { string = format!("{}{}", string, statement.to_string()); } }, Ast::FunctionLiteral { token, parameters, body } => { string = format!("{}(", token.literal); for (i, parameter ) in parameters.iter().enumerate() { if i == 0 { string = format!("{}{}", string, parameter.to_string()); } else { string = format!("{}, {}", string, parameter.to_string()); } } string = format!("{}) {{{}}}", string, body.to_string()); } Ast::CallExpression { ref function, arguments, .. } => { match **function { Ast::Identifier { ref value, .. } => string = format!("{}", value.to_string()), Ast::FunctionLiteral { .. } => string = format!("{}", function.to_string()), _ => (), } string = format!("{}(", string); for (i, argument) in arguments.iter().enumerate() { if i == 0 { string = format!("{}{}", string, argument.to_string()); } else { string = format!("{}, {}", string, argument.to_string()); } } string = format!("{})", string); } Ast::StringLiteral { value, .. } => string = value.to_string(), Ast::ArrayLiteral { elements, .. } => { string = format!("["); for (i, element) in elements.iter().enumerate() { if i == 0 { string = format!("{}{}", string, element.to_string()); } else { string = format!("{}, {}", string, element.to_string()); } } string = format!("{}]", string); }, Ast::IndexExpression { left, index, .. } => string = format!("({}[{}])", left.to_string(), index.to_string()), } string } pub fn get_kind_literal(&self) -> String { match self { Ast::Program {..} => "Program".to_string(), Ast::Identifier {..} => "Identifier".to_string(), Ast::LetStatement {..} => "LetStatement".to_string(), Ast::ReturnStatement {..} => "ReturnStatement".to_string(), Ast::ExpressionStatement {..} => "ExpressionStatement".to_string(), Ast::Expression {..} => "Expression".to_string(), Ast::IntegerLiteral {..} => "IntegerLiteral".to_string(), Ast::PrefixExpression {..} => "PrefixExpression".to_string(), Ast::InfixExpression {..} => "InfixExpression".to_string(), Ast::Boolean {..} => "Boolean".to_string(), Ast::IfExpression {..} => "IfExpression".to_string(), Ast::BlockStatement {..} => "BlockStatement".to_string(), Ast::FunctionLiteral {..} => "FunctionLiteral".to_string(), Ast::CallExpression {..} => "CallExpression".to_string(), Ast::StringLiteral {..} => "StringLiteral".to_string(), Ast::ArrayLiteral {..} => "ArrayLiteral".to_string(), Ast::IndexExpression {..} => "IndexExpression".to_string(), } } } #[test] fn test_ast_string() { let program = Ast::Program { statements: vec![ Box::new( Ast::LetStatement { token: Token { kind: TokenKind::Let, literal: "let".to_string() }, ident: Box::new( Ast::Identifier { token: Token { kind: TokenKind::Identifier, literal: "myVar".to_string() }, value: "myVar".to_string() } ), value: Box::new( Ast::Expression { token: Token { kind: TokenKind::Identifier, literal: "anotherVar".to_string() } } ) } ) ] }; assert_eq!(program.to_string(), "let myVar = anotherVar;".to_string()); }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// AwsTagFilterListResponse : An array of tag filter rules by `namespace` and tag filter string. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AwsTagFilterListResponse { /// An array of tag filters. #[serde(rename = "filters", skip_serializing_if = "Option::is_none")] pub filters: Option<Vec<crate::models::AwsTagFilter>>, } impl AwsTagFilterListResponse { /// An array of tag filter rules by `namespace` and tag filter string. pub fn new() -> AwsTagFilterListResponse { AwsTagFilterListResponse { filters: None, } } }
mod day01; mod day02; mod day03; fn main() { let _ = day01::main(); let _ = day02::main(); let _ = day03::main(); }
use fnv::FnvHashSet; #[derive(Debug, Serialize, Deserialize, Clone, Copy, Eq, PartialEq, Hash)] pub enum Features { All, TokensToTextID, BoostTextLocality, BoostingFieldData, Search, Filters, Facets, Select, WhyFound, Highlight, PhraseBoost, } impl Features { pub fn get_default_features() -> FnvHashSet<Features> { [Features::Search, Features::TokensToTextID].iter().cloned().collect() } pub fn invert(features: &FnvHashSet<Features>) -> FnvHashSet<Features> { let all_features: &[Features] = &[ Features::TokensToTextID, Features::BoostTextLocality, Features::BoostingFieldData, Features::Search, Features::Filters, Features::Facets, Features::Select, Features::WhyFound, Features::Highlight, Features::PhraseBoost, ]; all_features.iter().filter(|feature| features.contains(feature)).cloned().collect() } /// detects the needed index types from features pub fn features_to_disabled_indices(features: &FnvHashSet<Features>) -> FnvHashSet<IndexCreationType> { let mut hashset = FnvHashSet::default(); let add_if_features_not_used = |f: &[Features], index_type: IndexCreationType, hashset: &mut FnvHashSet<IndexCreationType>| { for feature in f { if features.contains(feature) { return; } } hashset.insert(index_type); }; add_if_features_not_used( &[ Features::All, Features::TokensToTextID, Features::BoostTextLocality, Features::Highlight, Features::BoostingFieldData, ], IndexCreationType::TokensToTextID, &mut hashset, ); add_if_features_not_used(&[Features::All, Features::Search], IndexCreationType::TokenToAnchorIDScore, &mut hashset); add_if_features_not_used(&[Features::All, Features::Select, Features::Facets], IndexCreationType::ParentToValueID, &mut hashset); add_if_features_not_used(&[Features::All, Features::BoostingFieldData], IndexCreationType::ValueIDToParent, &mut hashset); add_if_features_not_used(&[Features::All, Features::PhraseBoost], IndexCreationType::PhrasePairToAnchor, &mut hashset); add_if_features_not_used(&[Features::All, Features::Select, Features::WhyFound], IndexCreationType::TextIDToTokenIds, &mut hashset); add_if_features_not_used(&[Features::All, Features::BoostingFieldData], IndexCreationType::TextIDToParent, &mut hashset); add_if_features_not_used(&[Features::All, Features::Facets, Features::Select], IndexCreationType::ParentToTextID, &mut hashset); //TODO can be diabled if facets is on non root element add_if_features_not_used( &[Features::All, Features::BoostTextLocality, Features::Select, Features::Filters], IndexCreationType::TextIDToAnchor, &mut hashset, ); hashset } } #[derive(Debug, Serialize, Deserialize, Clone, Copy, Eq, PartialEq, Hash)] pub enum IndexCreationType { TokensToTextID, // Used by boost_text_locality, highlighting(why?), when resolving from a field to boost data (boost but indirectly) TODO: detect when boost is on same level and activate TokenToAnchorIDScore, //normal search PhrasePairToAnchor, //phrase boost TextIDToTokenIds, // highlight document(why_found, when select), select TextIDToParent, // queries with boost indices on fields (slow search path) ParentToTextID, // facets on root, facets on sublevel with no special direct index, select ParentToValueID, // select ValueIDToParent, // select TextIDToAnchor, // Boost text locality, exact filters like facets }
use std::ops::Drop; #[derive(Debug)] struct S(i32); impl Drop for S{ fn drop(&mut self){ println!("drop for {}",self.0); } } fn main(){ let x=S(1); println!("create x:{:?}",x); let x=S(2); println!("create shadowing x:{:?}",x); }
/// Activatable data acumulator. pub struct StringAccumulator { acc: Option<String>, } impl StringAccumulator { /// Create a new data accumulator. pub fn new() -> StringAccumulator { StringAccumulator { acc: None } } /// Start accumulating data pub fn activate(&mut self) { self.acc = Some(String::with_capacity(1024)); } /// Add a slice of data to the accumulator. pub fn add_slice<S: AsRef<str>>(&mut self, other: S) { if let Some(string) = self.acc.as_mut() { string.push_str(other.as_ref()); } } pub fn finish(&mut self) -> String { if let Some(string) = self.acc.take() { string } else { String::new() } } } #[test] fn test_empty() { let mut acc = StringAccumulator::new(); let res = acc.finish(); assert!(res.is_empty()); } #[test] fn test_add_inactive() { let mut acc = StringAccumulator::new(); acc.add_slice("foo"); let res = acc.finish(); assert!(res.is_empty()); } #[test] fn test_accum() { let mut acc = StringAccumulator::new(); acc.activate(); acc.add_slice("lorem"); acc.add_slice(" ipsum"); let res = acc.finish(); assert_eq!(res, "lorem ipsum".to_owned()); } #[test] fn test_accum_finish() { let mut acc = StringAccumulator::new(); acc.activate(); acc.add_slice("lorem"); acc.add_slice(" ipsum"); let res = acc.finish(); assert_eq!(res, "lorem ipsum".to_owned()); acc.add_slice("bob"); let res = acc.finish(); assert!(res.is_empty()) } #[test] fn test_accum_twice() { let mut acc = StringAccumulator::new(); acc.activate(); acc.add_slice("lorem"); acc.add_slice(" ipsum"); let res = acc.finish(); assert_eq!(res, "lorem ipsum".to_owned()); acc.add_slice("bob"); acc.activate(); acc.add_slice("fishbone"); let res = acc.finish(); assert_eq!(res, "fishbone".to_owned()); }
use crate::core::{ authentication_barcode, authentication_nfc, authentication_password, fuzzy_vec_match, Account, Money, Permission, Pool, ServiceError, ServiceResult, }; use crate::identity_policy::{Action, RetrievedAccount}; use crate::login_required; use crate::web::utils::{EmptyToNone, HbData, IsJson, Search}; use actix_web::{http, web, HttpRequest, HttpResponse}; use handlebars::Handlebars; use uuid::Uuid; use std::collections::HashMap; #[derive(Debug, Serialize, Deserialize)] pub struct FormAccount { pub id: String, pub name: String, pub mail: String, pub username: String, pub account_number: String, pub minimum_credit: f32, pub permission: Permission, pub receives_monthly_report: Option<String>, #[serde(flatten)] pub extra: HashMap<String, String>, } #[derive(Debug, Serialize, Deserialize)] pub enum DisplayType { TEXT, EDIT, LINK, } #[derive(Debug, Serialize, Deserialize)] pub struct AuthenticationMethod { pub name: String, pub display: Option<(DisplayType, String)>, pub action: Option<(String, String)>, pub id: Option<String>, } #[derive(Debug, Serialize)] pub struct SearchAccount { #[serde(flatten)] pub account: Account, pub id_search: String, pub name_search: String, pub mail_search: String, pub username_search: String, pub account_number_search: String, pub permission_search: String, } impl SearchAccount { pub fn wrap(account: Account, search: &str) -> Option<SearchAccount> { let values = vec![ account .id .to_hyphenated() .encode_upper(&mut Uuid::encode_buffer()) .to_owned(), account.name.clone(), account.mail.clone().unwrap_or_else(|| "".to_owned()), account.username.clone().unwrap_or_else(|| "".to_owned()), account .account_number .clone() .unwrap_or_else(|| "".to_owned()), match account.permission { Permission::DEFAULT => "", Permission::MEMBER => "member", Permission::ADMIN => "admin", } .to_owned(), ]; let mut result = if search.is_empty() { values } else { match fuzzy_vec_match(search, &values) { Some(r) => r, None => return None, } }; Some(SearchAccount { account, permission_search: result.pop().expect(""), account_number_search: result.pop().expect(""), username_search: result.pop().expect(""), mail_search: result.pop().expect(""), name_search: result.pop().expect(""), id_search: result.pop().expect(""), }) } } /// GET route for `/admin/accounts` pub async fn get_accounts( pool: web::Data<Pool>, hb: web::Data<Handlebars<'_>>, logged_account: RetrievedAccount, query: web::Query<Search>, request: HttpRequest, ) -> ServiceResult<HttpResponse> { let action = request.redirect_type(); let logged_account = login_required!(logged_account, Permission::MEMBER, action); let conn = &pool.get()?; let search = match &query.search { Some(s) => s.clone(), None => "".to_owned(), }; let lower_search = search.trim().to_ascii_lowercase(); let search_accounts: Vec<SearchAccount> = Account::all(&conn)? .into_iter() .filter_map(|a| SearchAccount::wrap(a, &lower_search)) .collect(); if request.is_json() { Ok(HttpResponse::Ok().json(search_accounts)) } else { let body = HbData::new(&request) .with_account(logged_account) .with_data("search", &search) .with_data("accounts", &search_accounts) .render(&hb, "admin_account_list")?; Ok(HttpResponse::Ok().body(body)) } } /// GET route for `/admin/account/{account_id}` pub async fn get_account_edit( pool: web::Data<Pool>, hb: web::Data<Handlebars<'_>>, logged_account: RetrievedAccount, account_id: web::Path<String>, request: HttpRequest, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let conn = &pool.get()?; let account = Account::get(&conn, &Uuid::parse_str(&account_id)?)?; let has_mail_address = account.mail.is_some(); let mut authentication_methods: Vec<AuthenticationMethod> = vec![]; if let Some(invitation_link) = authentication_password::get_invitation_link(&conn, &account)? { authentication_methods.push(AuthenticationMethod { name: "Invite link".to_owned(), display: Some((DisplayType::LINK, format!("/register/{}", invitation_link))), action: Some(( "Revoke".to_owned(), format!("/admin/account/revoke/{}", &account.id), )), id: None, }); } if authentication_password::has_password(&conn, &account)? { authentication_methods.push(AuthenticationMethod { name: "Password".to_owned(), display: Some((DisplayType::TEXT, "Password exists".to_owned())), action: Some(( "Revoke".to_owned(), format!("/admin/account/revoke/{}", &account.id), )), id: None, }); } if authentication_methods.is_empty() { authentication_methods.push(AuthenticationMethod { name: "Password".to_owned(), display: None, action: Some(( "Create invitation".to_owned(), format!("/admin/account/invite/{}", &account.id), )), id: None, }); } for (barcode_id, barcode) in authentication_barcode::get_barcodes(&conn, &account)? .into_iter() .enumerate() { authentication_methods.push(AuthenticationMethod { name: "Barcode".to_owned(), display: Some((DisplayType::TEXT, barcode)), action: Some(( "Delete".to_owned(), format!("/admin/account/remove-barcode/{}", &account.id), )), id: Some(format!("barcode-{}", barcode_id)), }); } if authentication_methods.len() == 1 { authentication_methods.push(AuthenticationMethod { name: "Add Barcode".to_owned(), display: Some((DisplayType::EDIT, "".to_owned())), action: None, id: Some("barcode-new".to_owned()), }); } for (nfc_id, nfc) in authentication_nfc::get_nfcs(&conn, &account)? .into_iter() .enumerate() { let card_id = nfc.card_id.clone(); let name = if nfc.is_secure() { "NFC (secure)" } else if nfc.need_write_key(&conn)? { "NFC (pending)" } else { "NFC (insecure)" } .to_owned(); authentication_methods.push(AuthenticationMethod { name, display: Some((DisplayType::TEXT, card_id)), action: Some(( "Delete".to_owned(), format!("/admin/account/remove-nfc/{}", &account.id), )), id: Some(format!("nfc-{}", nfc_id)), }); } if authentication_methods.len() == 2 { authentication_methods.push(AuthenticationMethod { name: "Add NFC".to_owned(), display: Some((DisplayType::EDIT, "".to_owned())), action: None, id: Some("nfc-new".to_owned()), }); } let body = HbData::new(&request) .with_account(logged_account) .with_data("account", &account) .with_data("authentication_methods", &authentication_methods) .with_data("has_mail_address", &has_mail_address) .render(&hb, "admin_account_edit")?; Ok(HttpResponse::Ok().body(body)) } /// POST route for `/admin/account/{account_id}` pub async fn post_account_edit( pool: web::Data<Pool>, logged_account: RetrievedAccount, account: web::Form<FormAccount>, account_id: web::Path<String>, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); if *account_id != account.id { return Err(ServiceError::BadRequest( "Id missmage", "The product id of the url and the form do not match!".to_owned(), )); } let conn = &pool.get()?; let mut server_account = Account::get(&conn, &Uuid::parse_str(&account_id)?)?; server_account.name = account.name.clone(); let new_mail = account.mail.empty_to_none(); // only enable monthly reports when mail address is existent server_account.receives_monthly_report = new_mail.is_some() && (account.receives_monthly_report == Some("on".to_string())); server_account.mail = new_mail; server_account.username = account.username.empty_to_none(); server_account.account_number = account.account_number.empty_to_none(); server_account.permission = account.permission; server_account.minimum_credit = (account.minimum_credit * 100.0) as Money; server_account.update(&conn)?; let mut reauth = false; for (key, value) in &account.extra { if value.trim().is_empty() { continue; } if key.starts_with("barcode-new") { authentication_barcode::register(&conn, &server_account, value).ok(); } if key.starts_with("nfc-new") { let mut writeable = false; let value = if value.starts_with("ascii:") { writeable = true; value.replace("ascii:", "").trim().to_owned() } else { value.clone() }; authentication_nfc::register(&conn, &server_account, &value, writeable).ok(); reauth = true; } } let location = if reauth { "/admin/accounts?reauthenticate" } else { "/admin/accounts" }; Ok(HttpResponse::Found() .header(http::header::LOCATION, location) .finish()) } /// GET route for `/admin/account/create` pub async fn get_account_create( hb: web::Data<Handlebars<'_>>, logged_account: RetrievedAccount, request: HttpRequest, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let body = HbData::new(&request) .with_account(logged_account) .render(&hb, "admin_account_create")?; Ok(HttpResponse::Ok().body(body)) } /// POST route for `/admin/account/create` pub async fn post_account_create( pool: web::Data<Pool>, logged_account: RetrievedAccount, account: web::Form<FormAccount>, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let conn = &pool.get()?; let mut server_account = Account::create(&conn, &account.name, account.permission)?; server_account.mail = account.mail.empty_to_none(); server_account.username = account.username.empty_to_none(); server_account.account_number = account.account_number.empty_to_none(); server_account.minimum_credit = (account.minimum_credit * 100.0) as Money; server_account.update(&conn)?; Ok(HttpResponse::Found() .header( http::header::LOCATION, format!("/admin/account/{}", server_account.id), ) .finish()) } /// GET route for `/admin/account/invite/{account_id}` pub async fn invite_get( pool: web::Data<Pool>, logged_account: RetrievedAccount, account_id: web::Path<String>, ) -> ServiceResult<HttpResponse> { login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let conn = &pool.get()?; let account = Account::get(&conn, &Uuid::parse_str(&account_id)?)?; authentication_password::create_invitation_link(&conn, &account)?; Ok(HttpResponse::Found() .header( http::header::LOCATION, format!("/admin/account/{}", account.id), ) .finish()) } /// GET route for `/admin/account/revoke/{account_id}` pub async fn revoke_get( pool: web::Data<Pool>, logged_account: RetrievedAccount, account_id: web::Path<String>, ) -> ServiceResult<HttpResponse> { login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let conn = &pool.get()?; let account = Account::get(&conn, &Uuid::parse_str(&account_id)?)?; authentication_password::revoke_invitation_link(&conn, &account)?; authentication_password::remove(&conn, &account)?; Ok(HttpResponse::Found() .header( http::header::LOCATION, format!("/admin/account/{}", account.id), ) .finish()) } /// GET route for `/admin/account/remove-nfc/{account_id}` pub async fn remove_nfc_get( pool: web::Data<Pool>, logged_account: RetrievedAccount, account_id: web::Path<String>, ) -> ServiceResult<HttpResponse> { login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let conn = &pool.get()?; let account = Account::get(&conn, &Uuid::parse_str(&account_id)?)?; authentication_nfc::remove(&conn, &account)?; Ok(HttpResponse::Found() .header( http::header::LOCATION, format!("/admin/account/{}", account.id), ) .finish()) } /// GET route for `/admin/account/remove-nfc/{account_id}` pub async fn remove_barcode_get( pool: web::Data<Pool>, logged_account: RetrievedAccount, account_id: web::Path<String>, ) -> ServiceResult<HttpResponse> { login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let conn = &pool.get()?; let account = Account::get(&conn, &Uuid::parse_str(&account_id)?)?; authentication_barcode::remove(&conn, &account)?; Ok(HttpResponse::Found() .header( http::header::LOCATION, format!("/admin/account/{}", account.id), ) .finish()) } /// GET route for `/admin/account/delete/{account_id}` pub async fn delete_get( _hb: web::Data<Handlebars<'_>>, logged_account: RetrievedAccount, _account_id: web::Path<String>, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); println!("Delete is not supported!"); Ok(HttpResponse::Found() .header(http::header::LOCATION, "/admin/accounts") .finish()) }
use crate::{backend::SchemaBuilder, prepare::*, types::*, ColumnDef, SchemaStatementBuilder}; /// Alter a table /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let table = Table::alter() /// .table(Font::Table) /// .add_column(ColumnDef::new(Alias::new("new_col")).integer().not_null().default(100)) /// .to_owned(); /// /// assert_eq!( /// table.to_string(MysqlQueryBuilder), /// r#"ALTER TABLE `font` ADD COLUMN `new_col` int NOT NULL DEFAULT 100"# /// ); /// assert_eq!( /// table.to_string(PostgresQueryBuilder), /// r#"ALTER TABLE "font" ADD COLUMN "new_col" integer NOT NULL DEFAULT 100"# /// ); /// assert_eq!( /// table.to_string(SqliteQueryBuilder), /// r#"ALTER TABLE `font` ADD COLUMN `new_col` integer NOT NULL DEFAULT 100"#, /// ); /// ``` #[derive(Debug, Clone)] pub struct TableAlterStatement { pub(crate) table: Option<DynIden>, pub(crate) alter_option: Option<TableAlterOption>, } /// All available table alter options #[derive(Debug, Clone)] pub enum TableAlterOption { AddColumn(ColumnDef), ModifyColumn(ColumnDef), RenameColumn(DynIden, DynIden), DropColumn(DynIden), } impl Default for TableAlterStatement { fn default() -> Self { Self::new() } } impl TableAlterStatement { /// Construct alter table statement pub fn new() -> Self { Self { table: None, alter_option: None, } } /// Set table name pub fn table<T: 'static>(mut self, table: T) -> Self where T: Iden, { self.table = Some(SeaRc::new(table)); self } /// Add a column to an existing table /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let table = Table::alter() /// .table(Font::Table) /// .add_column(ColumnDef::new(Alias::new("new_col")).integer().not_null().default(100)) /// .to_owned(); /// /// assert_eq!( /// table.to_string(MysqlQueryBuilder), /// r#"ALTER TABLE `font` ADD COLUMN `new_col` int NOT NULL DEFAULT 100"# /// ); /// assert_eq!( /// table.to_string(PostgresQueryBuilder), /// r#"ALTER TABLE "font" ADD COLUMN "new_col" integer NOT NULL DEFAULT 100"# /// ); /// assert_eq!( /// table.to_string(SqliteQueryBuilder), /// r#"ALTER TABLE `font` ADD COLUMN `new_col` integer NOT NULL DEFAULT 100"#, /// ); /// ``` pub fn add_column(self, column_def: ColumnDef) -> Self { self.alter_option(TableAlterOption::AddColumn(column_def)) } /// Modify a column in an existing table /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let table = Table::alter() /// .table(Font::Table) /// .modify_column(ColumnDef::new(Alias::new("new_col")).big_integer().default(999)) /// .to_owned(); /// /// assert_eq!( /// table.to_string(MysqlQueryBuilder), /// r#"ALTER TABLE `font` MODIFY COLUMN `new_col` bigint DEFAULT 999"# /// ); /// assert_eq!( /// table.to_string(PostgresQueryBuilder), /// vec![ /// r#"ALTER TABLE "font""#, /// r#"ALTER COLUMN "new_col" TYPE bigint,"#, /// r#"ALTER COLUMN "new_col" SET DEFAULT 999"#, /// ].join(" ") /// ); /// // Sqlite not support modifying table column /// ``` pub fn modify_column(self, column_def: ColumnDef) -> Self { self.alter_option(TableAlterOption::ModifyColumn(column_def)) } /// Rename a column in an existing table /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let table = Table::alter() /// .table(Font::Table) /// .rename_column(Alias::new("new_col"), Alias::new("new_column")) /// .to_owned(); /// /// assert_eq!( /// table.to_string(MysqlQueryBuilder), /// r#"ALTER TABLE `font` RENAME COLUMN `new_col` TO `new_column`"# /// ); /// assert_eq!( /// table.to_string(PostgresQueryBuilder), /// r#"ALTER TABLE "font" RENAME COLUMN "new_col" TO "new_column""# /// ); /// assert_eq!( /// table.to_string(SqliteQueryBuilder), /// r#"ALTER TABLE `font` RENAME COLUMN `new_col` TO `new_column`"# /// ); /// ``` pub fn rename_column<T: 'static, R: 'static>(self, from_name: T, to_name: R) -> Self where T: Iden, R: Iden, { self.alter_option(TableAlterOption::RenameColumn( SeaRc::new(from_name), SeaRc::new(to_name), )) } /// Add a column to existing table /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let table = Table::alter() /// .table(Font::Table) /// .drop_column(Alias::new("new_column")) /// .to_owned(); /// /// assert_eq!( /// table.to_string(MysqlQueryBuilder), /// r#"ALTER TABLE `font` DROP COLUMN `new_column`"# /// ); /// assert_eq!( /// table.to_string(PostgresQueryBuilder), /// r#"ALTER TABLE "font" DROP COLUMN "new_column""# /// ); /// // Sqlite not support modifying table column /// ``` pub fn drop_column<T: 'static>(self, col_name: T) -> Self where T: Iden, { self.alter_option(TableAlterOption::DropColumn(SeaRc::new(col_name))) } fn alter_option(mut self, alter_option: TableAlterOption) -> Self { self.alter_option = Some(alter_option); self } } impl SchemaStatementBuilder for TableAlterStatement { fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String { let mut sql = SqlWriter::new(); schema_builder.prepare_table_alter_statement(self, &mut sql); sql.result() } fn build_any(&self, schema_builder: &dyn SchemaBuilder) -> String { let mut sql = SqlWriter::new(); schema_builder.prepare_table_alter_statement(self, &mut sql); sql.result() } }
use super::*; use crate::lexer::Lexer; use crate::parser::Parser; use std::fs::{read, read_to_string}; use std::path::Path; #[test] fn affect() { test("affect"); } #[test] fn boucle() { test("boucle"); } #[test] fn expression() { test("expression"); } #[test] fn max() { test("max"); } #[test] fn tri() { test("tri"); } #[test] fn affect_err() { test("affect-err"); } #[test] fn appel() { test("appel"); } #[test] fn associativite() { test("associativite"); } #[test] fn calculette() { test("calculette"); } #[test] fn procedure_arg() { test("procedure_arg"); } #[test] fn procedure() { test("procedure"); } #[test] fn procedure_retour() { test("procedure_retour"); } #[test] fn procedure_varloc() { test("procedure_varloc"); } #[test] fn si() { test("si"); } #[test] fn sinon() { test("sinon"); } #[test] fn tableau2() { test("tableau2"); } #[test] fn tableau() { test("tableau"); } #[test] fn tantque0() { test("tantque0"); } #[test] fn tantque() { test("tantque"); } #[test] fn lexunits() { test("lexunits"); } #[test] fn factorielle() { test("factorielle"); } #[test] fn fibo() { test("fibo"); } #[test] fn pgcd() { test("pgcd"); } #[test] fn sommeneg() { test("sommeneg"); } #[test] fn lex_err() { test("lex-err"); } #[test] fn synt_err() { test("synt-err"); } #[test] fn extra() { test("extra"); } #[test] fn ordre() { test("ordre"); } #[test] fn three_three_a() { test("33a"); } #[test] fn tri_ugly() { test("tri_ugly"); } #[test] fn issue_1() { test("issue_1"); } #[test] fn issue_2() { test("issue_2"); } #[test] fn issue_3() { test("issue_3"); } #[test] fn issue_4() { test("issue_4"); } #[test] fn alone_read_call() { test("alone_read_call"); } fn test(filename: &str) { let l_file = read_to_string(format!("tests/resources/{}.l", filename)).unwrap(); let asynt_file = format!("tests/resources/{}.asynt", filename); let parser = Parser::new().parse(Lexer::new(&l_file)); if Path::new(&asynt_file).is_file() { let asynt_file = read(asynt_file).unwrap(); let mut generated_asynt = Vec::with_capacity(asynt_file.capacity()); parser.unwrap().to_asynt(&mut generated_asynt, 0).unwrap(); print!("{}", String::from_utf8_lossy(&generated_asynt)); assert!(asynt_file == generated_asynt); } else { assert!(parser.is_err()); } }
use crate::frontend::layer_panel::LayerPanelEntry; use crate::message_prelude::*; use crate::Color; use serde::{Deserialize, Serialize}; pub type Callback = Box<dyn Fn(FrontendMessage)>; #[impl_message(Message, Frontend)] #[derive(PartialEq, Clone, Deserialize, Serialize, Debug)] pub enum FrontendMessage { CollapseFolder { path: Vec<LayerId> }, ExpandFolder { path: Vec<LayerId>, children: Vec<LayerPanelEntry> }, SetActiveTool { tool_name: String }, SetActiveDocument { document_index: usize }, UpdateOpenDocumentsList { open_documents: Vec<String> }, DisplayError { description: String }, DisplayConfirmationToCloseDocument { document_index: usize }, DisplayConfirmationToCloseAllDocuments, UpdateCanvas { document: String }, UpdateScrollbars { position: (f64, f64), size: (f64, f64), multiplier: (f64, f64) }, UpdateLayer { path: Vec<LayerId>, data: LayerPanelEntry }, ExportDocument { document: String, name: String }, SaveDocument { document: String, name: String }, OpenDocumentBrowse, EnableTextInput, DisableTextInput, UpdateWorkingColors { primary: Color, secondary: Color }, SetCanvasZoom { new_zoom: f64 }, SetCanvasRotation { new_radians: f64 }, } pub struct FrontendMessageHandler { callback: crate::Callback, } impl FrontendMessageHandler { pub fn new(callback: Callback) -> Self { Self { callback } } } impl MessageHandler<FrontendMessage, ()> for FrontendMessageHandler { fn process_action(&mut self, message: FrontendMessage, _data: (), _responses: &mut VecDeque<Message>) { (self.callback)(message) } advertise_actions!( FrontendMessageDiscriminant; DisplayError, CollapseFolder, ExpandFolder, SetActiveTool, UpdateCanvas, UpdateScrollbars, EnableTextInput, DisableTextInput, SetCanvasZoom, SetCanvasRotation, OpenDocumentBrowse, ); }
fn main() { println!("{}", factorial_iterative(10)); println!("{}", factorial_recursive(10)); println!("{}", factorial_tail_recursive(10)); } // Using iteration fn factorial_iterative(n: int) -> int { let mut acc: int = 1; for i in range(1, n + 1) { acc *= i; } acc } // Using recursion fn factorial_recursive(n: int) -> int { if n == 1 { return 1; } n * factorial_recursive(n - 1) } // Using tail recursion fn factorial_tail_recursive(n: int) -> int { fn factorial_tail_helper(n: int, acc: int) -> int { if n == 1 { return acc; } factorial_tail_helper(n - 1, acc * n) } factorial_tail_helper(n, 1) }
//! GoodReads book schemas and record processing. use chrono::NaiveDate; use serde::Deserialize; use crate::arrow::*; use crate::cleaning::isbns::*; use crate::parsing::*; use crate::prelude::*; const ID_FILE: &'static str = "gr-book-ids.parquet"; const INFO_FILE: &'static str = "gr-book-info.parquet"; const SERIES_FILE: &'static str = "gr-book-series.parquet"; const AUTHOR_FILE: &'static str = "gr-book-authors.parquet"; /// The raw records we read from JSON #[derive(Deserialize)] pub struct RawBook { pub book_id: String, pub work_id: String, pub isbn: String, pub isbn13: String, pub asin: String, #[serde(default)] pub title: String, #[serde(default)] pub authors: Vec<RawAuthor>, #[serde(default)] pub publication_year: String, #[serde(default)] pub publication_month: String, #[serde(default)] pub publication_day: String, #[serde(default)] pub series: Vec<String>, } /// The raw author records from JSON. #[derive(Deserialize)] pub struct RawAuthor { pub author_id: String, #[serde(default)] pub role: String, } /// the book ID records to write to Parquet. #[derive(ArrowField, ArrowSerialize)] pub struct BookIdRecord { pub book_id: i32, pub work_id: Option<i32>, pub isbn10: Option<String>, pub isbn13: Option<String>, pub asin: Option<String>, } /// book info records to actually write #[derive(ArrowField, ArrowSerialize)] pub struct BookRecord { pub book_id: i32, pub title: Option<String>, pub pub_year: Option<u16>, pub pub_month: Option<u8>, pub pub_date: Option<NaiveDate>, } /// book series linking records #[derive(ArrowField, ArrowSerialize)] pub struct BookSeriesRecord { pub book_id: i32, pub series: String, } /// book author linking records #[derive(ArrowField, ArrowSerialize)] pub struct BookAuthorRecord { pub book_id: i32, pub author_id: i32, pub role: Option<String>, } /// Output handler for GoodReads books. pub struct BookWriter { id_out: TableWriter<BookIdRecord>, info_out: TableWriter<BookRecord>, author_out: TableWriter<BookAuthorRecord>, series_out: TableWriter<BookSeriesRecord>, } impl BookWriter { pub fn open() -> Result<BookWriter> { let id_out = TableWriter::open(ID_FILE)?; let info_out = TableWriter::open(INFO_FILE)?; let author_out = TableWriter::open(AUTHOR_FILE)?; let series_out = TableWriter::open(SERIES_FILE)?; Ok(BookWriter { id_out, info_out, author_out, series_out, }) } } impl DataSink for BookWriter { fn output_files<'a>(&'a self) -> Vec<PathBuf> { path_list(&[ID_FILE, INFO_FILE, AUTHOR_FILE, SERIES_FILE]) } } impl ObjectWriter<RawBook> for BookWriter { fn write_object(&mut self, row: RawBook) -> Result<()> { let book_id: i32 = row.book_id.parse()?; self.id_out.write_object(BookIdRecord { book_id, work_id: parse_opt(&row.work_id)?, isbn10: trim_opt(&row.isbn) .map(|s| clean_asin_chars(s)) .filter(|s| s.len() >= 7), isbn13: trim_opt(&row.isbn13) .map(|s| clean_asin_chars(s)) .filter(|s| s.len() >= 7), asin: trim_opt(&row.asin) .map(|s| clean_asin_chars(s)) .filter(|s| s.len() >= 7), })?; let pub_year = parse_opt(&row.publication_year)?; let pub_month = parse_opt(&row.publication_month)?; let pub_day: Option<u32> = parse_opt(&row.publication_day)?; let pub_date = maybe_date(pub_year, pub_month, pub_day); self.info_out.write_object(BookRecord { book_id, title: trim_owned(&row.title), pub_year, pub_month, pub_date, })?; for author in row.authors { self.author_out.write_object(BookAuthorRecord { book_id, author_id: author.author_id.parse()?, role: Some(author.role).filter(|s| !s.is_empty()), })?; } for series in row.series { self.series_out .write_object(BookSeriesRecord { book_id, series })?; } Ok(()) } fn finish(self) -> Result<usize> { self.id_out.finish()?; self.info_out.finish()?; self.author_out.finish()?; self.series_out.finish()?; Ok(0) } }
extern crate proc_macro; use darling::{FromDeriveInput, FromField}; use proc_macro::TokenStream; use proc_macro_error::{abort, proc_macro_error}; use quote::quote; // use proc_macro2::TokenStream as TokenStream2; use syn::{parse_macro_input, spanned::Spanned, DeriveInput, Fields, FieldsNamed, ItemStruct}; macro_rules! ensure { ($input:expr => $enum:ident::$field:pat => $retval:tt) => {{ ensure!($input => $enum::$field => $retval, "invalid syntax") }}; ($input:expr => $enum:ident::$field:pat => $retval:tt, $msg:expr) => {{ use $enum::*; match $input { $field => $retval, v => abort!(v.span(), $msg) } }} } #[derive(Debug, FromDeriveInput)] #[darling(attributes(table))] struct TableOption { #[darling(default)] name: Option<String>, } #[derive(Debug, FromField)] #[darling(attributes(get))] struct GetOption { #[darling(default)] pk: bool, } #[proc_macro_derive(Get, attributes(table, get))] #[proc_macro_error] pub fn get(ast: TokenStream) -> TokenStream { let ast2 = ast.clone(); let st = parse_macro_input!(ast2 as ItemStruct); let struct_ident = st.ident; let fields: FieldsNamed = ensure!(st.fields => Fields::Named(v) => v); let di = parse_macro_input!(ast as DeriveInput); let opt = TableOption::from_derive_input(&di).unwrap(); let table_name = opt .name .unwrap_or(struct_ident.to_string().to_ascii_lowercase()); let field = fields .named .iter() .filter_map(|f| { let attr = GetOption::from_field(f).unwrap(); if attr.pk { Some(f) } else { None } }) .collect::<Vec<_>>(); let pk = match field.len() { 0 => abort!( fields.span(), "`#[get(pk)]` must be specified for the primary key" ), 1 => field[0].clone(), _ => abort!(fields.span(), "`#[get(pk)]` can be used only once"), }; let (pk_ident, pk_ty) = (pk.ident.clone().unwrap(), pk.ty.clone()); let query = format!("SELECT * FROM {} WHERE {} = $1", table_name, pk_ident,); let gen = quote! { impl #struct_ident { pub async fn get(pool: & ::sqlx::PgPool, #pk_ident: #pk_ty) -> Result<Self, ::sqlx::Error> { let data = ::sqlx::query_as!( Self, #query, #pk_ident, ) .fetch_one(pool) .await?; Ok(data) } } }; gen.into() } #[derive(Debug, FromField)] #[darling(attributes(create))] struct CreateOption { #[darling(default)] ignore: bool, } #[proc_macro_derive(Create, attributes(table, create))] #[proc_macro_error] pub fn create(ast: TokenStream) -> TokenStream { let ast2 = ast.clone(); let st = parse_macro_input!(ast2 as ItemStruct); let struct_ident = st.ident; let fields: FieldsNamed = ensure!(st.fields => Fields::Named(v) => v); let di = parse_macro_input!(ast as DeriveInput); let opt = TableOption::from_derive_input(&di).unwrap(); let table_name = opt .name .unwrap_or(struct_ident.to_string().to_ascii_lowercase()); let field_idents = fields .named .iter() .filter_map(|f| { let attr = CreateOption::from_field(f).unwrap(); if !attr.ignore { Some(f.ident.clone().unwrap()) } else { None } }) .collect::<Vec<_>>(); let field_names = field_idents .iter() .map(|f| f.clone().to_string()) .collect::<Vec<_>>(); let fn_args = fields .named .iter() .filter_map(|f| { let attr = CreateOption::from_field(f).unwrap(); if !attr.ignore { let ident = f.ident.clone(); let ty = f.ty.clone(); Some(quote!(#ident: #ty)) } else { None } }) .collect::<Vec<_>>(); let incremental = (1..=field_names.len()) .map(|i| format!("${}", i)) .collect::<Vec<_>>(); let query = format!( "INSERT INTO {} ({}) VALUES ({})", table_name, field_names.join(", "), incremental.join(", ") ); let gen = quote! { impl #struct_ident { pub async fn create(pool: & ::sqlx::PgPool, #(#fn_args),*) -> Result<(), ::sqlx::Error> { ::sqlx::query!( #query, #(#field_idents),* ) .execute(pool) .await?; Ok(()) } } }; gen.into() } #[derive(Debug, FromField)] #[darling(attributes(update))] struct UpdateOption { #[darling(default)] ignore: bool, } #[proc_macro_derive(Update, attributes(table, update, get))] pub fn update(ast: TokenStream) -> TokenStream { let ast2 = ast.clone(); let st = parse_macro_input!(ast2 as ItemStruct); let struct_ident = st.ident; let fields: FieldsNamed = ensure!(st.fields => Fields::Named(v) => v); let di = parse_macro_input!(ast as DeriveInput); let opt = TableOption::from_derive_input(&di).unwrap(); let table_name = opt .name .unwrap_or(struct_ident.to_string().to_ascii_lowercase()); let field = fields .named .iter() .filter_map(|f| { let attr = GetOption::from_field(f).unwrap(); if attr.pk { Some(f) } else { None } }) .collect::<Vec<_>>(); let pk = match field.len() { 0 => abort!( fields.span(), "`#[delete(pk)]` must be specified for the primary key" ), 1 => field[0].clone(), _ => abort!(fields.span(), "`#[delete(pk)]` can be used only once"), }; let (pk_ident, pk_ty) = (pk.ident.clone().unwrap(), pk.ty.clone()); let field_idents = fields .named .iter() .filter_map(|f| { let update_attr = UpdateOption::from_field(f).unwrap(); let get_attr = GetOption::from_field(f).unwrap(); if !update_attr.ignore && !get_attr.pk { Some(f.ident.clone().unwrap()) } else { None } }) .collect::<Vec<_>>(); let field_names = field_idents .iter() .map(|f| f.clone().to_string()) .collect::<Vec<_>>(); let fn_args = fields .named .iter() .filter_map(|f| { let update_attr = UpdateOption::from_field(f).unwrap(); let get_attr = GetOption::from_field(f).unwrap(); if !update_attr.ignore && !get_attr.pk { let ident = f.ident.clone(); let ty = f.ty.clone(); Some(quote!(#ident: #ty)) } else { None } }) .collect::<Vec<_>>(); let col_setter = fields .named .iter() .filter_map(|f| { let update_attr = UpdateOption::from_field(f).unwrap(); let get_attr = GetOption::from_field(f).unwrap(); if !update_attr.ignore && !get_attr.pk { let ident = f.ident.clone().unwrap(); let set_ident = syn::Ident::new(&format!("set_{}", &ident), ident.span()); let ty = f.ty.clone(); let query = format!("UPDATE {} SET {} = $1 WHERE {} = $2", &table_name, &pk_ident, &ident); Some(quote!( pub async fn #set_ident(pool: & ::sqlx::PgPool, #pk_ident: #pk_ty, #ident: #ty) -> Result<(), ::sqlx::Error> { ::sqlx::query!(#query, #pk_ident, #ident) .execute(pool) .await?; Ok(()) } )) } else { None } }) .collect::<Vec<_>>(); let incremental = (2..=field_names.len() + 1) .map(|i| format!("${}", i)) .collect::<Vec<_>>(); let query = format!( "UPDATE {} SET {} WHERE {} = $1", table_name, field_names .iter() .zip(incremental.iter()) .map(|(f, i)| format!("{} = {}", f, i)) .collect::<Vec<_>>() .join(","), &pk_ident ); let gen = quote! { impl #struct_ident { pub async fn update(pool: & ::sqlx::PgPool, #pk_ident: #pk_ty, #(#fn_args),*) -> Result<(), ::sqlx::Error> { ::sqlx::query!( #query, #pk_ident, #(#field_idents),* ) .execute(pool) .await?; Ok(()) } #(#col_setter)* } }; gen.into() } #[proc_macro_derive(Delete, attributes(table, get))] #[proc_macro_error] pub fn delete(ast: TokenStream) -> TokenStream { let ast2 = ast.clone(); let st = parse_macro_input!(ast2 as ItemStruct); let struct_ident = st.ident; let fields: FieldsNamed = ensure!(st.fields => Fields::Named(v) => v); let di = parse_macro_input!(ast as DeriveInput); let opt = TableOption::from_derive_input(&di).unwrap(); let table_name = opt .name .unwrap_or(struct_ident.to_string().to_ascii_lowercase()); let field = fields .named .iter() .filter_map(|f| { let attr = GetOption::from_field(f).unwrap(); if attr.pk { Some(f) } else { None } }) .collect::<Vec<_>>(); let pk = match field.len() { 0 => abort!( fields.span(), "`#[delete(pk)]` must be specified for the primary key" ), 1 => field[0].clone(), _ => abort!(fields.span(), "`#[delete(pk)]` can be used only once"), }; let (pk_ident, pk_ty) = (pk.ident.clone().unwrap(), pk.ty.clone()); let query = format!("DELETE FROM {} WHERE {} = $1", table_name, pk_ident,); let gen = quote! { impl #struct_ident { pub async fn delete(pool: & ::sqlx::PgPool, #pk_ident: #pk_ty) -> Result<(), ::sqlx::Error> { ::sqlx::query!( #query, #pk_ident, ) .execute(pool) .await?; Ok(()) } } }; gen.into() }
use colored::Colorize; use futures::stream::StreamExt; use serde::{Deserialize, Serialize}; use structopt::StructOpt; use persist_core::error::Error; use persist_core::protocol::{LogStreamSource, LogsRequest, LogsResponse}; use crate::daemon; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, StructOpt)] pub struct Opts { /// The names of the processes to get logs for #[structopt(name = "process-name")] pub processes: Vec<String>, /// Get logs from all the processes #[structopt(long)] pub all: bool, /// The number of previous log lines to initially output #[structopt(long, short = "n", default_value = "10")] pub lines: usize, /// Disable log streaming #[structopt(long = "no-stream")] pub no_stream: bool, } pub async fn handle(opts: Opts) -> Result<(), Error> { let filters = match (opts.all, opts.processes) { (false, processes) if processes.is_empty() => { return Err(Error::from(String::from( "you must specify at least one process name or --all", ))); } (false, processes) => Some(processes), (true, _) => None, }; let request = LogsRequest { filters, stream: !opts.no_stream, lines: opts.lines, source_filter: None, }; let mut daemon = daemon::connect().await?; let mut logs = daemon.logs(request).await?; while let Some(response) = logs.next().await.transpose()? { let entry = match response { LogsResponse::Entry(entry) => entry, LogsResponse::Unsubscribed => break, LogsResponse::Subscribed => { // TODO(error): received `Subscribed` twice ?? unreachable!() } }; let source = match entry.source { LogStreamSource::Stdout => "(out)", LogStreamSource::Stderr => "(err)", }; println!( " {} {} {} {}", entry.name.bright_blue().bold(), source.bold(), "|".bold(), entry.msg, ); } Ok(()) }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use base::prelude::*; use io::{Read}; use core::{mem, cmp}; use base::{error}; use super::{Zone}; macro_rules! rd { ($ip:expr, $t:ty) => { if $ip.len() < mem::size_of::<$t>() { Err(error::InvalidSequence) } else { let mut v: $t = 0; let _ = $ip.read(v.as_mut()); Ok(v.from_be()) } } } fn read_u8(ip: &mut &[u8]) -> Result<u8> { rd!(ip, u8) } fn read_i32(ip: &mut &[u8]) -> Result<i32> { rd!(ip, i32) } fn read_i64(ip: &mut &[u8]) -> Result<i64> { rd!(ip, i64) } trait TReader { fn read_seconds(ip: &mut &[u8]) -> Result<i64>; fn seconds_width() -> usize; } struct T32Reader; impl TReader for T32Reader { fn read_seconds(ip: &mut &[u8]) -> Result<i64> { read_i32(ip).map(|v| v as i64) } fn seconds_width() -> usize { 4 } } struct T64Reader; impl TReader for T64Reader { fn read_seconds(ip: &mut &[u8]) -> Result<i64> { read_i64(ip) } fn seconds_width() -> usize { 8 } } pub fn parse(ip: &mut &[u8]) -> Result<Zone> { if ip.len() < 5 { return Err(error::InvalidSequence); } if &ip[..4] != "TZif" { return Err(error::InvalidSequence); } let version = match ip[4] { 0 => 1, _ => 2, }; if version > 1 { try!(discard::<T32Reader>(ip)); parse_::<T64Reader>(ip) } else { parse_::<T32Reader>(ip) } } fn consume(buf: &mut &[u8], n: usize) { let min = cmp::min(buf.len(), n); *buf = &buf[min..]; } fn parse_<T: TReader>(ip: &mut &[u8]) -> Result<Zone> { consume(ip, 20); let is_utc_indicators = try!(read_i32(ip)) as usize; let is_std_indicators = try!(read_i32(ip)) as usize; let num_leap_seconds = try!(read_i32(ip)) as usize; let num_transitions = try!(read_i32(ip)) as usize; let num_states = try!(read_i32(ip)) as usize; let abbr_bytes = try!(read_i32(ip)) as usize; if num_states == 0 { return Err(error::InvalidSequence); } let mut transitions = vec!(); let mut states = vec!(); let mut leap_seconds = vec!(); for _ in 0..num_transitions { transitions.push((try!(T::read_seconds(ip)), 0)); } for i in 0..num_transitions { let state = try!(read_u8(ip)) as usize; if state >= num_states { return Err(error::InvalidSequence); } transitions[i].1 = state; } for _ in 0..num_states { states.push((try!(read_i32(ip)) as i64, try!(read_u8(ip)) != 0)); consume(ip, 1); } consume(ip, abbr_bytes); for _ in 0..num_leap_seconds { leap_seconds.push((try!(T::read_seconds(ip)), try!(read_i32(ip)) as i64)); } consume(ip, is_std_indicators); consume(ip, is_utc_indicators); Ok(Zone { transitions: transitions, states: states, leap_seconds: leap_seconds, }) } fn discard<T: TReader>(ip: &mut &[u8]) -> Result { consume(ip, 20); let is_utc_indicators = try!(read_i32(ip)) as usize; let is_std_indicators = try!(read_i32(ip)) as usize; let num_leap_seconds = try!(read_i32(ip)) as usize; let num_transitions = try!(read_i32(ip)) as usize; let num_states = try!(read_i32(ip)) as usize; let abbr_bytes = try!(read_i32(ip)) as usize; let bytes = num_transitions * T::seconds_width() + num_transitions * 1 + num_states * (4 + 1 + 1) + abbr_bytes * 1 + num_leap_seconds * (T::seconds_width() + 4) + is_utc_indicators * 1 + is_std_indicators * 1; consume(ip, bytes); Ok(()) }
use serde::Deserialize; #[derive(Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct Statistics { pub uuid: String, pub player_count: u64, pub mem_mb: u64, pub mc_version: f64, pub os: String, pub java_version: u32, pub timezone: String }
use std::any::TypeId; use std::cell::RefCell; use std::collections::HashMap; use std::hash::{BuildHasherDefault, Hasher}; use std::ptr::NonNull; use std::sync::Arc; use crate::coroutine_impl::Coroutine; use crate::join::Join; use generator::get_local_data; // thread local map storage thread_local! {static LOCALMAP: LocalMap = RefCell::new(HashMap::default());} /// coroutine local storage pub struct CoroutineLocal { // current coroutine handle co: Coroutine, // when panic happens, we need to trigger the join here join: Arc<Join>, // real local data hash map local_data: LocalMap, } impl CoroutineLocal { /// create coroutine local storage pub fn new(co: Coroutine, join: Arc<Join>) -> Box<Self> { Box::new(CoroutineLocal { co, join, local_data: RefCell::new(HashMap::default()), }) } // get the coroutine handle pub fn get_co(&self) -> &Coroutine { &self.co } // get the join handle pub fn get_join(&self) -> Arc<Join> { self.join.clone() } } #[inline] pub fn get_co_local_data() -> Option<NonNull<CoroutineLocal>> { let ptr = get_local_data(); #[allow(clippy::cast_ptr_alignment)] NonNull::new(ptr as *mut CoroutineLocal) } #[inline] fn with<F: FnOnce(&LocalMap) -> R, R>(f: F) -> R { match get_co_local_data() { Some(v) => f(&(unsafe { v.as_ref() }.local_data)), None => LOCALMAP.with(|data| f(data)), } } pub type LocalMap = RefCell<HashMap<TypeId, Box<dyn Opaque>, BuildHasherDefault<IdHasher>>>; pub trait Opaque {} impl<T> Opaque for T {} /// A key for local data stored in a coroutine. /// /// This type is generated by the `coroutine_local!` macro and performs very /// similarly to the `thread_local!` macro and `std::thread::LocalKey` types. /// Data associated with a `LocalKey<T>` is stored inside of a coroutine, /// and the data is destroyed when the coroutine is completed. /// /// coroutine-local data requires the `'static` bound to ensure it lives long /// enough. When a key is accessed for the first time the coroutine's data is /// initialized with the provided initialization expression to the macro. pub struct LocalKey<T> { // "private" fields which have to be public to get around macro hygiene, not // included in the stability story for this type. Can change at any time. #[doc(hidden)] pub __key: fn() -> TypeId, #[doc(hidden)] pub __init: fn() -> T, } #[derive(Default)] pub struct IdHasher { id: u64, } impl Hasher for IdHasher { fn write(&mut self, _bytes: &[u8]) { // TODO: need to do something sensible panic!("can only hash u64"); } fn write_u64(&mut self, u: u64) { self.id = u; } fn finish(&self) -> u64 { self.id } } impl<T: 'static> LocalKey<T> { /// Access this coroutine-local key, running the provided closure with a /// reference to the value. /// /// This function will access this coroutine-local key to retrieve the data /// associated with the current coroutine and this key. If this is the first /// time this key has been accessed on this coroutine, then the key will be /// initialized with the initialization expression provided at the time the /// `coroutine_local!` macro was called. /// /// The provided closure will be provided a shared reference to the /// underlying data associated with this coroutine-local-key. The data itself /// is stored inside of the current coroutine. /// /// if it's not accessed in a coroutine context, it will use the thread local /// storage as a backend, so it's safe to use it in thread context /// /// # Panics /// /// This function can possibly panic for a number of reasons: /// /// * If the initialization expression is run and it panics /// * If the closure provided panics #[inline] pub fn with<F, R>(&'static self, f: F) -> R where F: FnOnce(&T) -> R, { let key = (self.__key)(); with(|data| { let raw_pointer = { let mut data = data.borrow_mut(); let entry = data.entry(key).or_insert_with(|| Box::new((self.__init)())); &**entry as *const dyn Opaque as *const T }; unsafe { f(&*raw_pointer) } }) } }
use std::collections::HashMap; pub trait SimpleDB { fn set(&mut self, key: String, value: u32); fn get(&mut self, key: String) -> Option<&u32>; fn unset(&mut self, key: String); fn begin_transaction(&mut self); fn rollback(&mut self) -> Result<(), String>; fn commit(&mut self) -> Result<(), String>; } pub struct InMemoryDB { db: Vec<HashMap<String, u32>>, } impl InMemoryDB { pub fn new() -> Self { InMemoryDB { db: vec![HashMap::new()], } } } impl SimpleDB for InMemoryDB { fn set(&mut self, key: String, value: u32) { if let Some(last) = self.db.last_mut() { last.insert(key, value); } } fn get(&mut self, key: String) -> Option<&u32> { if let Some(last) = self.db.last() { return last.get(&key); } else { None } } fn unset(&mut self, key: String) { let last = self.db.last_mut().unwrap(); last.remove(&key); } fn begin_transaction(&mut self) { let new_db = self.db.last().unwrap().clone(); self.db.push(new_db); } fn rollback(&mut self) -> Result<(), String> { match self.db.pop() { Some(_last) => { if self.db.len() == 0 { return Err(String::from("No transactions in progress")) } Ok(()) }, None => Err(String::from("No transactions in progress")) } } fn commit(&mut self) -> Result<(), String> { match self.db.pop() { Some(last) => { if self.db.len() == 0 { return Err(String::from("No transactions in progress")) } self.db = vec![last]; Ok(()) }, None => Err(String::from("No transactions in progress")) } } }
#[macro_use] extern crate log; mod sshagent; mod rustica; use clap::{App, Arg}; use sshagent::{Agent, error::Error as AgentError, Identity, SSHAgentHandler, Response}; use std::env; use std::os::unix::net::{UnixListener}; use std::process; use rustica::{cert, RusticaServer, Signatory}; use rustica_keys::ssh::{Certificate, CertType, CurveKind, PublicKeyKind, PrivateKey, PrivateKeyKind}; use rustica_keys::utils::signature_convert_asn1_ecdsa_to_ssh; use rustica_keys::yubikey::{ provision, ssh::{ convert_to_ssh_pubkey, ssh_cert_signer, ssh_cert_fetch_pubkey, } }; use serde_derive::Deserialize; use std::convert::TryFrom; use std::fs::{self, File}; use std::io::{Read}; use std::time::SystemTime; use yubikey_piv::key::{AlgorithmId, SlotId}; use yubikey_piv::policy::TouchPolicy; #[derive(Debug, Deserialize)] struct Options { principals: Option<Vec<String>>, hosts: Option<Vec<String>>, kind: Option<String>, duration: Option<u64>, } #[derive(Debug, Deserialize)] struct Config { server: Option<String>, server_pem: Option<String>, slot: Option<String>, options: Option<Options>, } #[derive(Debug)] struct Handler { server: RusticaServer, cert: Option<Identity>, signatory: Signatory, stale_at: u64, certificate_options: rustica::CertificateConfig, } impl From<Option<Options>> for rustica::CertificateConfig { fn from(co: Option<Options>) -> rustica::CertificateConfig { match co { None => { rustica::CertificateConfig { cert_type: CertType::User, duration: 10, hosts: vec![], principals: vec![], } }, Some(co) => { rustica::CertificateConfig { cert_type: CertType::try_from(co.kind.unwrap_or_else(|| String::from("user")).as_str()).unwrap_or(CertType::User), duration: co.duration.unwrap_or(10), hosts: co.hosts.unwrap_or_default(), principals: co.principals.unwrap_or_default(), } } } } } impl SSHAgentHandler for Handler { fn identities(&mut self) -> Result<Response, AgentError> { let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs(); if let Some(cert) = &self.cert { if timestamp < self.stale_at { debug!("Certificate has not expired, not refreshing"); return Ok(Response::Identities(vec![cert.clone()])); } } match cert::get_custom_certificate(&self.server, &self.signatory, &self.certificate_options) { Ok(response) => { info!("{:#}", Certificate::from_string(&response.cert).unwrap()); let cert: Vec<&str> = response.cert.split(' ').collect(); let raw_cert = base64::decode(cert[1]).unwrap_or_default(); let ident = Identity { key_blob: raw_cert, key_comment: response.comment, }; self.cert = Some(ident.clone()); Ok(Response::Identities(vec![ident])) }, Err(e) => { error!("Refresh certificate error: {:?}", e); Err(AgentError::from("Could not refresh certificate")) }, } } /// Pubkey is currently unused because the idea is to only ever have a single cert which itself is only /// active for a very small window of time fn sign_request(&mut self, _pubkey: Vec<u8>, data: Vec<u8>, _flags: u32) -> Result<Response, AgentError> { match &self.signatory { Signatory::Yubikey(slot) => { let signature = ssh_cert_signer(&data, *slot).unwrap(); let signature = (&signature[27..]).to_vec(); let pubkey = ssh_cert_fetch_pubkey(*slot).unwrap(); Ok(Response::SignResponse { algo_name: String::from(pubkey.key_type.name), signature, }) }, Signatory::Direct(privkey) => { let rng = ring::rand::SystemRandom::new(); match &privkey.kind { PrivateKeyKind::Rsa(_) => Err(AgentError::from("unimplemented")), PrivateKeyKind::Ecdsa(key) => { let (alg, name) = match key.curve.kind { CurveKind::Nistp256 => (&ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING, "ecdsa-sha2-nistp256"), CurveKind::Nistp384 => (&ring::signature::ECDSA_P384_SHA384_ASN1_SIGNING, "ecdsa-sha2-nistp384"), CurveKind::Nistp521 => return Err(AgentError::from("unimplemented")), }; let pubkey = match &privkey.pubkey.kind { PublicKeyKind::Ecdsa(key) => &key.key, _ => return Err(AgentError::from("unimplemented")), }; let key = if key.key[0] == 0x0_u8 {&key.key[1..]} else {&key.key}; let key_pair = ring::signature::EcdsaKeyPair::from_private_key_and_public_key(alg, &key, &pubkey).unwrap(); let signature = signature_convert_asn1_ecdsa_to_ssh(key_pair.sign(&rng, &data).unwrap().as_ref()).unwrap(); let signature = (&signature[4..]).to_vec(); Ok(Response::SignResponse { algo_name: name.to_string(), signature, }) }, PrivateKeyKind::Ed25519(_) => Err(AgentError::from("unimplemented")), } } } } } fn provision_new_key(slot: SlotId, pin: &str, subj: &str, mgm_key: &[u8], alg: &str, secure: bool) { let alg = match alg { "eccp256" => AlgorithmId::EccP256, _ => AlgorithmId::EccP384, }; println!("Provisioning new {:?} key in slot: {:?}", alg, slot); let policy = if secure { println!("You're creating a secure key that will require touch to use."); TouchPolicy::Cached } else { TouchPolicy::Never }; match provision(pin.as_bytes(), mgm_key, slot, subj, alg, policy) { Ok(pk) => { convert_to_ssh_pubkey(&pk).unwrap(); }, Err(_) => panic!("Could not provision device with new key"), } } fn slot_parser(slot: &str) -> Option<SlotId> { // If first character is R, then we need to parse the nice // notation if (slot.len() == 2 || slot.len() == 3) && slot.starts_with('R') { let slot_value = slot[1..].parse::<u8>(); match slot_value { Ok(v) if v <= 20 => Some(SlotId::try_from(0x81_u8 + v).unwrap()), _ => None, } } else if let Ok(s) = SlotId::try_from(slot.to_owned()) { Some(s) } else { None } } fn slot_validator(slot: &str) -> Result<(), String> { match slot_parser(slot) { Some(_) => Ok(()), None => Err(String::from("Provided slot was not valid. Should be R1 - R20 or a raw hex identifier")), } } fn main() -> Result<(), Box<dyn std::error::Error>> { env_logger::init(); let matches = App::new("rustica-agent") .version(env!("CARGO_PKG_VERSION")) .author("Mitchell Grenier <mitchell@confurious.io>") .about("The SSH Agent component of Rustica") .arg( Arg::new("server") .about("Full address of Rustica server to use as CA") .long("server") .short('r') .takes_value(true), ) .arg( Arg::new("serverpem") .about("Path to PEM that contains server public key") .long("serverpem") .short('c') .takes_value(true), ) .arg( Arg::new("slot") .about("Numerical value for the slot on the yubikey to use for your private key") .long("slot") .short('s') .validator(slot_validator) .takes_value(true), ) .arg( Arg::new("file") .about("Used instead of a slot to provide a private key via file") .long("file") .short('f') .takes_value(true), ) .arg( Arg::new("kind") .about("The type of certificate you want to request") .long("kind") .short('k') .possible_value("user") .possible_value("host") .takes_value(true), ) .arg( Arg::new("duration") .about("Your request for certificate duration in seconds") .long("duration") .short('d') .takes_value(true), ) .arg( Arg::new("principals") .about("A comma separated list of values you are requesting as principals") .short('n') .takes_value(true), ) .arg( Arg::new("hosts") .about("A comma separated list of hostnames you are requesting a certificate for") .short('h') .takes_value(true), ) .arg( Arg::new("immediate") .about("Immiediately request a certificate. Useful for testing.") .short('i') ) .subcommand( App::new("provision") .about("Provision this slot with a new private key. The pin number must be passed as parameter here") .arg( Arg::new("management-key") .about("Specify the management key") .default_value("010203040506070801020304050607080102030405060708") .long("mgmkey") .short('m') .required(true) .takes_value(true), ) .arg( Arg::new("pin") .about("Specify the pin") .default_value("123456") .long("pin") .short('p') .required(true) .takes_value(true), ) .arg( Arg::new("type") .about("Specify the type of key you want to provision") .default_value("eccp256") .long("type") .short('t') .possible_value("eccp256") .possible_value("eccp384") .takes_value(true), ) .arg( Arg::new("require-touch") .about("Newly provisioned key requires touch for signing operations (touch cached for 15 seconds)") .long("require-touch") .short('r') ) .arg( Arg::new("subject") .about("Subject of the new cert you're creating (this is only used as a note)") .default_value("Rustica-AgentQuickProvision") .long("subj") .short('j') ) ) .get_matches(); // First we read the configuration file and use those unless overriden by // the commandline let config = fs::read_to_string("/etc/rustica/config.toml"); let config = match config { Ok(content) => toml::from_str(&content)?, Err(_) => { Config { server: None, server_pem: None, slot: None, options: None, } } }; let mut certificate_options = rustica::CertificateConfig::from(config.options); let address = match (matches.value_of("server"), &config.server) { (Some(server), _) => server.to_owned(), (_, Some(server)) => server.to_owned(), (None, None) => { error!("A server must be specified either in the config file or on the commandline"); return Ok(()); } }; let ca = if address.starts_with("https") { match (matches.value_of("serverpem"), &config.server_pem) { (Some(v), _) => { let mut contents = String::new(); File::open(v)?.read_to_string(&mut contents)?; contents }, (_, Some(v)) => v.to_owned(), (None, None) => { error!("You requested an HTTPS server address but no server pem for identification."); return Ok(()); } } } else { String::new() }; let server = RusticaServer { address, ca, }; let cmd_slot = match matches.value_of("slot") { Some(x) => Some(x.to_owned()), None => None, }; let signatory = match (&cmd_slot, &config.slot, matches.value_of("file")) { (_, _, Some(file)) => Signatory::Direct(PrivateKey::from_path(file)?), (Some(slot), _, _) | (_, Some(slot), _) => { match slot_parser(slot) { Some(s) => Signatory::Yubikey(s), None => { error!("Chosen slot was invalid. Slot should be of the the form of: R# where # is between 1 and 20 inclusive"); return Ok(()); } } }, (None, None, None) => { error!("A slot or file must be specified to use as identification"); return Ok(()); } }; let pubkey = match signatory { Signatory::Yubikey(slot) => match ssh_cert_fetch_pubkey(slot) { Some(cert) => cert, None => { println!("There was no keypair found in slot {:?}. Provision one or use another slot.", slot); return Ok(()) } }, Signatory::Direct(ref privkey) => privkey.pubkey.clone() }; if let Some(ref matches) = matches.subcommand_matches("provision") { let slot = match signatory { Signatory::Yubikey(slot) => slot, Signatory::Direct(_) => { println!("Cannot provision a file, requires a Yubikey slot"); return Ok(()); } }; let secure = matches.is_present("require-touch"); let subj = matches.value_of("subject").unwrap(); let mgm_key = match matches.value_of("management-key") { Some(mgm) => hex::decode(mgm).unwrap(), None => { println!("Management key error"); return Ok(()); } }; let pin = matches.value_of("pin").unwrap_or("123456"); provision_new_key(slot, pin, &subj, &mgm_key, matches.value_of("type").unwrap_or("eccp384"), secure); return Ok(()); } let mut cert = None; let mut stale_at = 0; if let Some(principals) = matches.value_of("principals") { certificate_options.principals = principals.split(',').map(|s| s.to_string()).collect(); } if let Some(hosts) = matches.value_of("hosts") { certificate_options.hosts = hosts.split(',').map(|s| s.to_string()).collect(); } if let Some(kind) = matches.value_of("kind") { certificate_options.cert_type = CertType::try_from(kind).unwrap_or(CertType::User); } if let Some(duration) = matches.value_of("duration") { certificate_options.duration = duration.parse::<u64>().unwrap_or(10); } if matches.is_present("immediate") { cert = match cert::get_custom_certificate(&server, &signatory, &certificate_options) { Ok(x) => { let cert = rustica_keys::Certificate::from_string(&x.cert).unwrap(); println!("Issued Certificate Details:"); println!("{:#}\n", &cert); stale_at = cert.valid_before; debug!("Raw Certificate: "); debug!("{}", &cert); let cert: Vec<&str> = x.cert.split(' ').collect(); let raw_cert = base64::decode(cert[1]).unwrap_or_default(); Some(Identity { key_blob: raw_cert, key_comment: x.comment, }) } Err(e) => { error!("Error: {:?}", e); return Ok(()); }, }; } println!("Starting Rustica Agent"); println!("Access Fingerprint: {}", pubkey.fingerprint().hash); let mut socket_path = env::temp_dir(); socket_path.push(format!("rustica.{}", process::id())); println!("SSH_AUTH_SOCK={}; export SSH_AUTH_SOCK;", socket_path.to_string_lossy()); let handler = Handler { server, cert, signatory, stale_at, certificate_options, }; let socket = UnixListener::bind(socket_path).unwrap(); Agent::run(handler, socket); Ok(()) }
#[doc = "Register `EMR` reader"] pub type R = crate::R<EMR_SPEC>; #[doc = "Register `EMR` writer"] pub type W = crate::W<EMR_SPEC>; #[doc = "Field `MR0` reader - Event Mask on line 0"] pub type MR0_R = crate::BitReader<MR0_A>; #[doc = "Event Mask on line 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MR0_A { #[doc = "0: Interrupt request line is masked"] Masked = 0, #[doc = "1: Interrupt request line is unmasked"] Unmasked = 1, } impl From<MR0_A> for bool { #[inline(always)] fn from(variant: MR0_A) -> Self { variant as u8 != 0 } } impl MR0_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MR0_A { match self.bits { false => MR0_A::Masked, true => MR0_A::Unmasked, } } #[doc = "Interrupt request line is masked"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == MR0_A::Masked } #[doc = "Interrupt request line is unmasked"] #[inline(always)] pub fn is_unmasked(&self) -> bool { *self == MR0_A::Unmasked } } #[doc = "Field `MR0` writer - Event Mask on line 0"] pub type MR0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MR0_A>; impl<'a, REG, const O: u8> MR0_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Interrupt request line is masked"] #[inline(always)] pub fn masked(self) -> &'a mut crate::W<REG> { self.variant(MR0_A::Masked) } #[doc = "Interrupt request line is unmasked"] #[inline(always)] pub fn unmasked(self) -> &'a mut crate::W<REG> { self.variant(MR0_A::Unmasked) } } #[doc = "Field `MR1` reader - Event Mask on line 1"] pub use MR0_R as MR1_R; #[doc = "Field `MR2` reader - Event Mask on line 2"] pub use MR0_R as MR2_R; #[doc = "Field `MR3` reader - Event Mask on line 3"] pub use MR0_R as MR3_R; #[doc = "Field `MR4` reader - Event Mask on line 4"] pub use MR0_R as MR4_R; #[doc = "Field `MR5` reader - Event Mask on line 5"] pub use MR0_R as MR5_R; #[doc = "Field `MR6` reader - Event Mask on line 6"] pub use MR0_R as MR6_R; #[doc = "Field `MR7` reader - Event Mask on line 7"] pub use MR0_R as MR7_R; #[doc = "Field `MR8` reader - Event Mask on line 8"] pub use MR0_R as MR8_R; #[doc = "Field `MR9` reader - Event Mask on line 9"] pub use MR0_R as MR9_R; #[doc = "Field `MR10` reader - Event Mask on line 10"] pub use MR0_R as MR10_R; #[doc = "Field `MR11` reader - Event Mask on line 11"] pub use MR0_R as MR11_R; #[doc = "Field `MR12` reader - Event Mask on line 12"] pub use MR0_R as MR12_R; #[doc = "Field `MR13` reader - Event Mask on line 13"] pub use MR0_R as MR13_R; #[doc = "Field `MR14` reader - Event Mask on line 14"] pub use MR0_R as MR14_R; #[doc = "Field `MR15` reader - Event Mask on line 15"] pub use MR0_R as MR15_R; #[doc = "Field `MR16` reader - Event Mask on line 16"] pub use MR0_R as MR16_R; #[doc = "Field `MR17` reader - Event Mask on line 17"] pub use MR0_R as MR17_R; #[doc = "Field `MR18` reader - Event Mask on line 18"] pub use MR0_R as MR18_R; #[doc = "Field `MR19` reader - Event Mask on line 19"] pub use MR0_R as MR19_R; #[doc = "Field `MR20` reader - Event Mask on line 20"] pub use MR0_R as MR20_R; #[doc = "Field `MR21` reader - Event Mask on line 21"] pub use MR0_R as MR21_R; #[doc = "Field `MR22` reader - Event Mask on line 22"] pub use MR0_R as MR22_R; #[doc = "Field `MR23` reader - Event Mask on line 23"] pub use MR0_R as MR23_R; #[doc = "Field `MR24` reader - Event Mask on line 24"] pub use MR0_R as MR24_R; #[doc = "Field `MR25` reader - Event Mask on line 25"] pub use MR0_R as MR25_R; #[doc = "Field `MR26` reader - Event Mask on line 26"] pub use MR0_R as MR26_R; #[doc = "Field `MR27` reader - Event Mask on line 27"] pub use MR0_R as MR27_R; #[doc = "Field `MR28` reader - Event Mask on line 28"] pub use MR0_R as MR28_R; #[doc = "Field `MR1` writer - Event Mask on line 1"] pub use MR0_W as MR1_W; #[doc = "Field `MR2` writer - Event Mask on line 2"] pub use MR0_W as MR2_W; #[doc = "Field `MR3` writer - Event Mask on line 3"] pub use MR0_W as MR3_W; #[doc = "Field `MR4` writer - Event Mask on line 4"] pub use MR0_W as MR4_W; #[doc = "Field `MR5` writer - Event Mask on line 5"] pub use MR0_W as MR5_W; #[doc = "Field `MR6` writer - Event Mask on line 6"] pub use MR0_W as MR6_W; #[doc = "Field `MR7` writer - Event Mask on line 7"] pub use MR0_W as MR7_W; #[doc = "Field `MR8` writer - Event Mask on line 8"] pub use MR0_W as MR8_W; #[doc = "Field `MR9` writer - Event Mask on line 9"] pub use MR0_W as MR9_W; #[doc = "Field `MR10` writer - Event Mask on line 10"] pub use MR0_W as MR10_W; #[doc = "Field `MR11` writer - Event Mask on line 11"] pub use MR0_W as MR11_W; #[doc = "Field `MR12` writer - Event Mask on line 12"] pub use MR0_W as MR12_W; #[doc = "Field `MR13` writer - Event Mask on line 13"] pub use MR0_W as MR13_W; #[doc = "Field `MR14` writer - Event Mask on line 14"] pub use MR0_W as MR14_W; #[doc = "Field `MR15` writer - Event Mask on line 15"] pub use MR0_W as MR15_W; #[doc = "Field `MR16` writer - Event Mask on line 16"] pub use MR0_W as MR16_W; #[doc = "Field `MR17` writer - Event Mask on line 17"] pub use MR0_W as MR17_W; #[doc = "Field `MR18` writer - Event Mask on line 18"] pub use MR0_W as MR18_W; #[doc = "Field `MR19` writer - Event Mask on line 19"] pub use MR0_W as MR19_W; #[doc = "Field `MR20` writer - Event Mask on line 20"] pub use MR0_W as MR20_W; #[doc = "Field `MR21` writer - Event Mask on line 21"] pub use MR0_W as MR21_W; #[doc = "Field `MR22` writer - Event Mask on line 22"] pub use MR0_W as MR22_W; #[doc = "Field `MR23` writer - Event Mask on line 23"] pub use MR0_W as MR23_W; #[doc = "Field `MR24` writer - Event Mask on line 24"] pub use MR0_W as MR24_W; #[doc = "Field `MR25` writer - Event Mask on line 25"] pub use MR0_W as MR25_W; #[doc = "Field `MR26` writer - Event Mask on line 26"] pub use MR0_W as MR26_W; #[doc = "Field `MR27` writer - Event Mask on line 27"] pub use MR0_W as MR27_W; #[doc = "Field `MR28` writer - Event Mask on line 28"] pub use MR0_W as MR28_W; impl R { #[doc = "Bit 0 - Event Mask on line 0"] #[inline(always)] pub fn mr0(&self) -> MR0_R { MR0_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Event Mask on line 1"] #[inline(always)] pub fn mr1(&self) -> MR1_R { MR1_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Event Mask on line 2"] #[inline(always)] pub fn mr2(&self) -> MR2_R { MR2_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Event Mask on line 3"] #[inline(always)] pub fn mr3(&self) -> MR3_R { MR3_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Event Mask on line 4"] #[inline(always)] pub fn mr4(&self) -> MR4_R { MR4_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Event Mask on line 5"] #[inline(always)] pub fn mr5(&self) -> MR5_R { MR5_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Event Mask on line 6"] #[inline(always)] pub fn mr6(&self) -> MR6_R { MR6_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Event Mask on line 7"] #[inline(always)] pub fn mr7(&self) -> MR7_R { MR7_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Event Mask on line 8"] #[inline(always)] pub fn mr8(&self) -> MR8_R { MR8_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Event Mask on line 9"] #[inline(always)] pub fn mr9(&self) -> MR9_R { MR9_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Event Mask on line 10"] #[inline(always)] pub fn mr10(&self) -> MR10_R { MR10_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Event Mask on line 11"] #[inline(always)] pub fn mr11(&self) -> MR11_R { MR11_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Event Mask on line 12"] #[inline(always)] pub fn mr12(&self) -> MR12_R { MR12_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - Event Mask on line 13"] #[inline(always)] pub fn mr13(&self) -> MR13_R { MR13_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - Event Mask on line 14"] #[inline(always)] pub fn mr14(&self) -> MR14_R { MR14_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - Event Mask on line 15"] #[inline(always)] pub fn mr15(&self) -> MR15_R { MR15_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - Event Mask on line 16"] #[inline(always)] pub fn mr16(&self) -> MR16_R { MR16_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Event Mask on line 17"] #[inline(always)] pub fn mr17(&self) -> MR17_R { MR17_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - Event Mask on line 18"] #[inline(always)] pub fn mr18(&self) -> MR18_R { MR18_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - Event Mask on line 19"] #[inline(always)] pub fn mr19(&self) -> MR19_R { MR19_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - Event Mask on line 20"] #[inline(always)] pub fn mr20(&self) -> MR20_R { MR20_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - Event Mask on line 21"] #[inline(always)] pub fn mr21(&self) -> MR21_R { MR21_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - Event Mask on line 22"] #[inline(always)] pub fn mr22(&self) -> MR22_R { MR22_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - Event Mask on line 23"] #[inline(always)] pub fn mr23(&self) -> MR23_R { MR23_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - Event Mask on line 24"] #[inline(always)] pub fn mr24(&self) -> MR24_R { MR24_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - Event Mask on line 25"] #[inline(always)] pub fn mr25(&self) -> MR25_R { MR25_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - Event Mask on line 26"] #[inline(always)] pub fn mr26(&self) -> MR26_R { MR26_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - Event Mask on line 27"] #[inline(always)] pub fn mr27(&self) -> MR27_R { MR27_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - Event Mask on line 28"] #[inline(always)] pub fn mr28(&self) -> MR28_R { MR28_R::new(((self.bits >> 28) & 1) != 0) } } impl W { #[doc = "Bit 0 - Event Mask on line 0"] #[inline(always)] #[must_use] pub fn mr0(&mut self) -> MR0_W<EMR_SPEC, 0> { MR0_W::new(self) } #[doc = "Bit 1 - Event Mask on line 1"] #[inline(always)] #[must_use] pub fn mr1(&mut self) -> MR1_W<EMR_SPEC, 1> { MR1_W::new(self) } #[doc = "Bit 2 - Event Mask on line 2"] #[inline(always)] #[must_use] pub fn mr2(&mut self) -> MR2_W<EMR_SPEC, 2> { MR2_W::new(self) } #[doc = "Bit 3 - Event Mask on line 3"] #[inline(always)] #[must_use] pub fn mr3(&mut self) -> MR3_W<EMR_SPEC, 3> { MR3_W::new(self) } #[doc = "Bit 4 - Event Mask on line 4"] #[inline(always)] #[must_use] pub fn mr4(&mut self) -> MR4_W<EMR_SPEC, 4> { MR4_W::new(self) } #[doc = "Bit 5 - Event Mask on line 5"] #[inline(always)] #[must_use] pub fn mr5(&mut self) -> MR5_W<EMR_SPEC, 5> { MR5_W::new(self) } #[doc = "Bit 6 - Event Mask on line 6"] #[inline(always)] #[must_use] pub fn mr6(&mut self) -> MR6_W<EMR_SPEC, 6> { MR6_W::new(self) } #[doc = "Bit 7 - Event Mask on line 7"] #[inline(always)] #[must_use] pub fn mr7(&mut self) -> MR7_W<EMR_SPEC, 7> { MR7_W::new(self) } #[doc = "Bit 8 - Event Mask on line 8"] #[inline(always)] #[must_use] pub fn mr8(&mut self) -> MR8_W<EMR_SPEC, 8> { MR8_W::new(self) } #[doc = "Bit 9 - Event Mask on line 9"] #[inline(always)] #[must_use] pub fn mr9(&mut self) -> MR9_W<EMR_SPEC, 9> { MR9_W::new(self) } #[doc = "Bit 10 - Event Mask on line 10"] #[inline(always)] #[must_use] pub fn mr10(&mut self) -> MR10_W<EMR_SPEC, 10> { MR10_W::new(self) } #[doc = "Bit 11 - Event Mask on line 11"] #[inline(always)] #[must_use] pub fn mr11(&mut self) -> MR11_W<EMR_SPEC, 11> { MR11_W::new(self) } #[doc = "Bit 12 - Event Mask on line 12"] #[inline(always)] #[must_use] pub fn mr12(&mut self) -> MR12_W<EMR_SPEC, 12> { MR12_W::new(self) } #[doc = "Bit 13 - Event Mask on line 13"] #[inline(always)] #[must_use] pub fn mr13(&mut self) -> MR13_W<EMR_SPEC, 13> { MR13_W::new(self) } #[doc = "Bit 14 - Event Mask on line 14"] #[inline(always)] #[must_use] pub fn mr14(&mut self) -> MR14_W<EMR_SPEC, 14> { MR14_W::new(self) } #[doc = "Bit 15 - Event Mask on line 15"] #[inline(always)] #[must_use] pub fn mr15(&mut self) -> MR15_W<EMR_SPEC, 15> { MR15_W::new(self) } #[doc = "Bit 16 - Event Mask on line 16"] #[inline(always)] #[must_use] pub fn mr16(&mut self) -> MR16_W<EMR_SPEC, 16> { MR16_W::new(self) } #[doc = "Bit 17 - Event Mask on line 17"] #[inline(always)] #[must_use] pub fn mr17(&mut self) -> MR17_W<EMR_SPEC, 17> { MR17_W::new(self) } #[doc = "Bit 18 - Event Mask on line 18"] #[inline(always)] #[must_use] pub fn mr18(&mut self) -> MR18_W<EMR_SPEC, 18> { MR18_W::new(self) } #[doc = "Bit 19 - Event Mask on line 19"] #[inline(always)] #[must_use] pub fn mr19(&mut self) -> MR19_W<EMR_SPEC, 19> { MR19_W::new(self) } #[doc = "Bit 20 - Event Mask on line 20"] #[inline(always)] #[must_use] pub fn mr20(&mut self) -> MR20_W<EMR_SPEC, 20> { MR20_W::new(self) } #[doc = "Bit 21 - Event Mask on line 21"] #[inline(always)] #[must_use] pub fn mr21(&mut self) -> MR21_W<EMR_SPEC, 21> { MR21_W::new(self) } #[doc = "Bit 22 - Event Mask on line 22"] #[inline(always)] #[must_use] pub fn mr22(&mut self) -> MR22_W<EMR_SPEC, 22> { MR22_W::new(self) } #[doc = "Bit 23 - Event Mask on line 23"] #[inline(always)] #[must_use] pub fn mr23(&mut self) -> MR23_W<EMR_SPEC, 23> { MR23_W::new(self) } #[doc = "Bit 24 - Event Mask on line 24"] #[inline(always)] #[must_use] pub fn mr24(&mut self) -> MR24_W<EMR_SPEC, 24> { MR24_W::new(self) } #[doc = "Bit 25 - Event Mask on line 25"] #[inline(always)] #[must_use] pub fn mr25(&mut self) -> MR25_W<EMR_SPEC, 25> { MR25_W::new(self) } #[doc = "Bit 26 - Event Mask on line 26"] #[inline(always)] #[must_use] pub fn mr26(&mut self) -> MR26_W<EMR_SPEC, 26> { MR26_W::new(self) } #[doc = "Bit 27 - Event Mask on line 27"] #[inline(always)] #[must_use] pub fn mr27(&mut self) -> MR27_W<EMR_SPEC, 27> { MR27_W::new(self) } #[doc = "Bit 28 - Event Mask on line 28"] #[inline(always)] #[must_use] pub fn mr28(&mut self) -> MR28_W<EMR_SPEC, 28> { MR28_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 = "Event mask register (EXTI_EMR)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`emr::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 [`emr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct EMR_SPEC; impl crate::RegisterSpec for EMR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`emr::R`](R) reader structure"] impl crate::Readable for EMR_SPEC {} #[doc = "`write(|w| ..)` method takes [`emr::W`](W) writer structure"] impl crate::Writable for EMR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets EMR to value 0"] impl crate::Resettable for EMR_SPEC { const RESET_VALUE: Self::Ux = 0; }
/// Exchanges a temporary OAuth code for an API token. /// /// Wraps https://api.slack.com/methods/oauth.access #[derive(Clone, Debug, Serialize, new)] pub struct AccessRequest<'a> { /// Issued when you created your application. pub client_id: &'a str, /// Issued when you created your application. pub client_secret: &'a str, /// The code param returned via the OAuth callback. pub code: &'a str, /// This must match the originally submitted URI (if one was sent). #[new(default)] pub redirect_uri: Option<&'a str>, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct AccessResponse { pub access_token: Option<String>, pub scope: Option<String>, }
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use uniform_rand::{ my_blake2b_hash, my_blake2s_hash, my_blake3_hash, my_sha3_hash, rounding_algo, TIME, UPPER, }; pub fn criterion_benchmark(c: &mut Criterion) { c.bench_function("my_sha3_hash", |b| { b.iter(|| rounding_algo(black_box(TIME), black_box(UPPER), black_box(my_sha3_hash))) }); c.bench_function("my_blake2s_hash", |b| { b.iter(|| { rounding_algo( black_box(TIME), black_box(UPPER), black_box(my_blake2s_hash), ) }) }); c.bench_function("my_blake2b_hash", |b| { b.iter(|| { rounding_algo( black_box(TIME), black_box(UPPER), black_box(my_blake2b_hash), ) }) }); c.bench_function("my_blake3_hash", |b| { b.iter(|| rounding_algo(black_box(TIME), black_box(UPPER), black_box(my_blake3_hash))) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
use std::error; use std::fmt; #[derive(Debug)] pub enum Error { CloseNodeError(String, &'static str), /// The list of dependencies is empty EmptyListError, IteratorDropped, NoAvailableNodeError, ResolveGraphError(&'static str), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::CloseNodeError(name, reason) => { write!(f, "Failed to close node {}: {}", name, reason) } Self::EmptyListError => write!(f, "The dependency list is empty"), Self::IteratorDropped => write!( f, "The iterator attached to the coordination thread dropped" ), Self::NoAvailableNodeError => write!(f, "No node are currently available"), Self::ResolveGraphError(reason) => write!(f, "Failed to resolve the graph: {}", reason), // _ => write!(f, "{:?}", self), } } } impl error::Error for Error {}
use std::sync::mpsc::channel; use std::thread; let (sender, receiver) = channel(); thread::spawn(move|| { sender.send(expensive_computation()).unwrap(); }); println!("{:?}", receiver.recv().unwrap());
use hymns::p2; use hymns::runner::timed_run; use hymns::vector2::Point2; use std::collections::HashSet; const INPUT: &str = include_str!("../input.txt"); fn reflect_points(axis: char, x_or_y: usize, points: &mut HashSet<Point2<usize>>) { let mut points_to_move = vec![]; for point in points.iter() { if axis == 'y' { if point.y > x_or_y { points_to_move.push(*point); } } else if point.x > x_or_y { points_to_move.push(*point); } } for point in points_to_move { if axis == 'y' { let distance_from_axis = point.y - x_or_y; points.insert(p2!(point.x, x_or_y - distance_from_axis)); } else { let distance_from_axis = point.x - x_or_y; points.insert(p2!(x_or_y - distance_from_axis, point.y)); } points.remove(&point); } } fn build_points(line_iter: &mut impl Iterator<Item = &'static str>) -> HashSet<Point2<usize>> { line_iter .map(|line| { let mut nums = line.split(','); let x: usize = nums.next().unwrap().parse().unwrap(); let y: usize = nums.next().unwrap().parse().unwrap(); p2!(x, y) }) .collect() } fn build_folds( line_iter: &mut impl Iterator<Item = &'static str>, ) -> impl Iterator<Item = (char, usize)> + '_ { line_iter.map(|line| { let bytes = line.as_bytes(); let axis = char::from(bytes[11]); let x_or_y = std::str::from_utf8(&bytes[13..]).unwrap().parse().unwrap(); (axis, x_or_y) }) } fn part1() -> usize { let mut line_iter = INPUT.lines(); let mut points = build_points(&mut line_iter.by_ref().take_while(|&line| !line.is_empty())); let (reflection_axis, x_or_y) = build_folds(&mut line_iter).next().unwrap(); reflect_points(reflection_axis, x_or_y, &mut points); points.len() } fn part2() -> String { let mut line_iter = INPUT.lines(); let mut points = build_points(&mut line_iter.by_ref().take_while(|&line| !line.is_empty())); for (reflection_axis, x_or_y) in build_folds(&mut line_iter) { reflect_points(reflection_axis, x_or_y, &mut points); } let (min_x, max_x, min_y, max_y) = points.iter().fold( (usize::MAX, usize::MIN, usize::MAX, usize::MIN), |(min_x, max_x, min_y, max_y), p| { ( min_x.min(p.x), max_x.max(p.x), min_y.min(p.y), max_y.max(p.y), ) }, ); let mut result = String::new(); for y in min_y..=max_y { for x in min_x..=max_x { if points.contains(&p2!(x, y)) { result.push('#'); } else { result.push(' '); } } result.push('\n'); } result } fn main() { timed_run(1, part1); timed_run(2, part2); } #[cfg(test)] mod tests { use super::*; #[test] fn test_part1() { assert_eq!(part1(), 842); } #[test] fn test_part2() { let mut expected = r#"### #### # # ### ## ## #### # # # # # # # # # # # # # # # ### ### ## # # # # # # # # # # # # ### # # # # # # # # # # # # # # # # # # # ### # # # # # ## ## #### ## "# .to_string(); // This is just to avoid ending a source code line with whitespace expected.push('\n'); assert_eq!(part2(), expected); } }
// =============================================================================== // 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 RemoveEntities { pub entity_list: Vec<i64>, } impl PartialEq for RemoveEntities { fn eq(&self, _other: &RemoveEntities) -> bool { true && &self.entity_list == &_other.entity_list } } impl LmcpSubscription for RemoveEntities { fn subscription() -> &'static str { "afrl.cmasi.RemoveEntities" } } impl Struct for RemoveEntities { fn struct_info() -> StructInfo { StructInfo { exist: 1, series: 4849604199710720000u64, version: 3, struct_ty: 53, } } } impl Lmcp for RemoveEntities { 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.entity_list.ser(r)?; pos += writeb; } Ok(pos) } fn deser(buf: &[u8]) -> Result<(RemoveEntities, usize), Error> { let mut pos = 0; let (si, u) = StructInfo::deser(buf)?; pos += u; if si == RemoveEntities::struct_info() { let mut out: RemoveEntities = Default::default(); { let r = get!(buf.get(pos ..)); let (x, readb): (Vec<i64>, usize) = Lmcp::deser(r)?; out.entity_list = x; pos += readb; } Ok((out, pos)) } else { Err(error!(ErrorType::InvalidStructInfo)) } } fn size(&self) -> usize { let mut size = 15; size += self.entity_list.size(); size } } pub trait RemoveEntitiesT: Debug + Send { fn as_afrl_cmasi_remove_entities(&self) -> Option<&RemoveEntities> { None } fn as_mut_afrl_cmasi_remove_entities(&mut self) -> Option<&mut RemoveEntities> { None } fn entity_list(&self) -> &Vec<i64>; fn entity_list_mut(&mut self) -> &mut Vec<i64>; } impl Clone for Box<RemoveEntitiesT> { fn clone(&self) -> Box<RemoveEntitiesT> { if let Some(x) = RemoveEntitiesT::as_afrl_cmasi_remove_entities(self.as_ref()) { Box::new(x.clone()) } else { unreachable!() } } } impl Default for Box<RemoveEntitiesT> { fn default() -> Box<RemoveEntitiesT> { Box::new(RemoveEntities::default()) } } impl PartialEq for Box<RemoveEntitiesT> { fn eq(&self, other: &Box<RemoveEntitiesT>) -> bool { if let (Some(x), Some(y)) = (RemoveEntitiesT::as_afrl_cmasi_remove_entities(self.as_ref()), RemoveEntitiesT::as_afrl_cmasi_remove_entities(other.as_ref())) { x == y } else { false } } } impl Lmcp for Box<RemoveEntitiesT> { fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> { if let Some(x) = RemoveEntitiesT::as_afrl_cmasi_remove_entities(self.as_ref()) { x.ser(buf) } else { unreachable!() } } fn deser(buf: &[u8]) -> Result<(Box<RemoveEntitiesT>, usize), Error> { let (si, _) = StructInfo::deser(buf)?; if si == RemoveEntities::struct_info() { let (x, readb) = RemoveEntities::deser(buf)?; Ok((Box::new(x), readb)) } else { Err(error!(ErrorType::InvalidStructInfo)) } } fn size(&self) -> usize { if let Some(x) = RemoveEntitiesT::as_afrl_cmasi_remove_entities(self.as_ref()) { x.size() } else { unreachable!() } } } impl RemoveEntitiesT for RemoveEntities { fn as_afrl_cmasi_remove_entities(&self) -> Option<&RemoveEntities> { Some(self) } fn as_mut_afrl_cmasi_remove_entities(&mut self) -> Option<&mut RemoveEntities> { Some(self) } fn entity_list(&self) -> &Vec<i64> { &self.entity_list } fn entity_list_mut(&mut self) -> &mut Vec<i64> { &mut self.entity_list } } #[cfg(test)] pub mod tests { use super::*; use quickcheck::*; impl Arbitrary for RemoveEntities { fn arbitrary<G: Gen>(_g: &mut G) -> RemoveEntities { RemoveEntities { entity_list: Arbitrary::arbitrary(_g), } } } quickcheck! { fn serializes(x: RemoveEntities) -> Result<TestResult, Error> { use std::u16; if x.entity_list.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); } 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: RemoveEntities) -> Result<TestResult, Error> { use std::u16; if x.entity_list.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); } let mut buf: Vec<u8> = vec![0; x.size()]; let sx = x.ser(&mut buf)?; let (y, sy) = RemoveEntities::deser(&buf)?; Ok(TestResult::from_bool(sx == sy && x == y)) } } }
use reqwest::header::HeaderValue; use serde::{Deserialize, Serialize}; #[derive(Clone)] pub struct DockerHub { username: String, password: String, } #[derive(Deserialize, Debug, Clone)] pub struct Token { pub token: String, } impl DockerHub { pub fn new(username: String, password: String) -> DockerHub { DockerHub { username, password } } pub async fn get_token(&self) -> Result<Token, Box<dyn std::error::Error>> { let token_url = "https://auth.docker.io/token?service=registry.docker.io&scope=repository:ratelimitpreview/test:pull"; if !self.username.is_empty() && !self.password.is_empty() { log::info!("Using Authenticated Token"); let token_response: Token = reqwest::Client::new() .get(token_url) .basic_auth(&self.username, Some(&self.password)) .send() .await? .json() .await?; return Ok(token_response); } log::info!("Using Anonymous Token"); let token_response: Token = reqwest::Client::new() .get(token_url) .send() .await? .json() .await?; Ok(token_response) } pub async fn get_docker_limits( &self, token: Token, ) -> Result<(String, String), Box<dyn std::error::Error>> { let registry_url = "https://registry-1.docker.io/v2/ratelimitpreview/test/manifests/latest"; let response: reqwest::Response = reqwest::Client::new() .head(registry_url) .bearer_auth(token.token) .send() .await?; let lm = response .headers() .get("ratelimit-limit") .map(|x| x.to_str()) .unwrap_or(Ok(""))? .into(); let rm = response .headers() .get("ratelimit-remaining") .unwrap_or(&HeaderValue::from_static("")) .to_str()? .into(); Ok((lm, rm)) } } #[derive(Debug, Deserialize, Serialize)] pub struct Claims { exp: usize, }
// Tests OP_COMPRESSED. To actually test compression you need to look at // server logs to see if decompression is happening. Even if these tests // are run against a server that does not support compression // these tests won't fail because the messages will be sent without compression // (as indicated in the specs). use bson::{doc, Bson}; use crate::{ client::options::ClientOptions, compression::{Compressor, CompressorId, Decoder}, test::{TestClient, CLIENT_OPTIONS}, }; #[cfg(feature = "zlib-compression")] #[test] fn test_zlib_compressor() { let zlib_compressor = Compressor::Zlib { level: Some(4) }; assert_eq!(CompressorId::Zlib, zlib_compressor.id()); let mut encoder = zlib_compressor.to_encoder().unwrap(); assert!(encoder.write_all(b"foo").is_ok()); assert!(encoder.write_all(b"bar").is_ok()); assert!(encoder.write_all(b"ZLIB").is_ok()); let compressed_bytes = encoder.finish().unwrap(); let decoder = Decoder::from_u8(CompressorId::Zlib as u8).unwrap(); let original_bytes = decoder.decode(compressed_bytes.as_slice()).unwrap(); assert_eq!(b"foobarZLIB", original_bytes.as_slice()); } #[cfg(feature = "zstd-compression")] #[test] fn test_zstd_compressor() { let zstd_compressor = Compressor::Zstd { level: None }; assert_eq!(CompressorId::Zstd, zstd_compressor.id()); let mut encoder = zstd_compressor.to_encoder().unwrap(); assert!(encoder.write_all(b"foo").is_ok()); assert!(encoder.write_all(b"bar").is_ok()); assert!(encoder.write_all(b"ZSTD").is_ok()); let compressed_bytes = encoder.finish().unwrap(); let decoder = Decoder::from_u8(CompressorId::Zstd as u8).unwrap(); let original_bytes = decoder.decode(compressed_bytes.as_slice()).unwrap(); assert_eq!(b"foobarZSTD", original_bytes.as_slice()); } #[cfg(feature = "snappy-compression")] #[test] fn test_snappy_compressor() { let snappy_compressor = Compressor::Snappy; assert_eq!(CompressorId::Snappy, snappy_compressor.id()); let mut encoder = snappy_compressor.to_encoder().unwrap(); assert!(encoder.write_all(b"foo").is_ok()); assert!(encoder.write_all(b"bar").is_ok()); assert!(encoder.write_all(b"SNAPPY").is_ok()); let compressed_bytes = encoder.finish().unwrap(); let decoder = Decoder::from_u8(CompressorId::Snappy as u8).unwrap(); let original_bytes = decoder.decode(compressed_bytes.as_slice()).unwrap(); assert_eq!(b"foobarSNAPPY", original_bytes.as_slice()); } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[cfg(feature = "zlib-compression")] async fn ping_server_with_zlib_compression() { let mut client_options = CLIENT_OPTIONS.get().await.clone(); client_options.compressors = Some(vec![Compressor::Zlib { level: Some(4) }]); send_ping_with_compression(client_options).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[cfg(feature = "zstd-compression")] async fn ping_server_with_zstd_compression() { let mut client_options = CLIENT_OPTIONS.get().await.clone(); client_options.compressors = Some(vec![Compressor::Zstd { level: None }]); send_ping_with_compression(client_options).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[cfg(feature = "snappy-compression")] async fn ping_server_with_snappy_compression() { let mut client_options = CLIENT_OPTIONS.get().await.clone(); client_options.compressors = Some(vec![Compressor::Snappy]); send_ping_with_compression(client_options).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[cfg(all( feature = "zstd-compression", feature = "zlib-compression", feature = "snappy-compression" ))] async fn ping_server_with_all_compressors() { let mut client_options = CLIENT_OPTIONS.get().await.clone(); client_options.compressors = Some(vec![ Compressor::Zlib { level: None }, Compressor::Snappy, Compressor::Zstd { level: None }, ]); send_ping_with_compression(client_options).await; } async fn send_ping_with_compression(client_options: ClientOptions) { let client = TestClient::with_options(Some(client_options)).await; let ret = client .database("admin") .run_command(doc! {"ping": 1}, None) .await; assert!(ret.is_ok()); let ret = ret.unwrap(); assert_eq!(ret.get("ok"), Some(Bson::Double(1.0)).as_ref()); }
use structopt::StructOpt; use tonic::{transport::Channel, Request, Response}; use pomodoro::session_client::SessionClient; use pomodoro::{ get_state_response::Phase, GetStateRequest, GetStateResponse, StartRequest, StartResponse, StopRequest, StopResponse, }; pub mod pomodoro { tonic::include_proto!("pomodoro"); } #[derive(StructOpt)] #[structopt(name = "pomoctl", about = "a lightweight pomodoro timer client")] pub struct Config { #[structopt(short = "h", long = "host", default_value = "[::1]")] host: String, #[structopt(short = "p", long = "port", default_value = "20799")] port: u16, #[structopt(subcommand)] cmd: Command, } #[derive(StructOpt)] enum Command { Start { #[structopt(short = "p", long = "periods", default_value = "0")] periods: u32, #[structopt(short = "w", long = "work-time", default_value = "25")] work_time: u32, #[structopt(short = "s", long = "short-time", default_value = "4")] short_break_time: u32, #[structopt(short = "l", long = "long-time", default_value = "20")] long_break_time: u32, #[structopt(long = "short-breaks", default_value = "4")] short_breaks_before_long: u32, }, State, Stop, } struct StartParams { periods: u32, work_time: u32, short_break_time: u32, long_break_time: u32, short_breaks_before_long: u32, } pub async fn run(conf: Config) -> Result<(), Box<dyn std::error::Error>> { let addr = format!("http://{}:{}", conf.host, conf.port); let mut client = match SessionClient::connect(addr).await { Ok(c) => c, Err(_) => { println!("connection-error"); std::process::exit(1); } }; match conf.cmd { Command::Start { periods, work_time, short_break_time, long_break_time, short_breaks_before_long, } => { let params = StartParams { periods, work_time, short_break_time, long_break_time, short_breaks_before_long, }; start(&mut client, params).await?; } Command::State => { let state_response = get_state(&mut client).await?; print_state(state_response.into_inner()); } Command::Stop => { stop(&mut client).await?; } }; Ok(()) } async fn start( client: &mut SessionClient<Channel>, params: StartParams, ) -> Result<Response<StartResponse>, Box<dyn std::error::Error>> { let request = Request::new(StartRequest { periods: params.periods, work_time: params.work_time, short_break_time: params.short_break_time, long_break_time: params.long_break_time, short_breaks_before_long: params.short_breaks_before_long, }); Ok(client.start(request).await?) } async fn get_state( client: &mut SessionClient<Channel>, ) -> Result<Response<GetStateResponse>, Box<dyn std::error::Error>> { let request = Request::new(GetStateRequest {}); Ok(client.get_state(request).await?) } async fn stop( client: &mut SessionClient<Channel>, ) -> Result<Response<StopResponse>, Box<dyn std::error::Error>> { let request = Request::new(StopRequest {}); Ok(client.stop(request).await?) } fn print_state(response: GetStateResponse) { let (state, remaining) = match Phase::from_i32(response.phase) { Some(Phase::Stopped) => ("stopped", None), Some(Phase::Working) => ("working", Some(response.time_remaining)), Some(Phase::ShortBreak) => { ("short-break", Some(response.time_remaining)) } Some(Phase::LongBreak) => { ("long-break", Some(response.time_remaining)) } None => ("".into(), None), }; let remaining = remaining .map(readable_remaining) .unwrap_or_else(String::new); println!("{} {}", state, remaining); } fn readable_remaining(time: u64) -> String { if time == 0 { return "".into(); } format!("{:02}:{:02}", time / 60, time % 60) }
extern crate rand; extern crate image; use std::collections::HashMap; use rand::random; use std::fs::File; use std::path::Path; /// Single map point pub struct Field{ state: u32, } impl Field{ pub fn new(state: u32) -> Field{ Field{ state: state, } } } /// Whole map pub struct Map{ height: u32, width: u32, fields: HashMap<(u32,u32),Field>, } /// Params for algo func pub struct Params{ /// algo iteration count iterations: u32, /// chances (0..100) to fill tile as earth /// for tiles with 0,1,2,3,4 neighbours chances: (u32,u32,u32,u32,u32), } impl Map { pub fn new(x: u32, y: u32) -> Map{ let mut map = Map{ height: y, width: x, fields: HashMap::new(), }; for i in 0..y { for j in 0..x{ map.fields.insert((j,i),Field::new(0)); } } map } /// Print map into stdout pub fn print(&self){ for i in 0..self.height { for j in 0..self.width { let sym = if self.fields.get(&(j,i)).unwrap().state > 0 { '*' } else { ' ' }; print!(" {}", sym); } println!(""); } } pub fn export(&self){ let mut imgbuf = image::ImageBuffer::new(self.width, self.height); for (x, y, pixel) in imgbuf.enumerate_pixels_mut() { let color = if self.fields.get(&(x,y)).unwrap().state > 0 { [0,125,0] } else { [0,0,125] }; *pixel = image::Rgb(color); } let ref mut fout = File::create(&Path::new("out.png")).unwrap(); image::ImageRgb8(imgbuf).save(fout, image::PNG); } /// Find neighbours for single map point fn calc_weight(&self, p: (u32,u32)) -> u32{ let mut res = self.fields.get(&p).unwrap().state; // right cell if p.0 < self.width -1 { res += self.fields.get(&(p.0 + 1 , p.1)).unwrap().state; } // left cell if p.0 > 0 { res += self.fields.get(&(p.0 - 1, p.1)).unwrap().state; } // upper cell if p.1 > 0 { res += self.fields.get(&(p.0, p.1 - 1)).unwrap().state; } // down cell if p.1 < self.height -1 { res += self.fields.get(&(p.0, p.1 + 1)).unwrap().state; } res } /// Create neighbours map fn calc_neighbours(&self,pre_map: &mut HashMap<(u32,u32),u32>){ for i in 0..self.height { for j in 0..self.width { let w = self.calc_weight((j,i)); pre_map.insert((j,i),w); } } } fn algo(&mut self, params: Params){ let mut neighbours = HashMap::<(u32,u32),u32>::new(); for _ in 0..params.iterations { self.calc_neighbours(&mut neighbours); for (p, field) in self.fields.iter_mut() { if field.state > 0 { continue; } let weight = neighbours.get(&p).unwrap(); let chance = random::<u32>() % 100; match *weight { 0 => if chance < params.chances.0 { field.state = 1 }, 1 => if chance < params.chances.1 { field.state = 1 }, 2 => if chance < params.chances.2 { field.state = 1 }, 3 => if chance < params.chances.3 { field.state = 1 }, 4 => if chance < params.chances.4 { field.state = 1 }, _ => {}, } } } } fn seed(&mut self, chance: u32){ // seed map for (_,field) in self.fields.iter_mut() { if random::<u32>() % 100 == chance { field.state = 1; } } } //TODO add target fill rate /// Generate map pub fn generate(&mut self){ self.seed(1); self.algo(Params{iterations: 25, chances: (0,20,40,50,80)}); } }
fn main() { let an_integer = 1u32; let a_boolean = true; let unit = (); // copy `an_integer` into `copied_integer` let copied_integer = an_integer; println!("An integer: {:?}", copied_integer); println!("A boolea: {:?}", a_boolean); println!("Meet the unit value: {:?}", unit); // The compiler warns about unused variable bindings; // these warnings can be silenced by prefixing the variable // name with an underscore let _unused_variable = 3u32; let noisy_unused_variable = 2u32; }