blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
140
path
stringlengths
5
183
src_encoding
stringclasses
6 values
length_bytes
int64
12
5.32M
score
float64
2.52
4.94
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
12
5.32M
download_success
bool
1 class
caf572d72fa9bb490090f0058f93f64166c8836c
Rust
fossabot/sahke
/src/requests/payloads/send_game.rs
UTF-8
2,387
3.078125
3
[ "MIT" ]
permissive
use serde::{Deserialize, Serialize}; use crate::{ requests::{dynamic, json, Method}, types::{InlineKeyboardMarkup, Message}, }; /// Use this method to send a game. On success, the sent Message is returned. #[serde_with_macros::skip_serializing_none] #[derive(Debug, PartialEq, Eq, Hash, Clone, Deserialize, Serialize)] pub struct SendGame { /// Unique identifier for the target chat chat_id: i32, /// Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. game_short_name: String, /// Sends the message silently. Users will receive a notification with no sound. disable_notification: Option<bool>, /// If the message is a reply, ID of the original message reply_to_message_id: Option<i32>, /// A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game. reply_markup: Option<InlineKeyboardMarkup>, } impl Method for SendGame { type Output = Message; const NAME: &'static str = "sendGame"; } impl json::Payload for SendGame {} impl dynamic::Payload for SendGame { fn kind(&self) -> dynamic::Kind { dynamic::Kind::Json(serde_json::to_string(self).unwrap()) } } impl SendGame { pub fn new<G>(chat_id: i32, game_short_name: G) -> Self where G: Into<String> { let game_short_name = game_short_name.into(); Self { chat_id, game_short_name, disable_notification: None, reply_to_message_id: None, reply_markup: None, } } } impl json::Request<'_, SendGame> { pub fn chat_id(mut self, val: i32) -> Self { self.payload.chat_id = val; self } pub fn game_short_name<T>(mut self, val: T) -> Self where T: Into<String> { self.payload.game_short_name = val.into(); self } pub fn disable_notification(mut self, val: bool) -> Self { self.payload.disable_notification = Some(val); self } pub fn reply_to_message_id(mut self, val: i32) -> Self { self.payload.reply_to_message_id = Some(val); self } pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.payload.reply_markup = Some(val); self } }
true
14df6dd4f4e7a92e592cd5b470a79f736e6ebae6
Rust
skywind3000/vim-clap
/crates/maple_cli/src/cmd/exec.rs
UTF-8
1,076
2.765625
3
[ "MIT" ]
permissive
use std::path::PathBuf; use std::process::Command; use anyhow::Result; use crate::light_command::{set_current_dir, LightCommand}; // This can work with the piped command, e.g., git ls-files | uniq. fn prepare_exec_cmd(cmd_str: &str, cmd_dir: Option<PathBuf>) -> Command { let mut cmd = if cfg!(target_os = "windows") { let mut cmd = Command::new("cmd"); cmd.args(&["/C", cmd_str]); cmd } else { let mut cmd = Command::new("bash"); cmd.arg("-c").arg(cmd_str); cmd }; set_current_dir(&mut cmd, cmd_dir); cmd } pub fn run( cmd: String, output: Option<String>, output_threshold: usize, cmd_dir: Option<PathBuf>, number: Option<usize>, enable_icon: bool, ) -> Result<()> { let mut exec_cmd = prepare_exec_cmd(&cmd, cmd_dir); let mut light_cmd = LightCommand::new( &mut exec_cmd, number, output, enable_icon, false, output_threshold, ); light_cmd.execute(&cmd.split_whitespace().map(Into::into).collect::<Vec<_>>()) }
true
62cbd09e138b0a7353dd3cc0638c35a4ee0eca3f
Rust
dendisuhubdy/rust-vs-cpp-unique_ptr
/rc_out_of_vector.rs
UTF-8
228
2.921875
3
[]
no_license
// Reference-counted smart pointer. use std::rc::Rc; fn main() { let v = vec![Rc::new(5i)]; println!("{}", *v[0]); let pointer_to_5 = v[0].clone(); println!("{}", *pointer_to_5); println!("{}", *v[0]); }
true
936f92e7b6458f148c393774d87080030dc53ef9
Rust
findelabs/rust-tools
/src/strings.rs
UTF-8
475
2.625
3
[]
no_license
use http::request::Parts; pub fn get_root_path(parts: &Parts) -> String { match parts.uri.path() { "/" => "default".to_owned(), _ => { let stage_one: Vec<&str> = parts.uri.path().split("/").collect(); // Convert to array let stage_two = &stage_one[1..stage_one.len() - 1]; // Remove the last path let stage_three = stage_two.join("_"); // Join back with underscores stage_three } } }
true
da5dee183bd1c7824120d446de5ae770517db20e
Rust
Johniel/contests
/atcoder/abc101/B/main.rs
UTF-8
442
3.09375
3
[ "Unlicense" ]
permissive
use std::io::Read; fn main() { let mut buff = String::new(); std::io::stdin().read_to_string(&mut buff).unwrap(); let mut iter = buff.split_whitespace(); let n: i32 = iter.next().unwrap().parse().unwrap(); let mut sum: i32 = 0; let mut m: i32 = n; while m != 0 { sum += m % 10; m /= 10; } if n % sum == 0 { println!("Yes"); } else { println!("No"); } () }
true
34b9a736f2d1aae1657f7015af2d9dc7245d27d3
Rust
danielthank/aoc2018
/day1/src/main.rs
UTF-8
1,042
3.296875
3
[]
no_license
use std::{ collections::HashSet, io::{self, Read, Write}, }; type MainResult<T> = std::result::Result<T, Box<dyn std::error::Error>>; fn main() -> MainResult<()> { let mut input = String::new(); io::stdin().read_to_string(&mut input)?; part1(&mut input)?; part2(&mut input)?; Ok(()) } fn part1(input: &mut String) -> MainResult<()> { let nums = input .lines() .map(|line| line.parse::<i32>()) .collect::<Result<Vec<_>, _>>()?; writeln!(io::stdout(), "{}", nums.iter().sum::<i32>())?; Ok(()) } fn part2(input: &mut String) -> MainResult<()> { let mut h: HashSet<i32> = HashSet::new(); let nums = input .lines() .map(|line| line.parse::<i32>()) .collect::<Result<Vec<_>, _>>()?; let mut sum = 0; loop { for num in nums.iter() { h.insert(sum); sum += num; if h.contains(&sum) { writeln!(io::stdout(), "{}", sum)?; return Ok(()); } } } }
true
0768a75a3e163beaeedb7bf9716f47941012bce8
Rust
aesedepece/limits-rs
/src/lib.rs
UTF-8
1,320
3.40625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Utilities for determining the limits that an operating system enforces on a given particular //! process. //! //! In its current implementation, this crate allows convenient read of the `/proc/<pid>/limits` //! file on GNU/Linux. On any other platform, the provided methods will return an error so that the //! user can decide what to do in the absence of information about limits. //! //! Support for other operating systems and platforms may be added on demand. use thiserror::Error; // Support for GNU/Linux #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] pub use crate::linux::*; // Placeholder for all other platforms #[cfg(not(target_os = "linux"))] mod default; #[cfg(not(target_os = "linux"))] pub use crate::default::*; /// All methods that can fail in this crate should return `Result<_, Error>`. That is, one of the /// variants herein. #[derive(Debug, Error)] pub enum Error { #[error("Unsupported OS. Could not get process limits.")] UnsupportedOS, #[error("Proc file not found at `{}`: {}", .0, .1)] ProcFileNotFound(String, #[source] std::io::Error), } /// Get the limits for the process in which we are running (our own process id). pub fn get_own_limits() -> Result<Limits, crate::Error> { let own_pid = std::process::id(); get_pid_limits(own_pid) }
true
cc23e202fae78023d29a19edc410bbad72da9fa4
Rust
happydpc/minecrust
/src/camera.rs
UTF-8
4,258
3.03125
3
[]
no_license
use crate::{ na::Unit, types::prelude::*, utils::{point3f, quaternion4f}, }; use std::{ f32, f32::consts::{FRAC_PI_2, PI}, }; #[derive(Debug, Clone)] pub struct Camera { pub pos: Point3f, pub pitch_q: UnitQuaternionf, pub yaw_q: UnitQuaternionf, } impl Default for Camera { fn default() -> Self { Camera::new(Point3f::origin(), -Vector3f::z_axis()) } } impl Camera { /// Yaw is measured as rotation from (0, 0, 1). Positive yaw is in the direction of the x-axis. pub fn new(pos: Point3f, direction: Unit<Vector3f>) -> Camera { let yaw = f32::atan2(direction.x, direction.z); // From the right hand rule, positive pitch will depress positive z let pitch = f32::asin(-direction.y); // (pitch, yaw, roll) let pitch_q = UnitQuaternionf::from_euler_angles(pitch, 0.0, 0.0); let yaw_q = UnitQuaternionf::from_euler_angles(0.0, yaw, 0.0); let c = Camera { pos, pitch_q, yaw_q, }; println!("{:#?}", c); c } pub fn new_with_target(pos: Point3f, target: Point3f) -> Camera { Camera::new(pos, Unit::new_normalize(target - pos)) } pub fn to_matrix(&self) -> Matrix4f { Matrix4f::look_at_rh( &self.pos, &(self.pos + self.direction().as_ref()), self.up().as_ref(), ) } pub fn direction(&self) -> Unit<Vector3f> { self.yaw_q * (self.pitch_q * Vector3f::z_axis()) } pub fn up(&self) -> Unit<Vector3f> { Vector3f::y_axis() } pub fn rotate(&mut self, (d_yaw, d_pitch): (f32, f32)) { let (mut pitch, _, _) = self.pitch_q.euler_angles(); pitch += d_pitch; if pitch > FRAC_PI_2 - 0.001 { pitch = FRAC_PI_2 - 0.001; } else if pitch < -FRAC_PI_2 + 0.001 { pitch = -FRAC_PI_2 + 0.001; } self.yaw_q = UnitQuaternionf::from_euler_angles(0.0, d_yaw, 0.0) * self.yaw_q; self.pitch_q = UnitQuaternionf::from_euler_angles(pitch, 0.0, 0.0); } pub fn rotate_to(&mut self, (yaw, pitch): (f32, f32)) { self.pitch_q = UnitQuaternionf::from_euler_angles(pitch, 0.0, 0.0); self.yaw_q = UnitQuaternionf::from_euler_angles(0.0, yaw, 0.0); } pub fn rotate_to_dir(&mut self, direction: &Vector3f) { self.rotate_to(Vector3f::z().yaw_pitch_diff(direction)); } } #[derive(Debug, Clone, Copy)] pub struct CameraAnimation { pub start_pos: Point3f, pub start_yaw_q: UnitQuaternionf, pub start_pitch_q: UnitQuaternionf, pub end_pos: Point3f, pub end_yaw_q: UnitQuaternionf, pub end_pitch_q: UnitQuaternionf, pub start_time: f32, pub duration: f32, } impl CameraAnimation { pub fn new( camera: &Camera, end_position: Point3f, end_direction: &Vector3f, start_time: f32, duration: f32, ) -> CameraAnimation { let (mut yaw_diff, pitch_diff) = camera.direction().yaw_pitch_diff(end_direction); if yaw_diff > PI { yaw_diff -= 2.0 * PI; } else if yaw_diff < -PI { yaw_diff += 2.0 * PI; } let rot_yaw_q = UnitQuaternionf::from_euler_angles(0.0, yaw_diff, 0.0); let rot_pitch_q = UnitQuaternionf::from_euler_angles(pitch_diff, 0.0, 0.0); CameraAnimation { start_pos: camera.pos, start_yaw_q: camera.yaw_q, start_pitch_q: camera.pitch_q, end_pos: end_position, end_yaw_q: rot_yaw_q * camera.yaw_q, end_pitch_q: rot_pitch_q * camera.pitch_q, start_time, duration, } } /// Returns the point, yaw quaternion, and pitch quaternion of the animation at time `t`. pub fn at(&self, time: f32) -> (Point3f, UnitQuaternionf, UnitQuaternionf) { let t = (time - self.start_time) / self.duration; ( point3f::clerp(&self.start_pos, &self.end_pos, t), quaternion4f::clerp(&self.start_yaw_q, &self.end_yaw_q, t), quaternion4f::clerp(&self.start_pitch_q, &self.end_pitch_q, t), ) } pub fn end_time(&self) -> f32 { self.start_time + self.duration } }
true
f94b61a37bf2df250854b9e7a0992372e399682c
Rust
tkbrigham/dmgr
/src/router.rs
UTF-8
1,493
2.5625
3
[]
no_license
extern crate iron; extern crate router; use iron::prelude::*; use iron::status; use router::Router; use std::io::Read; use std::thread; fn router_registration_main() { let mut router = Router::new(); router.get("/", handler, "index"); router.post("/register", register, "register"); println!("fffffirst here"); let listening = Iron::new(router).http("localhost:3000").unwrap(); println!("here now!"); fn handler(req: &mut Request) -> IronResult<Response> { println!("hit main handler"); let ref query = req.extensions.get::<Router>().unwrap().find("query").unwrap_or("/"); Ok(Response::with((status::Ok, *query))) } fn register(req: &mut Request) -> IronResult<Response> { println!("hit register handler"); let mut s = String::new(); let len = req.body.read_to_string(&mut s); thread::spawn(move || { let mut router = Router::new(); router.get("/new_endpoint", new_endpoint_handler, "new_endpoint"); let listening_pt_2 = Iron::new(router).http("localhost:3001").unwrap(); fn new_endpoint_handler(req: &mut Request) -> IronResult<Response> { println!("I am inside new endpoint handler"); Ok(Response::with((status::Ok, "yes this is new endpoint"))) } }); println!("I should be going next"); Ok(Response::with((status::Ok, format!("registered new handler: {:?}", req)))) } }
true
fd0563ca11d714659f79bb16018137007fe9df73
Rust
IshitaTakeshi/Tadataka
/src/interpolation.rs
UTF-8
4,784
3.171875
3
[ "Apache-2.0" ]
permissive
use ndarray::{Array, Array1, ArrayBase, ArrayView1, ArrayView2, Data, Ix1, Ix2}; use num::NumCast; use num_traits::float::Float; pub trait Interpolation<CoordinateType, OutputType> { fn interpolate(&self, c: &CoordinateType) -> OutputType; } fn interpolate<A: Float>( image: &ArrayView2<'_, A>, coordinate: &ArrayView1<'_, A> ) -> A { let cx = coordinate[0]; let cy = coordinate[1]; let lx = cx.floor(); let ly = cy.floor(); let lxi: usize= NumCast::from(lx).unwrap(); let lyi: usize= NumCast::from(ly).unwrap(); if lx == cx && ly == cy { return image[[lyi, lxi]]; } let ux = lx + NumCast::from(1.).unwrap(); let uy = ly + NumCast::from(1.).unwrap(); let uxi: usize = NumCast::from(ux).unwrap(); let uyi: usize = NumCast::from(uy).unwrap(); if lx == cx { return image[[lyi, lxi]] * (ux - cx) * (uy - cy) + image[[uyi, lxi]] * (ux - cx) * (cy - ly); } if ly == cy { return image[[lyi, lxi]] * (ux - cx) * (uy - cy) + image[[lyi, uxi]] * (cx - lx) * (uy - cy); } image[[lyi, lxi]] * (ux - cx) * (uy - cy) + image[[lyi, uxi]] * (cx - lx) * (uy - cy) + image[[uyi, lxi]] * (ux - cx) * (cy - ly) + image[[uyi, uxi]] * (cx - lx) * (cy - ly) } impl<A, S1, S2> Interpolation<ArrayBase<S1, Ix1>, A> for ArrayBase<S2, Ix2> where S1: Data<Elem = A>, S2: Data<Elem = A>, A: Float, { fn interpolate(&self, coordinate: &ArrayBase<S1, Ix1>) -> A { assert!(coordinate.shape()[0] == 2); interpolate(&self.view(), &coordinate.view()) } } impl<A, S1, S2> Interpolation<ArrayBase<S1, Ix2>, Array1<A>> for ArrayBase<S2, Ix2> where S1: Data<Elem = A>, S2: Data<Elem = A>, A: Float, { fn interpolate(&self, coordinates: &ArrayBase<S1, Ix2>) -> Array1<A> { assert!(coordinates.shape()[1] == 2); let n = coordinates.shape()[0]; let mut intensities = Array::zeros(n); for i in 0..n { intensities[i] = interpolate(&self.view(), &coordinates.row(i)); } intensities } } #[cfg(test)] mod tests { use super::*; use ndarray::{arr1, arr2}; #[test] fn test_interpolate_1d_input() { let image = arr2(&[[0., 1., 5.], [0., 0., 2.], [4., 3., 2.], [5., 6., 1.]]); let expected = image[[2, 1]] * (2.0 - 1.3) * (3.0 - 2.6) + image[[2, 2]] * (1.3 - 1.0) * (3.0 - 2.6) + image[[3, 1]] * (2.0 - 1.3) * (2.6 - 2.0) + image[[3, 2]] * (1.3 - 1.0) * (2.6 - 2.0); let c = arr1(&[1.3, 2.6]); assert_eq!(image.interpolate(&c), expected); // minimum coordinate let c = arr1(&[0.0, 0.0]); assert_eq!(image.interpolate(&c), image[[0, 0]]); // minimum x let c = arr1(&[0.0, 0.1]); let expected = image[[0, 0]] * (1.0 - 0.0) * (1.0 - 0.1) + image[[1, 0]] * (1.0 - 0.0) * (0.1 - 0.0); assert_eq!(image.interpolate(&c), expected); // minimum y let c = arr1(&[0.1, 0.0]); let expected = image[[0, 0]] * (1.0 - 0.1) * (1.0 - 0.0) + image[[0, 1]] * (0.1 - 0.0) * (1.0 - 0.0); assert_eq!(image.interpolate(&c), expected); // maximum x let c = arr1(&[2.0, 2.9]); let expected = image[[2, 2]] * (3.0 - 2.0) * (3.0 - 2.9) + image[[3, 2]] * (3.0 - 2.0) * (2.9 - 2.0); assert_eq!(image.interpolate(&c), expected); // maximum y let c = arr1(&[1.9, 3.0]); let expected = image[[3, 1]] * (2.0 - 1.9) * (4.0 - 3.0) + image[[3, 2]] * (1.9 - 1.0) * (4.0 - 3.0); assert_eq!(image.interpolate(&c), expected); // maximum c let c = arr1(&[2.0, 3.0]); assert_eq!(image.interpolate(&c), image[[3, 2]]); // TODO How about invalid input? // let c = arr(&[[3.0, 2.01]]); // let c = arr(&[[3.01, 2.0]]); // let c = arr(&[[-0.01, 0.0]]); // let c = arr(&[[0.0, -0.01]]); } #[test] fn test_interpolate_2d_input() { let image = arr2(&[[0., 1., 5.], [0., 0., 2.], [4., 3., 2.], [5., 6., 1.]]); let c = arr2(&[[0.0, 0.1], [0.1, 0.0]]); let expected = arr1( &[image[[0, 0]] * (1.0 - 0.0) * (1.0 - 0.1) + image[[1, 0]] * (1.0 - 0.0) * (0.1 - 0.0), image[[0, 0]] * (1.0 - 0.1) * (1.0 - 0.0) + image[[0, 1]] * (0.1 - 0.0) * (1.0 - 0.0)] ); assert_eq!(image.interpolate(&c), expected); } }
true
b6f937500d8ae957e310a8868685e37f9a92b6f1
Rust
co42/bevy_tilemap
/src/chunk/mod.rs
UTF-8
12,850
3.6875
4
[ "MIT" ]
permissive
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created does live in here. //! //! These below examples have nothing to do with this library as all should be //! done through the [`Tilemap`]. These are just more specific examples which //! use the private API of this library. //! //! [`Tilemap`]: crate::tilemap::Tilemap //! //! # Simple chunk creation //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! // There are two ways to create a new chunk. Either directly... //! //! tilemap.insert_chunk((0, 0)); //! //! // Or indirectly... //! //! let point = (0, 0); //! let sprite_index = 0; //! let tile = Tile { point, sprite_index, ..Default::default() }; //! tilemap.insert_tile(tile); //! //! ``` //! //! # Specifying what kind of chunk //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! tilemap.insert_chunk((0, 0)); //! //! let sprite_order = 0; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense, ..Default::default() }, 1); //! //! let sprite_order = 1; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense, ..Default::default() }, 1); //! ``` /// Chunk entity. pub(crate) mod entity; /// Sparse and dense chunk layers. mod layer; /// Meshes for rendering to vertices. pub(crate) mod mesh; /// Raw tile that is stored in the chunks. pub mod raw_tile; /// Files and helpers for rendering. pub(crate) mod render; /// Systems for chunks. pub(crate) mod system; use crate::{lib::*, tile::Tile}; pub use layer::LayerKind; use layer::{DenseLayer, LayerKindInner, SparseLayer, SpriteLayer}; pub use raw_tile::RawTile; /// A type for sprite layers. type SpriteLayers = Vec<Option<SpriteLayer>>; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug)] /// A chunk which holds all the tiles to be rendered. pub(crate) struct Chunk { /// The point coordinate of the chunk. point: Point2, /// The sprite layers of the chunk. z_layers: Vec<SpriteLayers>, /// Ephemeral user data that can be used for flags or other purposes. user_data: u128, /// A chunks mesh used for rendering. #[cfg_attr(feature = "serde", serde(skip))] mesh: Option<Handle<Mesh>>, /// An entity which is tied to this chunk. entity: Option<Entity>, } impl Chunk { /// A newly constructed chunk from a point and the maximum number of layers. pub(crate) fn new( point: Point2, sprite_layers: &[Option<LayerKind>], dimensions: Dimension3, ) -> Chunk { let mut chunk = Chunk { point, z_layers: vec![vec![None; sprite_layers.len()]; dimensions.depth as usize], user_data: 0, mesh: None, entity: None, }; for (sprite_order, kind) in sprite_layers.iter().enumerate() { if let Some(kind) = kind { chunk.add_sprite_layer(kind, sprite_order, dimensions) } } chunk } /// Adds a layer from a layer kind, the z layer, and dimensions of the /// chunk. pub(crate) fn add_sprite_layer( &mut self, kind: &LayerKind, sprite_order: usize, dimensions: Dimension3, ) { for z in 0..dimensions.depth as usize { match kind { LayerKind::Dense => { let tiles = vec![ RawTile { index: 0, color: Color::rgba(0.0, 0.0, 0.0, 0.0) }; (dimensions.width * dimensions.height) as usize ]; if let Some(z_layer) = self.z_layers.get_mut(z) { if let Some(sprite_order_layer) = z_layer.get_mut(sprite_order) { if !sprite_order_layer.is_some() { *sprite_order_layer = Some(SpriteLayer { inner: LayerKindInner::Dense(DenseLayer::new(tiles)), }); } } else { error!("sprite layer {} could not be added?", sprite_order); } } else { error!("sprite layer {} is out of bounds", sprite_order); } } LayerKind::Sparse => { if let Some(z_layer) = self.z_layers.get_mut(z) { if let Some(sprite_order_layer) = z_layer.get_mut(sprite_order) { if !sprite_order_layer.is_some() { *sprite_order_layer = Some(SpriteLayer { inner: LayerKindInner::Sparse(SparseLayer::new( HashMap::default(), )), }); } } else { error!("sprite layer {} is out of bounds", sprite_order); } } else { error!("sprite layer {} is out of bounds", sprite_order); } } } } } /// Returns the point of the location of the chunk. pub(crate) fn point(&self) -> Point2 { self.point } /// Moves a layer from a z layer to another. pub(crate) fn move_sprite_layer(&mut self, from_layer_z: usize, to_layer_z: usize) { for sprite_layers in &mut self.z_layers { if let Some(layer) = sprite_layers.get(to_layer_z) { if layer.is_some() { error!("sprite layer {} exists and can not be moved", to_layer_z); return; } } sprite_layers.swap(from_layer_z, to_layer_z); } } /// Removes a layer from the specified layer. pub(crate) fn remove_sprite_layer(&mut self, sprite_layer: usize) { for z_layer in &mut self.z_layers { z_layer.remove(sprite_layer); } } /// Sets the mesh for the chunk layer to use. pub(crate) fn set_mesh(&mut self, mesh: Handle<Mesh>) { self.mesh = Some(mesh); } /// Returns a reference to the chunk's mesh. pub(crate) fn mesh(&self) -> Option<&Handle<Mesh>> { self.mesh.as_ref() } /// Takes the mesh handle. pub(crate) fn take_mesh(&mut self) -> Option<Handle<Mesh>> { self.mesh.take() } /// Sets a single raw tile to be added to a z layer and index. pub(crate) fn set_tile(&mut self, index: usize, tile: Tile<Point3>) { if let Some(z_depth) = self.z_layers.get_mut(tile.point.z as usize) { if let Some(layer) = z_depth.get_mut(tile.sprite_order) { let raw_tile = RawTile { index: tile.sprite_index, color: tile.tint, }; if let Some(layer) = layer { layer.inner.as_mut().set_tile(index, raw_tile); } else { error!("sprite layer {} does not exist", tile.sprite_order); } } else { error!( "{} exceeded max number of sprite layers: {}", tile.sprite_order, z_depth.len() ); } } else { error!("z layer {} does not exist", tile.point.z); } } /// Removes a tile from a sprite layer with a given index and z order. pub(crate) fn remove_tile(&mut self, index: usize, sprite_layer: usize, z_depth: usize) { if let Some(layers) = self.z_layers.get_mut(z_depth) { if let Some(layer) = layers.get_mut(sprite_layer) { if let Some(layer) = layer { layer.inner.as_mut().remove_tile(index); } else { error!("sprite layer {} does not exist", index); } } else { error!( "{} exceeded max number of sprite layers: {}", index, layers.len() ); } } else { error!("sprite layer {} does not exist", sprite_layer); } } /// Adds an entity to a z layer, always when it is spawned. pub(crate) fn set_entity(&mut self, entity: Entity) { self.entity = Some(entity); } /// Gets the mesh entity of the chunk. pub(crate) fn get_entity(&self) -> Option<Entity> { self.entity } /// Gets the layers entity, if any. Useful for despawning. pub(crate) fn take_entity(&mut self) -> Option<Entity> { self.entity.take() } /// Gets a reference to a tile from a provided z order and index. pub(crate) fn get_tile( &self, index: usize, sprite_order: usize, z_depth: usize, ) -> Option<&RawTile> { self.z_layers.get(z_depth).and_then(|z_depth| { z_depth.get(sprite_order).and_then(|layer| { layer .as_ref() .and_then(|layer| layer.inner.as_ref().get_tile(index)) }) }) } /// Gets a mutable reference to a tile from a provided z order and index. pub(crate) fn get_tile_mut( &mut self, index: usize, sprite_order: usize, z_depth: usize, ) -> Option<&mut RawTile> { self.z_layers.get_mut(z_depth).and_then(|z_depth| { z_depth.get_mut(sprite_order).and_then(|layer| { layer .as_mut() .and_then(|layer| layer.inner.as_mut().get_tile_mut(index)) }) }) } /// Clears a given layer of all sprites. pub(crate) fn clear_layer(&mut self, layer: usize) { if let Some(sprite_layer) = self.z_layers.get_mut(layer) { for layer in sprite_layer.iter_mut().flatten() { layer.inner.as_mut().clear(); } } } /// At the given z layer, changes the tiles into attributes for use with /// the renderer using the given dimensions. /// /// Easier to pass in the dimensions opposed to storing it everywhere. pub(crate) fn tiles_to_renderer_parts( &self, dimensions: Dimension3, ) -> (Vec<f32>, Vec<[f32; 4]>) { let mut tile_indices = Vec::new(); let mut tile_colors = Vec::new(); for depth in &self.z_layers { for layer in depth.iter().flatten() { let (mut indices, mut colors) = layer.inner.as_ref().tiles_to_attributes(dimensions); tile_indices.append(&mut indices); tile_colors.append(&mut colors); } } (tile_indices, tile_colors) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_layer() { let point = Point2::new(0, 0); let layers = vec![ Some(LayerKind::Dense), Some(LayerKind::Sparse), None, Some(LayerKind::Sparse), None, ]; let dimensions = Dimension3::new(5, 5, 3); let mut chunk = Chunk::new(point, &[None, None, None, None, None], dimensions); for (x, layer) in layers.iter().enumerate() { if let Some(layer) = layer { chunk.add_sprite_layer(&layer, x, dimensions); } } assert_eq!(chunk.z_layers.len(), 3); for layer in &chunk.z_layers { assert_eq!(layer.len(), 5); } chunk.move_sprite_layer(1, 2); let sprite_layers = chunk.z_layers.get(0).unwrap(); assert_eq!(sprite_layers.get(1).unwrap().as_ref(), None); assert!(sprite_layers.get(0).unwrap().as_ref().is_some()); chunk.remove_sprite_layer(0); assert_eq!(chunk.z_layers.len(), 3); for layer in &chunk.z_layers { assert_eq!(layer.len(), 4); } } }
true
49a8b8a916155547d64e5a68b96381167143b986
Rust
rforcen/rust
/line_art/src/parser.rs
UTF-8
14,992
3.203125
3
[]
no_license
// Parser #![allow(dead_code)] use std::f32::consts::PI; use std::fs::File; use std::io::prelude::*; use std::io::BufWriter; use crate::scanner::*; #[derive(Debug, Clone, Copy)] enum PCode { Pushc(f32), PushId, // k Plus, Minus, Mul, Div, Power, Neg, Sin, Cos, Tan, Log, Log10, Exp, } pub struct Parser<'a> { scanner: Scanner<'a>, sym: Token, error: bool, range_k: std::ops::Range<i32>, gr_type: Token, // Lines/Circle/Ellipse code: Vec<PCode>, xcode: Vec<PCode>, ycode: Vec<PCode>, x1code: Vec<PCode>, y1code: Vec<PCode>, rcode: Vec<PCode>, } impl<'a> Parser<'a> { pub fn new(expr: &'a str) -> Self { Self { scanner: Scanner::new(expr), sym: Token::Null, error: false, range_k: std::ops::Range::<i32> { start: 0, end: 0 }, gr_type: Token::Null, code: vec![], xcode: vec![], ycode: vec![], x1code: vec![], y1code: vec![], rcode: vec![], } } pub fn get_sym(&mut self) -> Token { self.sym = self.scanner.get_token(); self.sym } // check and get next sym fn check_sym(&mut self, s: Token) { self.error = self.sym != s; self.get_sym(); } fn get_check(&mut self, s: Token) { self.get_sym(); self.error = self.sym != s; } fn test_sym(&mut self, s: Token) { self.error = self.sym != s; } pub fn get_sym_set(&mut self, token_set: &[Token]) { for t in token_set.into_iter() { if self.get_sym() != *t { self.error = true; break; } } self.get_sym(); } pub fn compile(&mut self) -> bool { match self.get_sym() { Token::Lines => { self.get_check(Token::Comma); self.gr_type = Token::Lines; self.compile_lines() } Token::Circles => { self.get_check(Token::Comma); self.gr_type = Token::Circles; self.compile_circles() } _ => false, } } fn gen(&mut self, pcode: PCode) { self.code.push(pcode) } fn get_range(&mut self) { self.get_sym(); // range: start..end let neg = if self.sym == Token::Minus { self.get_sym(); true } else { false }; self.test_sym(Token::Number); let from = self.scanner.get_num() as i32; self.get_sym(); self.test_sym(Token::Period); self.get_sym(); self.test_sym(Token::Period); self.get_sym(); self.test_sym(Token::Number); let to = self.scanner.get_num() as i32; self.range_k = std::ops::Range::<i32> { start: if neg { -from } else { from }, end: to, }; self.get_sym(); self.test_sym(Token::Comma); } fn compile_lines(&mut self) -> bool { // from..to, (f1, t1),(f2,t2) self.get_range(); self.get_sym(); self.check_sym(Token::Oparen); self.exp0(); // f1 self.xcode = self.code.clone(); self.code.clear(); self.check_sym(Token::Comma); self.exp0(); // t1 self.ycode = self.code.clone(); self.code.clear(); self.check_sym(Token::Cparen); self.get_sym(); self.check_sym(Token::Comma); self.exp0(); // f2 self.x1code = self.code.clone(); self.code.clear(); self.check_sym(Token::Comma); self.exp0(); // t2 self.y1code = self.code.clone(); self.code.clear(); self.check_sym(Token::Cparen); !self.error } fn compile_circles(&mut self) -> bool { static DEF_TOKENS: [Token; 5] = [ Token::Id, Token::Oparen, Token::Id, Token::Cparen, Token::Equal, ]; self.get_range(); self.get_sym_set(&DEF_TOKENS); // X(k)= self.exp0(); self.test_sym(Token::Comma); self.xcode = self.code.clone(); self.code.clear(); self.get_sym_set(&DEF_TOKENS); // Y(K)= self.exp0(); self.test_sym(Token::Comma); self.ycode = self.code.clone(); self.code.clear(); self.get_sym_set(&DEF_TOKENS); // R(K)= self.exp0(); self.rcode = self.code.clone(); self.code.clear(); !self.error } pub fn exp0(&mut self) { let is_neg = if self.sym == Token::Minus { self.get_sym(); true } else { false }; self.exp01(); if is_neg { self.gen(PCode::Neg) } loop { match self.sym { Token::Plus => { self.get_sym(); self.exp01(); self.gen(PCode::Plus); } Token::Minus => { self.get_sym(); self.exp01(); self.gen(PCode::Minus); } _ => break, } } } fn exp01(&mut self) { fn implicit_mult(t: Token) -> bool { static IMPLICIT_MULT_SYM: [Token; 10] = [ Token::Id, Token::Number, Token::Pi, Token::Oparen, Token::FuncSin, Token::FuncCos, Token::FuncTan, Token::FuncLog, Token::FuncLog10, Token::FuncExp, ]; IMPLICIT_MULT_SYM.iter().any(|&i| i == t) } self.exp02(); loop { if implicit_mult(self.sym) { self.exp02(); self.gen(PCode::Mul) } else { match self.sym { Token::Mult => { self.get_sym(); self.exp02(); self.gen(PCode::Mul) } Token::Div => { self.get_sym(); self.exp02(); self.gen(PCode::Div) } _ => break, } } } } fn exp02(&mut self) { self.exp03(); if self.sym == Token::NumberSup { self.gen(PCode::Pushc(self.scanner.get_num())); self.gen(PCode::Power); self.get_sym(); } else { loop { if self.sym == Token::Power { self.get_sym(); self.exp03(); self.gen(PCode::Power); } else { break; } } } } fn exp03(&mut self) { match self.sym { Token::Oparen => { self.get_sym(); self.exp0(); self.check_sym(Token::Cparen); } Token::Number | Token::NumberSup => { self.gen(PCode::Pushc(self.scanner.get_num())); self.get_sym(); } Token::Pi => { self.gen(PCode::Pushc(PI)); self.get_sym(); } Token::Id => { // only id is 'k' self.gen(PCode::PushId); self.get_sym(); } Token::Minus => { self.get_sym(); self.exp03(); self.gen(PCode::Neg); } Token::FuncSin => { self.get_sym(); self.exp03(); self.gen(PCode::Sin); } Token::FuncCos => { self.get_sym(); self.exp03(); self.gen(PCode::Cos); } Token::FuncTan => { self.get_sym(); self.exp03(); self.gen(PCode::Tan); } Token::FuncLog => { self.get_sym(); self.exp03(); self.gen(PCode::Log); } Token::FuncLog10 => { self.get_sym(); self.exp03(); self.gen(PCode::Log10); } Token::FuncExp => { self.get_sym(); self.exp03(); self.gen(PCode::Exp); } Token::Null => {} _ => self.error = true, } } // execute_circle on k -> x,y,r fn exec(&self, code: &Vec<PCode>, k: f32) -> f32 { let mut stack = vec![0.; 16]; let mut sp = 0; for c in code { match c { PCode::Pushc(x) => { stack[sp] = *x; sp += 1 } PCode::PushId => { stack[sp] = k; sp += 1 } PCode::Plus => { sp -= 1; stack[sp - 1] += stack[sp] } PCode::Minus => { sp -= 1; stack[sp - 1] -= stack[sp] } PCode::Mul => { sp -= 1; stack[sp - 1] *= stack[sp] } PCode::Div => { sp -= 1; stack[sp - 1] /= stack[sp] } PCode::Power => { sp -= 1; stack[sp - 1] = stack[sp - 1].powf(stack[sp]) } PCode::Neg => stack[sp - 1] = -stack[sp - 1], PCode::Sin => stack[sp - 1] = stack[sp - 1].sin(), PCode::Cos => stack[sp - 1] = stack[sp - 1].cos(), PCode::Tan => stack[sp - 1] = stack[sp - 1].tan(), PCode::Log => stack[sp - 1] = stack[sp - 1].ln(), PCode::Log10 => stack[sp - 1] = stack[sp - 1].log10(), PCode::Exp => stack[sp - 1] = stack[sp - 1].exp(), } } if sp == 1 { stack[0] } else { 0.0 } } fn execute_circle(&self, k: f32) -> (f32, f32, f32) { // circles ( self.exec(&self.xcode, k), self.exec(&self.ycode, k), self.exec(&self.rcode, k), ) } fn execute_line(&self, k: f32) -> (f32, f32, f32, f32) { ( self.exec(&self.xcode, k), self.exec(&self.ycode, k), self.exec(&self.x1code, k), self.exec(&self.y1code, k), ) } fn generate_lines(&self) -> Vec<(f32, f32, f32, f32)> { (self.range_k.start..self.range_k.end) .map(|k| self.execute_line(k as f32)) .collect() } fn generate_circles(&self) -> Vec<(f32, f32, f32)> { (self.range_k.start..self.range_k.end) .map(|k| self.execute_circle(k as f32)) .collect() } fn generate_lines_svg( &self, path: &str, width: f32, height: f32, scale_factor: f32, /* 3 or 6 */ x_offset: f32, y_offset: f32, ) { let lines = self.generate_lines(); let mut buff_write = BufWriter::new(File::create(path).unwrap()); let scale = width / scale_factor; buff_write .write( &format!( " <svg width='{w}' height='{h}' fill='none' stroke='blue' stroke-width='{sw}' > \t<rect width='{w}' height='{h}' style='fill:white' />\n\n", w = width, h = height, sw = 0.3 ) .as_bytes(), ) .unwrap(); for line in &lines { buff_write .write( &format!( "\t<line x1='{:.0}' y1='{:.0}' x2='{:.0}' y2='{:.0}'/>\n", (line.0 + x_offset + 1.) * scale, height / 2. - (1. + line.1 + y_offset) * scale, (line.2 + x_offset + 1.) * scale, height / 2. - (1. + line.3 + y_offset) * scale ) .as_bytes(), ) .unwrap(); } buff_write.write(&format!("</svg>").as_bytes()).unwrap(); buff_write.flush().unwrap(); } pub fn generate_circles_svg( &self, path: &str, width: f32, height: f32, scale_factor: f32, /* 3 or 6 */ ) { let circs = self.generate_circles(); let mut buff_write = BufWriter::new(File::create(path).unwrap()); let scale = width / scale_factor; buff_write .write( &format!( " <svg width='{w}' height='{h}' fill='none' stroke='blue' stroke-width='{sw}' > \t<rect width='{w}' height='{h}' style='fill:white' />\n\n", w = width, h = height, sw = 0.3 ) .as_bytes(), ) .unwrap(); for circ in &circs { buff_write .write( &format!( "\t<circle cx='{:.0}' cy='{:.0}' r='{:.0}'/>\n", circ.0 * scale + width / 2., height / 2. - circ.1 * scale, circ.2 * scale ) .as_bytes(), ) .unwrap(); } buff_write.write(&format!("</svg>").as_bytes()).unwrap(); buff_write.flush().unwrap(); } pub fn print_code(&self) { print!("x.code="); for c in &self.xcode { print!("{:?} ", c) } print!("\ny.code="); for c in &self.ycode { print!("{:?} ", c) } print!("\nx1.code="); for c in &self.x1code { print!("{:?} ", c) } print!("\ny1.code="); for c in &self.y1code { print!("{:?} ", c) } print!("\n\nr.code="); for c in &self.rcode { print!("{:?} ", c) } println!("") } pub fn generate_svg( &self, path: &str, width: f32, height: f32, scale_factor: f32, /* 3 or 6 */ x_offset: f32, y_offset: f32, ) { match self.gr_type { Token::Lines => { self.generate_lines_svg(path, width, height, scale_factor, x_offset, y_offset) } Token::Circles => self.generate_circles_svg(path, width, height, scale_factor), _ => {} } } }
true
29d0d446416969b5642f8a1a7571bb6b42233ddf
Rust
mitchmindtree/gaussian
/src/lib.rs
UTF-8
1,382
3.546875
4
[]
no_license
/// Gen raw gaussian value with distribution mean at 0. pub fn gen_raw<R>(mut rng: R) -> f64 where R: rand::Rng, { rng.sample(rand_distr::StandardNormal) } /// Generates a raw gaussian value between [0.0, 1.0) whose distribution's mean is at `value` with /// the given amount of `randomness` between [0.0, 1.0). /// /// **Panic**s if the `value` is less than 0.0 or greater than or equal to 1.0. /// /// **Panic**s if the `randomness` is less than 0.0 or greater than or equal to 1.0. pub fn gen<R>(mut rng: R, value: f64, randomness: f64) -> f64 where R: rand::Rng, { assert!(value >= 0.0); assert!(value < 1.0); assert!(randomness >= 0.0); assert!(randomness <= 1.0); // If there is no randomness, return the value as it was given. if randomness == 0.0 { return value; } // If there is complete randomness, generate a uniform distribution value. if randomness == 1.0 { return rand::Rng::gen_range(&mut rng, 0.0, 1.0); } // Offset the value over the normal distributions let offset_value = value * 2.0 - 1.0; // Keep attempting values until we get one that falls within the range. loop { let normal = gen_raw(&mut rng); let attempt = normal * randomness + offset_value; if -1.0 <= attempt && attempt < 1.0 { return (attempt + 1.0) * 0.5; } } }
true
836887e0709ecd0a75054935cad89f032618c85d
Rust
bloveless/rust-advent-of-code-2020
/day04/src/main.rs
UTF-8
4,330
3
3
[]
no_license
#[macro_use] extern crate lazy_static; use std::fs; use regex::Regex; lazy_static! { static ref HEIGHT_REGEX: Regex = Regex::new(r"^([0-9]*)(in|cm)$").unwrap(); static ref HAIR_COLOR_REGEX: Regex = Regex::new(r"^#[0-9a-f]{6}$").unwrap(); static ref PASSPORT_REGEX: Regex = Regex::new(r"^[0-9]{9}$").unwrap(); } struct Identification<'a> { birth_year: Option<i32>, issue_year: Option<i32>, expiration_year: Option<i32>, height: Option<i32>, hair_color: Option<&'a str>, eye_color: Option<&'a str>, passport_id: Option<&'a str>, country_id: Option<&'a str>, } impl<'a> Identification<'a> { pub fn new() -> Identification<'a> { Identification{ birth_year: None, issue_year: None, expiration_year: None, height: None, hair_color: None, eye_color: None, passport_id: None, country_id: None } } fn is_valid(&self) -> bool { self.birth_year != None && self.issue_year != None && self.expiration_year != None && self.height != None && self.hair_color != None && self.eye_color != None && self.passport_id != None } fn set_birth_year(&mut self, year: &str) { let year: i32 = match year.parse() { Ok(year) => year, Err(_) => 0, }; if year >= 1920 && year <= 2002 { self.birth_year = Some(year); } } fn set_issue_year(&mut self, year: &str) { let year: i32 = match year.parse() { Ok(year) => year, Err(_) => 0, }; if year >= 2010 && year <= 2020 { self.issue_year = Some(year); } } fn set_expiration_year(&mut self, year: &str) { let year: i32 = match year.parse() { Ok(year) => year, Err(_) => 0, }; if year >= 2020 && year <= 2030 { self.expiration_year = Some(year); } } fn set_height(&mut self, height: &str) { for cap in HEIGHT_REGEX.captures_iter(height) { let height: i32 = cap[1].parse().unwrap(); if &cap[2] == "cm" && height >= 150 && height <= 193 { self.height = Some(height); } if &cap[2] == "in" && height >= 59 && height <= 76 { self.height = Some(height); } } } fn set_hair_color(&mut self, hair_color: &'a str) { if HAIR_COLOR_REGEX.is_match(hair_color) { self.hair_color = Some(hair_color); } } fn set_eye_color(&mut self, eye_color: &'a str) { if ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].contains(&eye_color) { self.eye_color = Some(eye_color); } } fn set_passport_id(&mut self, passport_id: &'a str) { if PASSPORT_REGEX.is_match(passport_id) { self.passport_id = Some(passport_id); } } fn set_country_id(&mut self, country_id: &'a str) { self.country_id = Some(country_id); } } fn main() { let input: String = fs::read_to_string("input.txt").expect("Unable to open input.txt file"); let lines: Vec<&str> = input.split("\n\n").collect(); let mut ids: Vec<Identification> = Vec::new(); for input in lines { let mut id = Identification::new(); for group in input.split_whitespace() { let key_value: Vec<&str> = group.split(':').collect(); match key_value[0] { "hcl" => id.set_hair_color(key_value[1]), "ecl" => id.set_eye_color(key_value[1]), "pid" => id.set_passport_id(key_value[1]), "cid" => id.set_country_id(key_value[1]), "eyr" => id.set_expiration_year(key_value[1]), "hgt" => id.set_height(key_value[1]), "byr" => id.set_birth_year(key_value[1]), "iyr" => id.set_issue_year(key_value[1]), _ => panic!("Unknown key found"), }; } ids.push(id); } let mut valid_ids = 0; for id in &ids { if id.is_valid() { valid_ids += 1; } } println!("Valid IDs: {} Total IDs: {}", valid_ids, ids.len()); }
true
125cbce1eaaf80be023c83f4109a54e600c896e9
Rust
BlackbirdHQ/ublox-cellular-rs
/ublox-cellular/src/command/sms/types.rs
UTF-8
1,112
2.71875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
//! Argument and parameter types used by Short Messages Service Commands and Responses use atat::atat_derive::AtatEnum; /// Indicates the basic message indication type #[derive(Debug, Clone, PartialEq, Eq, AtatEnum)] pub enum MessageIndicationType { /// • 1: Voice Message Waiting (third level method) or Voice Message Waiting on Line 1 /// (CPHS method) VoiceMessage = 1, /// • 2: Fax Message Waiting FaxMessage = 2, /// • 3: Electronic Mail Message Waiting EmailMessage = 3, /// • 4: Extended Message Type Waiting (i.e. see the 3GPP TS 23.038) ExtendedMessage = 4, /// • 5: Video Message Waiting VideoMessage = 5, /// • 6: Voice Message Waiting on Line 2 (CPHS method) VoiceMessageLine2 = 6, /// • 7: reserved for future use Reserved = 7, } /// Indicates whether the +UMWI URC is enabled or not #[derive(Debug, Clone, PartialEq, Eq, AtatEnum)] pub enum MessageWaitingMode { /// • 0: disable the +UMWI URC Disabled = 0, /// • 1 (factory-programmed value): enable the +UMWI URC #[at_arg(default)] Enabled = 1, }
true
22de444f45d5aa13397e1d0a76250d162d794287
Rust
anweiss/cddl
/src/validator/json.rs
UTF-8
90,143
2.515625
3
[ "MIT" ]
permissive
#![cfg(feature = "std")] #![cfg(feature = "json")] #![cfg(not(feature = "lsp"))] use super::*; use crate::{ ast::*, token, visitor::{self, *}, }; use std::{ borrow::Cow, collections::HashMap, convert::TryFrom, fmt::{self, Write}, }; use chrono::{TimeZone, Utc}; use serde_json::Value; #[cfg(feature = "additional-controls")] use control::{abnf_from_complex_controller, cat_operation, plus_operation, validate_abnf}; /// JSON validation Result pub type Result = std::result::Result<(), Error>; /// JSON validation error #[derive(Debug)] pub enum Error { /// Zero or more validation errors Validation(Vec<ValidationError>), /// JSON parsing error JSONParsing(serde_json::Error), /// CDDL parsing error CDDLParsing(String), /// UTF8 parsing error, UTF8Parsing(std::str::Utf8Error), /// Disabled feature DisabledFeature(String), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::Validation(errors) => { let mut error_str = String::new(); for e in errors.iter() { let _ = writeln!(error_str, "{}", e); } write!(f, "{}", error_str) } Error::JSONParsing(error) => write!(f, "error parsing JSON: {}", error), Error::CDDLParsing(error) => write!(f, "error parsing CDDL: {}", error), Error::UTF8Parsing(error) => write!(f, "error pasing utf8: {}", error), Error::DisabledFeature(feature) => write!(f, "feature {} is not enabled", feature), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::JSONParsing(error) => Some(error), _ => None, } } } impl Error { fn from_validator(jv: &JSONValidator, reason: String) -> Self { Error::Validation(vec![ValidationError { cddl_location: jv.cddl_location.clone(), json_location: jv.json_location.clone(), reason, is_multi_type_choice: jv.is_multi_type_choice, is_group_to_choice_enum: jv.is_group_to_choice_enum, type_group_name_entry: jv.type_group_name_entry.map(|e| e.to_string()), is_multi_group_choice: jv.is_multi_group_choice, }]) } } /// JSON validation error #[derive(Clone, Debug)] pub struct ValidationError { /// Error message pub reason: String, /// Location in CDDL where error occurred pub cddl_location: String, /// Location in JSON (in JSONPointer notation) where error occurred pub json_location: String, /// Whether or not the error is associated with multiple type choices pub is_multi_type_choice: bool, /// Whether or not the error is associated with multiple group choices pub is_multi_group_choice: bool, /// Whether or not the error is associated with a group to choice enumeration pub is_group_to_choice_enum: bool, /// Error is associated with a type/group name group entry pub type_group_name_entry: Option<String>, } impl fmt::Display for ValidationError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut error_str = String::from("error validating"); if self.is_multi_group_choice { error_str.push_str(" group choice"); } if self.is_multi_type_choice { error_str.push_str(" type choice"); } if self.is_group_to_choice_enum { error_str.push_str(" type choice in group to choice enumeration"); } if let Some(entry) = &self.type_group_name_entry { let _ = write!(error_str, " group entry associated with rule \"{}\"", entry); } if self.json_location.is_empty() { return write!( f, "{} at the root of the JSON document: {}", error_str, self.reason ); } write!( f, "{} at JSON location {}: {}", error_str, self.json_location, self.reason ) } } impl std::error::Error for ValidationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } impl ValidationError { fn from_validator(jv: &JSONValidator, reason: String) -> Self { ValidationError { cddl_location: jv.cddl_location.clone(), json_location: jv.json_location.clone(), reason, is_multi_type_choice: jv.is_multi_type_choice, is_group_to_choice_enum: jv.is_group_to_choice_enum, type_group_name_entry: jv.type_group_name_entry.map(|e| e.to_string()), is_multi_group_choice: jv.is_multi_group_choice, } } } /// JSON validator type #[derive(Clone)] pub struct JSONValidator<'a> { cddl: &'a CDDL<'a>, json: Value, errors: Vec<ValidationError>, cddl_location: String, json_location: String, // Occurrence indicator detected in current state of AST evaluation occurrence: Option<Occur>, // Current group entry index detected in current state of AST evaluation group_entry_idx: Option<usize>, // JSON object value hoisted from previous state of AST evaluation object_value: Option<Value>, // Is member key detected in current state of AST evaluation is_member_key: bool, // Is a cut detected in current state of AST evaluation is_cut_present: bool, // Str value of cut detected in current state of AST evaluation cut_value: Option<Cow<'a, str>>, // Validate the generic rule given by str ident in current state of AST // evaluation eval_generic_rule: Option<&'a str>, // Aggregation of generic rules generic_rules: Vec<GenericRule<'a>>, // Control operator token detected in current state of AST evaluation ctrl: Option<token::ControlOperator>, // Is a group to choice enumeration detected in current state of AST // evaluation is_group_to_choice_enum: bool, // Are 2 or more type choices detected in current state of AST evaluation is_multi_type_choice: bool, // Are 2 or more group choices detected in current state of AST evaluation is_multi_group_choice: bool, // Type/group name entry detected in current state of AST evaluation. Used // only for providing more verbose error messages type_group_name_entry: Option<&'a str>, // Whether or not to advance to the next group entry if member key validation // fails as detected during the current state of AST evaluation advance_to_next_entry: bool, is_ctrl_map_equality: bool, entry_counts: Option<Vec<EntryCount>>, // Collect map entry keys that have already been validated validated_keys: Option<Vec<String>>, // Collect map entry values that have yet to be validated values_to_validate: Option<Vec<Value>>, // Collect valid array indices when entries are type choices valid_array_items: Option<Vec<usize>>, // Collect invalid array item errors where the key is the index of the invalid // array item array_errors: Option<HashMap<usize, Vec<ValidationError>>>, is_colon_shortcut_present: bool, is_root: bool, is_multi_type_choice_type_rule_validating_array: bool, #[cfg(not(target_arch = "wasm32"))] #[cfg(feature = "additional-controls")] enabled_features: Option<&'a [&'a str]>, #[cfg(target_arch = "wasm32")] #[cfg(feature = "additional-controls")] enabled_features: Option<Box<[JsValue]>>, #[cfg(feature = "additional-controls")] has_feature_errors: bool, #[cfg(feature = "additional-controls")] disabled_features: Option<Vec<String>>, } #[derive(Clone, Debug)] struct GenericRule<'a> { name: &'a str, params: Vec<&'a str>, args: Vec<Type1<'a>>, } impl<'a> JSONValidator<'a> { #[cfg(not(target_arch = "wasm32"))] #[cfg(feature = "additional-controls")] /// New JSONValidation from CDDL AST and JSON value pub fn new(cddl: &'a CDDL<'a>, json: Value, enabled_features: Option<&'a [&'a str]>) -> Self { JSONValidator { cddl, json, errors: Vec::default(), cddl_location: String::new(), json_location: String::new(), occurrence: None, group_entry_idx: None, object_value: None, is_member_key: false, is_cut_present: false, cut_value: None, eval_generic_rule: None, generic_rules: Vec::new(), ctrl: None, is_group_to_choice_enum: false, is_multi_type_choice: false, is_multi_group_choice: false, type_group_name_entry: None, advance_to_next_entry: false, is_ctrl_map_equality: false, entry_counts: None, validated_keys: None, values_to_validate: None, valid_array_items: None, array_errors: None, is_colon_shortcut_present: false, is_root: false, is_multi_type_choice_type_rule_validating_array: false, enabled_features, has_feature_errors: false, disabled_features: None, } } #[cfg(not(target_arch = "wasm32"))] #[cfg(not(feature = "additional-controls"))] /// New JSONValidation from CDDL AST and JSON value pub fn new(cddl: &'a CDDL<'a>, json: Value) -> Self { JSONValidator { cddl, json, errors: Vec::default(), cddl_location: String::new(), json_location: String::new(), occurrence: None, group_entry_idx: None, object_value: None, is_member_key: false, is_cut_present: false, cut_value: None, eval_generic_rule: None, generic_rules: Vec::new(), ctrl: None, is_group_to_choice_enum: false, is_multi_type_choice: false, is_multi_group_choice: false, type_group_name_entry: None, advance_to_next_entry: false, is_ctrl_map_equality: false, entry_counts: None, validated_keys: None, values_to_validate: None, valid_array_items: None, array_errors: None, is_colon_shortcut_present: false, is_root: false, is_multi_type_choice_type_rule_validating_array: false, } } #[cfg(target_arch = "wasm32")] #[cfg(feature = "additional-controls")] /// New JSONValidation from CDDL AST and JSON value pub fn new(cddl: &'a CDDL<'a>, json: Value, enabled_features: Option<Box<[JsValue]>>) -> Self { JSONValidator { cddl, json, errors: Vec::default(), cddl_location: String::new(), json_location: String::new(), occurrence: None, group_entry_idx: None, object_value: None, is_member_key: false, is_cut_present: false, cut_value: None, eval_generic_rule: None, generic_rules: Vec::new(), ctrl: None, is_group_to_choice_enum: false, is_multi_type_choice: false, is_multi_group_choice: false, type_group_name_entry: None, advance_to_next_entry: false, is_ctrl_map_equality: false, entry_counts: None, validated_keys: None, values_to_validate: None, valid_array_items: None, array_errors: None, is_colon_shortcut_present: false, is_root: false, is_multi_type_choice_type_rule_validating_array: false, enabled_features, has_feature_errors: false, disabled_features: None, } } #[cfg(target_arch = "wasm32")] #[cfg(not(feature = "additional-controls"))] /// New JSONValidation from CDDL AST and JSON value pub fn new(cddl: &'a CDDL<'a>, json: Value) -> Self { JSONValidator { cddl, json, errors: Vec::default(), cddl_location: String::new(), json_location: String::new(), occurrence: None, group_entry_idx: None, object_value: None, is_member_key: false, is_cut_present: false, cut_value: None, eval_generic_rule: None, generic_rules: Vec::new(), ctrl: None, is_group_to_choice_enum: false, is_multi_type_choice: false, is_multi_group_choice: false, type_group_name_entry: None, advance_to_next_entry: false, is_ctrl_map_equality: false, entry_counts: None, validated_keys: None, values_to_validate: None, valid_array_items: None, array_errors: None, is_colon_shortcut_present: false, is_root: false, is_multi_type_choice_type_rule_validating_array: false, } } fn validate_array_items(&mut self, token: &ArrayItemToken) -> visitor::Result<Error> { if let Value::Array(a) = &self.json { // Member keys are annotation only in an array context if self.is_member_key { return Ok(()); } match validate_array_occurrence( self.occurrence.as_ref(), self.entry_counts.as_ref().map(|ec| &ec[..]), a, ) { Ok((iter_items, allow_empty_array)) => { if iter_items { for (idx, v) in a.iter().enumerate() { if let Some(indices) = &self.valid_array_items { if self.is_multi_type_choice && indices.contains(&idx) { continue; } } #[cfg(all(feature = "additional-controls", target_arch = "wasm32"))] let mut jv = JSONValidator::new(self.cddl, v.clone(), self.enabled_features.clone()); #[cfg(all(feature = "additional-controls", not(target_arch = "wasm32")))] let mut jv = JSONValidator::new(self.cddl, v.clone(), self.enabled_features); #[cfg(not(feature = "additional-controls"))] let mut jv = JSONValidator::new(self.cddl, v.clone()); jv.generic_rules = self.generic_rules.clone(); jv.eval_generic_rule = self.eval_generic_rule; jv.is_multi_type_choice = self.is_multi_type_choice; jv.ctrl = self.ctrl; let _ = write!(jv.json_location, "{}/{}", self.json_location, idx); match token { ArrayItemToken::Value(value) => jv.visit_value(value)?, ArrayItemToken::Range(lower, upper, is_inclusive) => { jv.visit_range(lower, upper, *is_inclusive)? } ArrayItemToken::Group(group) => jv.visit_group(group)?, ArrayItemToken::Identifier(ident) => jv.visit_identifier(ident)?, _ => (), } if self.is_multi_type_choice && jv.errors.is_empty() { if let Some(indices) = &mut self.valid_array_items { indices.push(idx); } else { self.valid_array_items = Some(vec![idx]); } continue; } if let Some(errors) = &mut self.array_errors { if let Some(error) = errors.get_mut(&idx) { error.append(&mut jv.errors); } else { errors.insert(idx, jv.errors); } } else { let mut errors = HashMap::new(); errors.insert(idx, jv.errors); self.array_errors = Some(errors) } } } else if let Some(idx) = self.group_entry_idx { if let Some(v) = a.get(idx) { #[cfg(all(feature = "additional-controls", target_arch = "wasm32"))] let mut jv = JSONValidator::new(self.cddl, v.clone(), self.enabled_features.clone()); #[cfg(all(feature = "additional-controls", not(target_arch = "wasm32")))] let mut jv = JSONValidator::new(self.cddl, v.clone(), self.enabled_features); #[cfg(not(feature = "additional-controls"))] let mut jv = JSONValidator::new(self.cddl, v.clone()); jv.generic_rules = self.generic_rules.clone(); jv.eval_generic_rule = self.eval_generic_rule; jv.is_multi_type_choice = self.is_multi_type_choice; jv.ctrl = self.ctrl; let _ = write!(jv.json_location, "{}/{}", self.json_location, idx); match token { ArrayItemToken::Value(value) => jv.visit_value(value)?, ArrayItemToken::Range(lower, upper, is_inclusive) => { jv.visit_range(lower, upper, *is_inclusive)? } ArrayItemToken::Group(group) => jv.visit_group(group)?, ArrayItemToken::Identifier(ident) => jv.visit_identifier(ident)?, _ => (), } self.errors.append(&mut jv.errors); } else if !allow_empty_array { self.add_error(token.error_msg(Some(idx))); } } else if !self.is_multi_type_choice { self.add_error(format!("{}, got {}", token.error_msg(None), self.json)); } } Err(errors) => { for e in errors.into_iter() { self.add_error(e); } } } } Ok(()) } fn validate_object_value(&mut self, value: &token::Value<'a>) -> visitor::Result<Error> { if let Value::Object(o) = &self.json { // Bareword member keys are converted to text string values if let token::Value::TEXT(t) = value { if self.is_cut_present { self.cut_value = Some(t.clone()); } if *t == "any" { return Ok(()); } // Retrieve the value from key unless optional/zero or more, in which // case advance to next group entry #[cfg(feature = "ast-span")] if let Some(v) = o.get(t.as_ref()) { self .validated_keys .get_or_insert(vec![t.to_string()]) .push(t.to_string()); self.object_value = Some(v.clone()); let _ = write!(self.json_location, "/{}", t); return Ok(()); } else if let Some(Occur::Optional { .. }) | Some(Occur::ZeroOrMore { .. }) = &self.occurrence.take() { self.advance_to_next_entry = true; return Ok(()); } else if let Some(ControlOperator::NE) | Some(ControlOperator::DEFAULT) = &self.ctrl { return Ok(()); } else { self.add_error(format!("object missing key: \"{}\"", t)) } // Retrieve the value from key unless optional/zero or more, in which // case advance to next group entry #[cfg(not(feature = "ast-span"))] if let Some(v) = o.get(t.as_ref()) { self .validated_keys .get_or_insert(vec![t.to_string()]) .push(t.to_string()); self.object_value = Some(v.clone()); self.json_location.push_str(&format!("/{}", t)); return Ok(()); } else if let Some(Occur::Optional {}) | Some(Occur::ZeroOrMore {}) = &self.occurrence.take() { self.advance_to_next_entry = true; return Ok(()); } else if let Some(Token::NE) | Some(Token::DEFAULT) = &self.ctrl { return Ok(()); } else { self.add_error(format!("object missing key: \"{}\"", t)) } } else { self.add_error(format!( "CDDL member key must be string data type. got {}", value )) } } Ok(()) } } impl<'a, 'b> Validator<'a, 'b, Error> for JSONValidator<'a> { /// Validate fn validate(&mut self) -> std::result::Result<(), Error> { for r in self.cddl.rules.iter() { // First type rule is root if let Rule::Type { rule, .. } = r { if rule.generic_params.is_none() { self.is_root = true; self.visit_type_rule(rule)?; self.is_root = false; break; } } } if !self.errors.is_empty() { return Err(Error::Validation(self.errors.clone())); } Ok(()) } fn add_error(&mut self, reason: String) { self.errors.push(ValidationError { reason, cddl_location: self.cddl_location.clone(), json_location: self.json_location.clone(), is_multi_type_choice: self.is_multi_type_choice, is_multi_group_choice: self.is_multi_group_choice, is_group_to_choice_enum: self.is_group_to_choice_enum, type_group_name_entry: self.type_group_name_entry.map(|e| e.to_string()), }); } } impl<'a, 'b> Visitor<'a, 'b, Error> for JSONValidator<'a> { fn visit_type_rule(&mut self, tr: &TypeRule<'a>) -> visitor::Result<Error> { if let Some(gp) = &tr.generic_params { if let Some(gr) = self .generic_rules .iter_mut() .find(|r| r.name == tr.name.ident) { gr.params = gp.params.iter().map(|p| p.param.ident).collect(); } else { self.generic_rules.push(GenericRule { name: tr.name.ident, params: gp.params.iter().map(|p| p.param.ident).collect(), args: vec![], }); } } let type_choice_alternates = type_choice_alternates_from_ident(self.cddl, &tr.name); if !type_choice_alternates.is_empty() { self.is_multi_type_choice = true; if self.json.is_array() { self.is_multi_type_choice_type_rule_validating_array = true; } } let error_count = self.errors.len(); for t in type_choice_alternates { let cur_errors = self.errors.len(); self.visit_type(t)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } return Ok(()); } } if tr.value.type_choices.len() > 1 && self.json.is_array() { self.is_multi_type_choice_type_rule_validating_array = true; } self.visit_type(&tr.value) } fn visit_group_rule(&mut self, gr: &GroupRule<'a>) -> visitor::Result<Error> { if let Some(gp) = &gr.generic_params { if let Some(gr) = self .generic_rules .iter_mut() .find(|r| r.name == gr.name.ident) { gr.params = gp.params.iter().map(|p| p.param.ident).collect(); } else { self.generic_rules.push(GenericRule { name: gr.name.ident, params: gp.params.iter().map(|p| p.param.ident).collect(), args: vec![], }); } } let group_choice_alternates = group_choice_alternates_from_ident(self.cddl, &gr.name); if !group_choice_alternates.is_empty() { self.is_multi_group_choice = true; } let error_count = self.errors.len(); for ge in group_choice_alternates { let cur_errors = self.errors.len(); self.visit_group_entry(ge)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } return Ok(()); } } self.visit_group_entry(&gr.entry) } fn visit_type(&mut self, t: &Type<'a>) -> visitor::Result<Error> { if t.type_choices.len() > 1 { self.is_multi_type_choice = true; } let initial_error_count = self.errors.len(); for type_choice in t.type_choices.iter() { // If validating an array whose elements are type choices (i.e. [ 1* tstr // / integer ]), collect all errors and filter after the fact if matches!(self.json, Value::Array(_)) && !self.is_multi_type_choice_type_rule_validating_array { let error_count = self.errors.len(); self.visit_type_choice(type_choice)?; #[cfg(feature = "additional-controls")] if self.errors.len() == error_count && !self.has_feature_errors && self.disabled_features.is_none() { // Disregard invalid type choice validation errors if one of the // choices validates successfully let type_choice_error_count = self.errors.len() - initial_error_count; if type_choice_error_count > 0 { for _ in 0..type_choice_error_count { self.errors.pop(); } } } #[cfg(not(feature = "additional-controls"))] if self.errors.len() == error_count { // Disregard invalid type choice validation errors if one of the // choices validates successfully let type_choice_error_count = self.errors.len() - initial_error_count; if type_choice_error_count > 0 { for _ in 0..type_choice_error_count { self.errors.pop(); } } } continue; } let error_count = self.errors.len(); self.visit_type_choice(type_choice)?; #[cfg(feature = "additional-controls")] if self.errors.len() == error_count && !self.has_feature_errors && self.disabled_features.is_none() { // Disregard invalid type choice validation errors if one of the // choices validates successfully let type_choice_error_count = self.errors.len() - initial_error_count; if type_choice_error_count > 0 { for _ in 0..type_choice_error_count { self.errors.pop(); } } return Ok(()); } #[cfg(not(feature = "additional-controls"))] if self.errors.len() == error_count { // Disregard invalid type choice validation errors if one of the // choices validates successfully let type_choice_error_count = self.errors.len() - initial_error_count; if type_choice_error_count > 0 { for _ in 0..type_choice_error_count { self.errors.pop(); } } return Ok(()); } } Ok(()) } fn visit_group(&mut self, g: &Group<'a>) -> visitor::Result<Error> { if g.group_choices.len() > 1 { self.is_multi_group_choice = true; } // Map equality/inequality validation if self.is_ctrl_map_equality { if let Some(t) = &self.ctrl { if let Value::Object(o) = &self.json { let entry_counts = entry_counts_from_group(self.cddl, g); let len = o.len(); if let ControlOperator::EQ = t { if !validate_entry_count(&entry_counts, len) { for ec in entry_counts.iter() { if let Some(occur) = &ec.entry_occurrence { self.add_error(format!( "map equality error. expected object with number of entries per occurrence {}", occur, )); } else { self.add_error(format!( "map equality error, expected object with length {}, got {}", ec.count, len )); } } return Ok(()); } } else if let ControlOperator::NE | ControlOperator::DEFAULT = t { if !validate_entry_count(&entry_counts, len) { for ec in entry_counts.iter() { if let Some(occur) = &ec.entry_occurrence { self.add_error(format!( "map inequality error. expected object with number of entries not per occurrence {}", occur, )); } else { self.add_error(format!( "map inequality error, expected object not with length {}, got {}", ec.count, len )); } } return Ok(()); } } } } } self.is_ctrl_map_equality = false; let initial_error_count = self.errors.len(); for group_choice in g.group_choices.iter() { let error_count = self.errors.len(); self.visit_group_choice(group_choice)?; if self.errors.len() == error_count { // Disregard invalid group choice validation errors if one of the // choices validates successfully let group_choice_error_count = self.errors.len() - initial_error_count; if group_choice_error_count > 0 { for _ in 0..group_choice_error_count { self.errors.pop(); } } return Ok(()); } } Ok(()) } fn visit_group_choice(&mut self, gc: &GroupChoice<'a>) -> visitor::Result<Error> { if self.is_group_to_choice_enum { let initial_error_count = self.errors.len(); for tc in type_choices_from_group_choice(self.cddl, gc).iter() { let error_count = self.errors.len(); self.visit_type_choice(tc)?; if self.errors.len() == error_count { let type_choice_error_count = self.errors.len() - initial_error_count; if type_choice_error_count > 0 { for _ in 0..type_choice_error_count { self.errors.pop(); } } return Ok(()); } } return Ok(()); } for (idx, ge) in gc.group_entries.iter().enumerate() { if let Some(current_index) = self.group_entry_idx.as_mut() { if idx != 0 { *current_index += 1; } } else { self.group_entry_idx = Some(idx); } self.visit_group_entry(&ge.0)?; } Ok(()) } fn visit_range( &mut self, lower: &Type2, upper: &Type2, is_inclusive: bool, ) -> visitor::Result<Error> { if matches!(&self.json, Value::Array(_)) { return self.validate_array_items(&ArrayItemToken::Range(lower, upper, is_inclusive)); } match lower { Type2::IntValue { value: l, .. } => match upper { Type2::IntValue { value: u, .. } => { let error_str = if is_inclusive { format!( "expected integer to be in range {} <= value <= {}, got {}", l, u, self.json ) } else { format!( "expected integer to be in range {} < value < {}, got {}", l, u, self.json ) }; match &self.json { Value::Number(n) => { if let Some(i) = n.as_i64() { if is_inclusive { if i < *l as i64 || i > *u as i64 { self.add_error(error_str); } else { return Ok(()); } } else if i <= *l as i64 || i >= *u as i64 { self.add_error(error_str); return Ok(()); } else { return Ok(()); } } else { self.add_error(error_str); return Ok(()); } } _ => { self.add_error(error_str); return Ok(()); } } } Type2::UintValue { value: u, .. } => { let error_str = if is_inclusive { format!( "expected integer to be in range {} <= value <= {}, got {}", l, u, self.json ) } else { format!( "expected integer to be in range {} < value < {}, got {}", l, u, self.json ) }; match &self.json { Value::Number(n) => { if let Some(i) = n.as_i64() { if is_inclusive { if i < *l as i64 || i > *u as i64 { self.add_error(error_str); } else { return Ok(()); } } else if i <= *l as i64 || i >= *u as i64 { self.add_error(error_str); return Ok(()); } else { return Ok(()); } } else { self.add_error(error_str); return Ok(()); } } _ => { self.add_error(error_str); return Ok(()); } } } _ => { self.add_error(format!( "invalid cddl range. upper value must be an integer type. got {}", upper )); return Ok(()); } }, Type2::UintValue { value: l, .. } => match upper { Type2::UintValue { value: u, .. } => { let error_str = if is_inclusive { format!( "expected uint to be in range {} <= value <= {}, got {}", l, u, self.json ) } else { format!( "expected uint to be in range {} < value < {}, got {}", l, u, self.json ) }; match &self.json { Value::Number(n) => { if let Some(i) = n.as_u64() { if is_inclusive { if i < *l as u64 || i > *u as u64 { self.add_error(error_str); } else { return Ok(()); } } else if i <= *l as u64 || i >= *u as u64 { self.add_error(error_str); return Ok(()); } else { return Ok(()); } } else { self.add_error(error_str); return Ok(()); } } Value::String(s) => match self.ctrl { Some(ControlOperator::SIZE) => { let len = s.len(); let s = s.clone(); if is_inclusive { if s.len() < *l || s.len() > *u { self.add_error(format!( "expected \"{}\" string length to be in the range {} <= value <= {}, got {}", s, l, u, len )); } return Ok(()); } else if s.len() <= *l || s.len() >= *u { self.add_error(format!( "expected \"{}\" string length to be in the range {} < value < {}, got {}", s, l, u, len )); return Ok(()); } } _ => { self.add_error("string value cannot be validated against a range without the .size control operator".to_string()); return Ok(()); } }, _ => { self.add_error(error_str); return Ok(()); } } } _ => { self.add_error(format!( "invalid cddl range. upper value must be a uint type. got {}", upper )); return Ok(()); } }, Type2::FloatValue { value: l, .. } => match upper { Type2::FloatValue { value: u, .. } => { let error_str = if is_inclusive { format!( "expected float to be in range {} <= value <= {}, got {}", l, u, self.json ) } else { format!( "expected float to be in range {} < value < {}, got {}", l, u, self.json ) }; match &self.json { Value::Number(n) => { if let Some(f) = n.as_f64() { if is_inclusive { if f < *l || f > *u { self.add_error(error_str); } else { return Ok(()); } } else if f <= *l || f >= *u { self.add_error(error_str); return Ok(()); } else { return Ok(()); } } else { self.add_error(error_str); return Ok(()); } } _ => { self.add_error(error_str); return Ok(()); } } } _ => { self.add_error(format!( "invalid cddl range. upper value must be a float type. got {}", upper )); return Ok(()); } }, _ => { self.add_error( "invalid cddl range. upper and lower values must be either integers or floats" .to_string(), ); return Ok(()); } } Ok(()) } fn visit_control_operator( &mut self, target: &Type2<'a>, ctrl: ControlOperator, controller: &Type2<'a>, ) -> visitor::Result<Error> { if let Type2::Typename { ident: target_ident, .. } = target { if let Type2::Typename { ident: controller_ident, .. } = controller { if let Some(name) = self.eval_generic_rule { if let Some(gr) = self .generic_rules .iter() .cloned() .find(|gr| gr.name == name) { for (idx, gp) in gr.params.iter().enumerate() { if let Some(arg) = gr.args.get(idx) { if *gp == target_ident.ident { let t2 = Type2::from(arg.clone()); if *gp == controller_ident.ident { return self.visit_control_operator(&t2, ctrl, &t2); } return self.visit_control_operator(&arg.type2, ctrl, controller); } } } } } } if let Some(name) = self.eval_generic_rule { if let Some(gr) = self .generic_rules .iter() .cloned() .find(|gr| gr.name == name) { for (idx, gp) in gr.params.iter().enumerate() { if let Some(arg) = gr.args.get(idx) { if *gp == target_ident.ident { let t2 = Type2::from(arg.clone()); return self.visit_control_operator(&t2, ctrl, controller); } } } } } } match ctrl { ControlOperator::EQ => match target { Type2::Typename { ident, .. } => { if is_ident_string_data_type(self.cddl, ident) || is_ident_numeric_data_type(self.cddl, ident) { return self.visit_type2(controller); } } Type2::Array { group, .. } => { if let Value::Array(_) = &self.json { self.entry_counts = Some(entry_counts_from_group(self.cddl, group)); self.visit_type2(controller)?; self.entry_counts = None; return Ok(()); } } Type2::Map { .. } => { if let Value::Object(_) = &self.json { self.ctrl = Some(ctrl); self.is_ctrl_map_equality = true; self.visit_type2(controller)?; self.ctrl = None; self.is_ctrl_map_equality = false; return Ok(()); } } _ => self.add_error(format!( "target for .eq operator must be a string, numerical, array or map data type, got {}", target )), }, ControlOperator::NE => match target { Type2::Typename { ident, .. } => { if is_ident_string_data_type(self.cddl, ident) || is_ident_numeric_data_type(self.cddl, ident) { self.ctrl = Some(ctrl); self.visit_type2(controller)?; self.ctrl = None; return Ok(()); } } Type2::Array { .. } => { if let Value::Array(_) = &self.json { self.ctrl = Some(ctrl); self.visit_type2(controller)?; self.ctrl = None; return Ok(()); } } Type2::Map { .. } => { if let Value::Object(_) = &self.json { self.ctrl = Some(ctrl); self.is_ctrl_map_equality = true; self.visit_type2(controller)?; self.ctrl = None; self.is_ctrl_map_equality = false; return Ok(()); } } _ => self.add_error(format!( "target for .ne operator must be a string, numerical, array or map data type, got {}", target )), }, ControlOperator::LT | ControlOperator::GT | ControlOperator::GE | ControlOperator::LE => { match target { Type2::Typename { ident, .. } if is_ident_numeric_data_type(self.cddl, ident) => { self.ctrl = Some(ctrl); self.visit_type2(controller)?; self.ctrl = None; } _ => { self.add_error(format!( "target for .lt, .gt, .ge or .le operator must be a numerical data type, got {}", target )); } } } ControlOperator::SIZE => match target { Type2::Typename { ident, .. } if is_ident_string_data_type(self.cddl, ident) || is_ident_uint_data_type(self.cddl, ident) => { self.ctrl = Some(ctrl); self.visit_type2(controller)?; self.ctrl = None; } _ => { self.add_error(format!( "target for .size must a string or uint data type, got {}", target )); } }, ControlOperator::AND => { self.ctrl = Some(ctrl); self.visit_type2(target)?; self.visit_type2(controller)?; self.ctrl = None; } ControlOperator::WITHIN => { self.ctrl = Some(ctrl); let error_count = self.errors.len(); self.visit_type2(target)?; let no_errors = self.errors.len() == error_count; self.visit_type2(controller)?; if no_errors && self.errors.len() > error_count { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } self.add_error(format!( "expected type {} .within type {}, got {}", target, controller, self.json, )); } self.ctrl = None; } ControlOperator::DEFAULT => { self.ctrl = Some(ctrl); let error_count = self.errors.len(); self.visit_type2(target)?; if self.errors.len() != error_count { #[cfg(feature = "ast-span")] if let Some(Occur::Optional { .. }) = self.occurrence.take() { self.add_error(format!( "expected default value {}, got {}", controller, self.json )); } #[cfg(not(feature = "ast-span"))] if let Some(Occur::Optional {}) = self.occurrence.take() { self.add_error(format!( "expected default value {}, got {}", controller, self.json )); } } self.ctrl = None; } ControlOperator::REGEXP | ControlOperator::PCRE => { self.ctrl = Some(ctrl); match target { Type2::Typename { ident, .. } if is_ident_string_data_type(self.cddl, ident) => { match self.json { Value::String(_) | Value::Array(_) => self.visit_type2(controller)?, _ => self.add_error(format!( ".regexp/.pcre control can only be matched against JSON string, got {}", self.json )), } } _ => self.add_error(format!( ".regexp/.pcre control can only be matched against string data type, got {}", target )), } self.ctrl = None; } #[cfg(feature = "additional-controls")] ControlOperator::CAT => { self.ctrl = Some(ctrl); match cat_operation(self.cddl, target, controller, false) { Ok(values) => { let error_count = self.errors.len(); for v in values.iter() { let cur_errors = self.errors.len(); self.visit_type2(v)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } break; } } } Err(e) => self.add_error(e), } self.ctrl = None; } #[cfg(feature = "additional-controls")] ControlOperator::DET => { self.ctrl = Some(ctrl); match cat_operation(self.cddl, target, controller, true) { Ok(values) => { let error_count = self.errors.len(); for v in values.iter() { let cur_errors = self.errors.len(); self.visit_type2(v)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } break; } } } Err(e) => self.add_error(e), } self.ctrl = None; } #[cfg(feature = "additional-controls")] ControlOperator::PLUS => { self.ctrl = Some(ctrl); match plus_operation(self.cddl, target, controller) { Ok(values) => { let error_count = self.errors.len(); for v in values.iter() { let cur_errors = self.errors.len(); self.visit_type2(v)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } break; } } } Err(e) => self.add_error(e), } self.ctrl = None; } #[cfg(feature = "additional-controls")] ControlOperator::ABNF => { self.ctrl = Some(ctrl); match target { Type2::Typename { ident, .. } if is_ident_string_data_type(self.cddl, ident) => { match self.json { Value::String(_) | Value::Array(_) => { if let Type2::ParenthesizedType { pt, .. } = controller { match abnf_from_complex_controller(self.cddl, pt) { Ok(values) => { let error_count = self.errors.len(); for v in values.iter() { let cur_errors = self.errors.len(); self.visit_type2(v)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } break; } } } Err(e) => self.add_error(e), } } else { self.visit_type2(controller)? } } _ => self.add_error(format!( ".abnf control can only be matched against a JSON string, got {}", self.json, )), } } _ => self.add_error(format!( ".abnf can only be matched against string data type, got {}", target, )), } self.ctrl = None; } #[cfg(feature = "additional-controls")] #[cfg(not(target_arch = "wasm32"))] ControlOperator::FEATURE => { self.ctrl = Some(ctrl); if let Some(ef) = self.enabled_features { let tv = text_value_from_type2(self.cddl, controller); if let Some(Type2::TextValue { value, .. }) = tv { if ef.contains(&&**value) { let err_count = self.errors.len(); self.visit_type2(target)?; if self.errors.len() > err_count { self.has_feature_errors = true; } self.ctrl = None; } else { self .disabled_features .get_or_insert(vec![value.to_string()]) .push(value.to_string()); } } else if let Some(Type2::UTF8ByteString { value, .. }) = tv { let value = std::str::from_utf8(value).map_err(Error::UTF8Parsing)?; if ef.contains(&value) { let err_count = self.errors.len(); self.visit_type2(target)?; if self.errors.len() > err_count { self.has_feature_errors = true; } self.ctrl = None; } else { self .disabled_features .get_or_insert(vec![value.to_string()]) .push(value.to_string()); } } } self.ctrl = None; } #[cfg(feature = "additional-controls")] #[cfg(target_arch = "wasm32")] ControlOperator::FEATURE => { self.ctrl = Some(ctrl); if let Some(ef) = &self.enabled_features { let tv = text_value_from_type2(self.cddl, controller); if let Some(Type2::TextValue { value, .. }) = tv { if ef.contains(&JsValue::from(value.as_ref())) { let err_count = self.errors.len(); self.visit_type2(target)?; if self.errors.len() > err_count { self.has_feature_errors = true; } self.ctrl = None; } else { self .disabled_features .get_or_insert(vec![value.to_string()]) .push(value.to_string()); } } else if let Some(Type2::UTF8ByteString { value, .. }) = tv { let value = std::str::from_utf8(value).map_err(Error::UTF8Parsing)?; if ef.contains(&JsValue::from(value)) { let err_count = self.errors.len(); self.visit_type2(target)?; if self.errors.len() > err_count { self.has_feature_errors = true; } self.ctrl = None; } else { self .disabled_features .get_or_insert(vec![value.to_string()]) .push(value.to_string()); } } } self.ctrl = None; } _ => { self.add_error(format!("unsupported control operator {}", ctrl)); } } Ok(()) } fn visit_type2(&mut self, t2: &Type2<'a>) -> visitor::Result<Error> { match t2 { Type2::TextValue { value, .. } => self.visit_value(&token::Value::TEXT(value.clone())), Type2::Map { group, .. } => match &self.json { Value::Object(o) => { #[allow(clippy::needless_collect)] let o = o.keys().cloned().collect::<Vec<_>>(); self.visit_group(group)?; if self.values_to_validate.is_none() { for k in o.into_iter() { if let Some(keys) = &self.validated_keys { if !keys.contains(&k) { self.add_error(format!("unexpected key {:?}", k)); } } } } self.is_cut_present = false; self.cut_value = None; Ok(()) } Value::Array(_) => self.validate_array_items(&ArrayItemToken::Group(group)), _ => { self.add_error(format!("expected map object {}, got {}", t2, self.json)); Ok(()) } }, Type2::Array { group, .. } => match &self.json { Value::Array(a) => { if group.group_choices.len() == 1 && group.group_choices[0].group_entries.is_empty() && !a.is_empty() && !matches!( self.ctrl, Some(ControlOperator::NE) | Some(ControlOperator::DEFAULT) ) { self.add_error(format!("expected empty array, got {}", self.json)); return Ok(()); } self.entry_counts = Some(entry_counts_from_group(self.cddl, group)); self.visit_group(group)?; self.entry_counts = None; if let Some(errors) = &mut self.array_errors { if let Some(indices) = &self.valid_array_items { for idx in indices.iter() { errors.remove(idx); } } for error in errors.values_mut() { self.errors.append(error); } } self.valid_array_items = None; self.array_errors = None; Ok(()) } _ => { self.add_error(format!("expected array type, got {}", self.json)); Ok(()) } }, Type2::ChoiceFromGroup { ident, generic_args, .. } => { if let Some(ga) = generic_args { if let Some(rule) = rule_from_ident(self.cddl, ident) { if let Some(gr) = self .generic_rules .iter_mut() .find(|gr| gr.name == ident.ident) { for arg in ga.args.iter() { gr.args.push((*arg.arg).clone()); } } else if let Some(params) = generic_params_from_rule(rule) { self.generic_rules.push(GenericRule { name: ident.ident, params, args: ga.args.iter().cloned().map(|arg| *arg.arg).collect(), }); } #[cfg(all(feature = "additional-controls", target_arch = "wasm32"))] let mut jv = JSONValidator::new(self.cddl, self.json.clone(), self.enabled_features.clone()); #[cfg(all(feature = "additional-controls", not(target_arch = "wasm32")))] let mut jv = JSONValidator::new(self.cddl, self.json.clone(), self.enabled_features); #[cfg(not(feature = "additional-controls"))] let mut jv = JSONValidator::new(self.cddl, self.json.clone()); jv.generic_rules = self.generic_rules.clone(); jv.eval_generic_rule = Some(ident.ident); jv.is_group_to_choice_enum = true; jv.is_multi_type_choice = self.is_multi_type_choice; jv.visit_rule(rule)?; self.errors.append(&mut jv.errors); return Ok(()); } } if group_rule_from_ident(self.cddl, ident).is_none() { self.add_error(format!( "rule {} must be a group rule to turn it into a choice", ident )); return Ok(()); } self.is_group_to_choice_enum = true; self.visit_identifier(ident)?; self.is_group_to_choice_enum = false; Ok(()) } Type2::ChoiceFromInlineGroup { group, .. } => { self.is_group_to_choice_enum = true; self.visit_group(group)?; self.is_group_to_choice_enum = false; Ok(()) } Type2::Typename { ident, generic_args, .. } => { if let Some(ga) = generic_args { if let Some(rule) = rule_from_ident(self.cddl, ident) { if let Some(gr) = self .generic_rules .iter_mut() .find(|gr| gr.name == ident.ident) { for arg in ga.args.iter() { gr.args.push((*arg.arg).clone()); } } else if let Some(params) = generic_params_from_rule(rule) { self.generic_rules.push(GenericRule { name: ident.ident, params, args: ga.args.iter().cloned().map(|arg| *arg.arg).collect(), }); } #[cfg(all(feature = "additional-controls", target_arch = "wasm32"))] let mut jv = JSONValidator::new(self.cddl, self.json.clone(), self.enabled_features.clone()); #[cfg(all(feature = "additional-controls", not(target_arch = "wasm32")))] let mut jv = JSONValidator::new(self.cddl, self.json.clone(), self.enabled_features); #[cfg(not(feature = "additional-controls"))] let mut jv = JSONValidator::new(self.cddl, self.json.clone()); jv.generic_rules = self.generic_rules.clone(); jv.eval_generic_rule = Some(ident.ident); jv.is_multi_type_choice = self.is_multi_type_choice; jv.visit_rule(rule)?; self.errors.append(&mut jv.errors); return Ok(()); } } let type_choice_alternates = type_choice_alternates_from_ident(self.cddl, ident); if !type_choice_alternates.is_empty() { self.is_multi_type_choice = true; } let error_count = self.errors.len(); for t in type_choice_alternates { let cur_errors = self.errors.len(); self.visit_type(t)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } return Ok(()); } } self.visit_identifier(ident) } Type2::IntValue { value, .. } => self.visit_value(&token::Value::INT(*value)), Type2::UintValue { value, .. } => self.visit_value(&token::Value::UINT(*value)), Type2::FloatValue { value, .. } => self.visit_value(&token::Value::FLOAT(*value)), Type2::ParenthesizedType { pt, .. } => self.visit_type(pt), Type2::Unwrap { ident, generic_args, .. } => { // Per // https://github.com/w3c/did-spec-registries/pull/138#issuecomment-719739215, // strip tag and validate underlying type if let Some(Type2::TaggedData { t, .. }) = tag_from_token(&lookup_ident(ident.ident)) { return self.visit_type(&t); } if let Some(ga) = generic_args { if let Some(rule) = unwrap_rule_from_ident(self.cddl, ident) { if let Some(gr) = self .generic_rules .iter_mut() .find(|gr| gr.name == ident.ident) { for arg in ga.args.iter() { gr.args.push((*arg.arg).clone()); } } else if let Some(params) = generic_params_from_rule(rule) { self.generic_rules.push(GenericRule { name: ident.ident, params, args: ga.args.iter().cloned().map(|arg| *arg.arg).collect(), }); } #[cfg(all(feature = "additional-controls", target_arch = "wasm32"))] let mut jv = JSONValidator::new(self.cddl, self.json.clone(), self.enabled_features.clone()); #[cfg(all(feature = "additional-controls", not(target_arch = "wasm32")))] let mut jv = JSONValidator::new(self.cddl, self.json.clone(), self.enabled_features); #[cfg(not(feature = "additional-controls"))] let mut jv = JSONValidator::new(self.cddl, self.json.clone()); jv.generic_rules = self.generic_rules.clone(); jv.eval_generic_rule = Some(ident.ident); jv.is_multi_type_choice = self.is_multi_type_choice; jv.visit_rule(rule)?; self.errors.append(&mut jv.errors); return Ok(()); } } if let Some(rule) = unwrap_rule_from_ident(self.cddl, ident) { return self.visit_rule(rule); } self.add_error(format!( "cannot unwrap identifier {}, rule not found", ident )); Ok(()) } #[cfg(feature = "ast-span")] Type2::Any { .. } => Ok(()), #[cfg(not(feature = "ast-span"))] Type2::Any {} => Ok(()), _ => { self.add_error(format!( "unsupported data type for validating JSON, got {}", t2 )); Ok(()) } } } fn visit_identifier(&mut self, ident: &Identifier<'a>) -> visitor::Result<Error> { if let Some(name) = self.eval_generic_rule { if let Some(gr) = self .generic_rules .iter() .cloned() .find(|gr| gr.name == name) { for (idx, gp) in gr.params.iter().enumerate() { if *gp == ident.ident { if let Some(arg) = gr.args.get(idx) { return self.visit_type1(arg); } } } } } // self.is_colon_shortcut_present is only true when the ident is part of a // member key if !self.is_colon_shortcut_present { if let Some(r) = rule_from_ident(self.cddl, ident) { return self.visit_rule(r); } } if is_ident_any_type(self.cddl, ident) { return Ok(()); } match &self.json { Value::Null if is_ident_null_data_type(self.cddl, ident) => Ok(()), Value::Bool(b) => { if is_ident_bool_data_type(self.cddl, ident) { return Ok(()); } if ident_matches_bool_value(self.cddl, ident, *b) { return Ok(()); } self.add_error(format!("expected type {}, got {}", ident, self.json)); Ok(()) } Value::Number(n) => { if is_ident_uint_data_type(self.cddl, ident) && n.is_u64() { return Ok(()); } else if is_ident_nint_data_type(self.cddl, ident) { if let Some(n) = n.as_i64() { if n.is_negative() { return Ok(()); } } } else if is_ident_time_data_type(self.cddl, ident) { if let Some(n) = n.as_i64() { if let chrono::LocalResult::None = Utc.timestamp_millis_opt(n * 1000) { self.add_error(format!( "expected time data type, invalid UNIX timestamp {}", n, )); } return Ok(()); } else if let Some(n) = n.as_f64() { // truncates fractional milliseconds when validating if let chrono::LocalResult::None = Utc.timestamp_millis_opt((n * 1000f64) as i64) { self.add_error(format!( "expected time data type, invalid UNIX timestamp {}", n, )); } } } else if (is_ident_integer_data_type(self.cddl, ident) && n.is_i64()) || (is_ident_float_data_type(self.cddl, ident) && n.is_f64()) { return Ok(()); } self.add_error(format!("expected type {}, got {}", ident, self.json)); Ok(()) } Value::String(s) => { if is_ident_uri_data_type(self.cddl, ident) { if let Err(e) = uriparse::URI::try_from(&**s) { self.add_error(format!("expected URI data type, decoding error: {}", e)); } } else if is_ident_b64url_data_type(self.cddl, ident) { if let Err(e) = base64_url::decode(s) { self.add_error(format!( "expected base64 URL data type, decoding error: {}", e )); } } else if is_ident_tdate_data_type(self.cddl, ident) { if let Err(e) = chrono::DateTime::parse_from_rfc3339(s) { self.add_error(format!("expected tdate data type, decoding error: {}", e)); } } else if is_ident_string_data_type(self.cddl, ident) { return Ok(()); } else { self.add_error(format!("expected type {}, got {}", ident, self.json)); } Ok(()) } Value::Array(_) => self.validate_array_items(&ArrayItemToken::Identifier(ident)), Value::Object(o) => match &self.occurrence { #[cfg(feature = "ast-span")] Some(Occur::Optional { .. }) | None => { if token::lookup_ident(ident.ident) .in_standard_prelude() .is_some() { self.add_error(format!( "expected object value of type {}, got object", ident.ident )); return Ok(()); } self.visit_value(&token::Value::TEXT(ident.ident.into())) } #[cfg(not(feature = "ast-span"))] Some(Occur::Optional {}) | None => { if token::lookup_ident(ident.ident) .in_standard_prelude() .is_some() { self.add_error(format!( "expected object value of type {}, got object", ident.ident )); return Ok(()); } self.visit_value(&token::Value::TEXT(ident.ident.into())) } Some(occur) => { if is_ident_string_data_type(self.cddl, ident) { let values_to_validate = o .iter() .filter_map(|(k, v)| match &self.validated_keys { Some(keys) if !keys.contains(k) => Some(v.clone()), Some(_) => None, None => Some(v.clone()), }) .collect::<Vec<_>>(); self.values_to_validate = Some(values_to_validate); } #[cfg(feature = "ast-span")] if let Occur::ZeroOrMore { .. } | Occur::OneOrMore { .. } = occur { if let Occur::OneOrMore { .. } = occur { if o.is_empty() { self.add_error(format!( "object cannot be empty, one or more entries with key type {} required", ident )); return Ok(()); } } } else if let Occur::Exact { lower, upper, .. } = occur { if let Some(values_to_validate) = &self.values_to_validate { if let Some(lower) = lower { if let Some(upper) = upper { if values_to_validate.len() < *lower || values_to_validate.len() > *upper { if lower == upper { self.add_error(format!( "object must contain exactly {} entries of key of type {}", lower, ident, )); } else { self.add_error(format!( "object must contain between {} and {} entries of key of type {}", lower, upper, ident, )); } return Ok(()); } } if values_to_validate.len() < *lower { self.add_error(format!( "object must contain at least {} entries of key of type {}", lower, ident, )); return Ok(()); } } if let Some(upper) = upper { if values_to_validate.len() > *upper { self.add_error(format!( "object must contain no more than {} entries of key of type {}", upper, ident, )); return Ok(()); } } return Ok(()); } } #[cfg(not(feature = "ast-span"))] if let Occur::ZeroOrMore {} | Occur::OneOrMore {} = occur { if let Occur::OneOrMore {} = occur { if o.is_empty() { self.add_error(format!( "object cannot be empty, one or more entries with key type {} required", ident )); return Ok(()); } } } else if let Occur::Exact { lower, upper } = occur { if let Some(values_to_validate) = &self.values_to_validate { if let Some(lower) = lower { if let Some(upper) = upper { if values_to_validate.len() < *lower || values_to_validate.len() > *upper { if lower == upper { self.add_error(format!( "object must contain exactly {} entries of key of type {}", lower, ident, )); } else { self.add_error(format!( "object must contain between {} and {} entries of key of type {}", lower, upper, ident, )); } return Ok(()); } } if values_to_validate.len() < *lower { self.add_error(format!( "object must contain at least {} entries of key of type {}", lower, ident, )); return Ok(()); } } if let Some(upper) = upper { if values_to_validate.len() > *upper { self.add_error(format!( "object must contain no more than {} entries of key of type {}", upper, ident, )); return Ok(()); } } return Ok(()); } } Ok(()) } }, _ => { if let Some(cut_value) = self.cut_value.take() { self.add_error(format!( "cut present for member key {}. expected type {}, got {}", cut_value, ident, self.json )); } else { self.add_error(format!("expected type {}, got {}", ident, self.json)); } Ok(()) } } } fn visit_value_member_key_entry( &mut self, entry: &ValueMemberKeyEntry<'a>, ) -> visitor::Result<Error> { if let Some(occur) = &entry.occur { self.visit_occurrence(occur)?; } let current_location = self.json_location.clone(); if let Some(mk) = &entry.member_key { let error_count = self.errors.len(); self.is_member_key = true; self.visit_memberkey(mk)?; self.is_member_key = false; // Move to next entry if member key validation fails if self.errors.len() != error_count { self.advance_to_next_entry = true; return Ok(()); } } if let Some(values) = &self.values_to_validate { for v in values.iter() { #[cfg(all(feature = "additional-controls", target_arch = "wasm32"))] let mut jv = JSONValidator::new(self.cddl, v.clone(), self.enabled_features.clone()); #[cfg(all(feature = "additional-controls", not(target_arch = "wasm32")))] let mut jv = JSONValidator::new(self.cddl, v.clone(), self.enabled_features); #[cfg(not(feature = "additional-controls"))] let mut jv = JSONValidator::new(self.cddl, v.clone()); jv.generic_rules = self.generic_rules.clone(); jv.eval_generic_rule = self.eval_generic_rule; jv.is_multi_type_choice = self.is_multi_type_choice; jv.is_multi_group_choice = self.is_multi_group_choice; jv.json_location.push_str(&self.json_location); jv.type_group_name_entry = self.type_group_name_entry; jv.visit_type(&entry.entry_type)?; self.json_location = current_location.clone(); self.errors.append(&mut jv.errors); if entry.occur.is_some() { self.occurrence = None; } } return Ok(()); } if let Some(v) = self.object_value.take() { #[cfg(all(feature = "additional-controls", target_arch = "wasm32"))] let mut jv = JSONValidator::new(self.cddl, v, self.enabled_features.clone()); #[cfg(all(feature = "additional-controls", not(target_arch = "wasm32")))] let mut jv = JSONValidator::new(self.cddl, v, self.enabled_features); #[cfg(not(feature = "additional-controls"))] let mut jv = JSONValidator::new(self.cddl, v); jv.generic_rules = self.generic_rules.clone(); jv.eval_generic_rule = self.eval_generic_rule; jv.is_multi_type_choice = self.is_multi_type_choice; jv.is_multi_group_choice = self.is_multi_group_choice; jv.json_location.push_str(&self.json_location); jv.type_group_name_entry = self.type_group_name_entry; jv.visit_type(&entry.entry_type)?; self.json_location = current_location; self.errors.append(&mut jv.errors); if entry.occur.is_some() { self.occurrence = None; } Ok(()) } else if !self.advance_to_next_entry { self.visit_type(&entry.entry_type) } else { Ok(()) } } fn visit_type_groupname_entry( &mut self, entry: &TypeGroupnameEntry<'a>, ) -> visitor::Result<Error> { self.type_group_name_entry = Some(entry.name.ident); if let Some(ga) = &entry.generic_args { if let Some(rule) = rule_from_ident(self.cddl, &entry.name) { if let Some(gr) = self .generic_rules .iter_mut() .find(|gr| gr.name == entry.name.ident) { for arg in ga.args.iter() { gr.args.push((*arg.arg).clone()); } } else if let Some(params) = generic_params_from_rule(rule) { self.generic_rules.push(GenericRule { name: entry.name.ident, params, args: ga.args.iter().cloned().map(|arg| *arg.arg).collect(), }); } #[cfg(all(feature = "additional-controls", target_arch = "wasm32"))] let mut jv = JSONValidator::new(self.cddl, self.json.clone(), self.enabled_features.clone()); #[cfg(all(feature = "additional-controls", not(target_arch = "wasm32")))] let mut jv = JSONValidator::new(self.cddl, self.json.clone(), self.enabled_features); #[cfg(not(feature = "additional-controls"))] let mut jv = JSONValidator::new(self.cddl, self.json.clone()); jv.generic_rules = self.generic_rules.clone(); jv.eval_generic_rule = Some(entry.name.ident); jv.is_multi_type_choice = self.is_multi_type_choice; jv.visit_rule(rule)?; self.errors.append(&mut jv.errors); return Ok(()); } } let type_choice_alternates = type_choice_alternates_from_ident(self.cddl, &entry.name); if !type_choice_alternates.is_empty() { self.is_multi_type_choice = true; } let error_count = self.errors.len(); for t in type_choice_alternates { let cur_errors = self.errors.len(); self.visit_type(t)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } return Ok(()); } } let error_count = self.errors.len(); let group_choice_alternates = group_choice_alternates_from_ident(self.cddl, &entry.name); if !group_choice_alternates.is_empty() { self.is_multi_group_choice = true; } for ge in group_choice_alternates { let cur_errors = self.errors.len(); self.visit_group_entry(ge)?; if self.errors.len() == cur_errors { for _ in 0..self.errors.len() - error_count { self.errors.pop(); } return Ok(()); } } walk_type_groupname_entry(self, entry)?; self.type_group_name_entry = None; Ok(()) } fn visit_memberkey(&mut self, mk: &MemberKey<'a>) -> visitor::Result<Error> { match mk { MemberKey::Type1 { is_cut, .. } => { self.is_cut_present = *is_cut; walk_memberkey(self, mk)?; self.is_cut_present = false; } MemberKey::Bareword { .. } => { self.is_colon_shortcut_present = true; walk_memberkey(self, mk)?; self.is_colon_shortcut_present = false; } _ => return walk_memberkey(self, mk), } Ok(()) } fn visit_value(&mut self, value: &token::Value<'a>) -> visitor::Result<Error> { // FIXME: If during traversal the type being validated is supposed to be a value, // this fails if let Value::Array(_) = &self.json { return self.validate_array_items(&ArrayItemToken::Value(value)); } if let Value::Object(_) = &self.json { return self.validate_object_value(value); } let error: Option<String> = match value { token::Value::INT(v) => match &self.json { Value::Number(n) => match n.as_i64() { Some(i) => match &self.ctrl { Some(ControlOperator::NE) | Some(ControlOperator::DEFAULT) if i != *v as i64 => None, Some(ControlOperator::LT) if i < *v as i64 => None, Some(ControlOperator::LE) if i <= *v as i64 => None, Some(ControlOperator::GT) if i > *v as i64 => None, Some(ControlOperator::GE) if i >= *v as i64 => None, #[cfg(feature = "additional-controls")] Some(ControlOperator::PLUS) => { if i == *v as i64 { None } else { Some(format!("expected computed .plus value {}, got {}", v, n)) } } #[cfg(feature = "additional-controls")] None | Some(ControlOperator::FEATURE) => { if i == *v as i64 { None } else { Some(format!("expected value {}, got {}", v, n)) } } #[cfg(not(feature = "additional-controls"))] None => { if i == *v as i64 { None } else { Some(format!("expected value {}, got {}", v, n)) } } _ => Some(format!( "expected value {} {}, got {}", self.ctrl.unwrap(), v, n )), }, None => Some(format!("{} cannot be represented as an i64", n)), }, _ => Some(format!("expected value {}, got {}", v, self.json)), }, token::Value::UINT(v) => match &self.json { Value::Number(n) => match n.as_u64() { Some(i) => match &self.ctrl { Some(ControlOperator::NE) | Some(ControlOperator::DEFAULT) if i != *v as u64 => None, Some(ControlOperator::LT) if i < *v as u64 => None, Some(ControlOperator::LE) if i <= *v as u64 => None, Some(ControlOperator::GT) if i > *v as u64 => None, Some(ControlOperator::GE) if i >= *v as u64 => None, Some(ControlOperator::SIZE) => match 256u128.checked_pow(*v as u32) { Some(n) if (i as u128) < n => None, _ => Some(format!("expected value .size {}, got {}", v, n)), }, #[cfg(feature = "additional-controls")] Some(ControlOperator::PLUS) => { if i == *v as u64 { None } else { Some(format!("expected computed .plus value {}, got {}", v, n)) } } #[cfg(feature = "additional-controls")] None | Some(ControlOperator::FEATURE) => { if i == *v as u64 { None } else { Some(format!("expected value {}, got {}", v, n)) } } #[cfg(not(feature = "additional-controls"))] None => { if i == *v as u64 { None } else { Some(format!("expected value {}, got {}", v, n)) } } _ => Some(format!( "expected value {} {}, got {}", self.ctrl.unwrap(), v, n )), }, None => Some(format!("{} cannot be represented as a u64", n)), }, Value::String(s) => match &self.ctrl { Some(ControlOperator::SIZE) => { if s.len() == *v { None } else { Some(format!("expected \"{}\" .size {}, got {}", s, v, s.len())) } } _ => Some(format!("expected {}, got {}", v, s)), }, _ => Some(format!("expected value {}, got {}", v, self.json)), }, token::Value::FLOAT(v) => match &self.json { Value::Number(n) => match n.as_f64() { Some(f) => match &self.ctrl { Some(ControlOperator::NE) | Some(ControlOperator::DEFAULT) if (f - *v).abs() > std::f64::EPSILON => { None } Some(ControlOperator::LT) if f < *v => None, Some(ControlOperator::LE) if f <= *v => None, Some(ControlOperator::GT) if f > *v => None, Some(ControlOperator::GE) if f >= *v => None, #[cfg(feature = "additional-controls")] Some(ControlOperator::PLUS) => { if (f - *v).abs() < std::f64::EPSILON { None } else { Some(format!("expected computed .plus value {}, got {}", v, n)) } } #[cfg(feature = "additional-controls")] None | Some(ControlOperator::FEATURE) => { if (f - *v).abs() < std::f64::EPSILON { None } else { Some(format!("expected value {}, got {}", v, n)) } } #[cfg(not(feature = "additional-controls"))] None => { if (f - *v).abs() < std::f64::EPSILON { None } else { Some(format!("expected value {}, got {}", v, n)) } } _ => Some(format!( "expected value {} {}, got {}", self.ctrl.unwrap(), v, n )), }, None => Some(format!("{} cannot be represented as an i64", n)), }, _ => Some(format!("expected value {}, got {}", v, self.json)), }, token::Value::TEXT(t) => match &self.json { Value::String(s) => match &self.ctrl { Some(ControlOperator::NE) | Some(ControlOperator::DEFAULT) => { if s != t { None } else { Some(format!("expected {} .ne to \"{}\"", value, s)) } } Some(ControlOperator::REGEXP) | Some(ControlOperator::PCRE) => { let re = regex::Regex::new( &format_regex( // Text strings must be JSON escaped per // https://datatracker.ietf.org/doc/html/rfc8610#section-3.1 serde_json::from_str::<Value>(&format!("\"{}\"", t)) .map_err(Error::JSONParsing)? .as_str() .ok_or_else(|| Error::from_validator(self, "malformed regex".to_string()))?, ) .ok_or_else(|| Error::from_validator(self, "malformed regex".to_string()))?, ) .map_err(|e| Error::from_validator(self, e.to_string()))?; if re.is_match(s) { None } else { Some(format!("expected \"{}\" to match regex \"{}\"", s, t)) } } #[cfg(feature = "additional-controls")] Some(ControlOperator::ABNF) => validate_abnf(t, s) .err() .map(|e| format!("\"{}\" is not valid against abnf: {}", s, e)), _ => { #[cfg(feature = "additional-controls")] if s == t { None } else if let Some(ControlOperator::CAT) | Some(ControlOperator::DET) = &self.ctrl { Some(format!( "expected value to match concatenated string {}, got \"{}\"", value, s )) } else if let Some(ctrl) = &self.ctrl { Some(format!("expected value {} {}, got \"{}\"", ctrl, value, s)) } else { Some(format!("expected value {} got \"{}\"", value, s)) } #[cfg(not(feature = "additional-controls"))] if s == t { None } else if let Some(ctrl) = &self.ctrl { Some(format!("expected value {} {}, got \"{}\"", ctrl, value, s)) } else { Some(format!("expected value {} got \"{}\"", value, s)) } } }, _ => Some(format!("expected value {}, got {}", t, self.json)), }, token::Value::BYTE(token::ByteValue::UTF8(b)) => match &self.json { Value::String(s) if s.as_bytes() == b.as_ref() => None, _ => Some(format!("expected byte value {:?}, got {}", b, self.json)), }, token::Value::BYTE(token::ByteValue::B16(b)) => match &self.json { Value::String(s) if s.as_bytes() == b.as_ref() => None, _ => Some(format!("expected byte value {:?}, got {}", b, self.json)), }, token::Value::BYTE(token::ByteValue::B64(b)) => match &self.json { Value::String(s) if s.as_bytes() == b.as_ref() => None, _ => Some(format!("expected byte value {:?}, got {}", b, self.json)), }, }; if let Some(e) = error { self.add_error(e); } Ok(()) } fn visit_occurrence(&mut self, o: &Occurrence) -> visitor::Result<Error> { self.occurrence = Some(o.occur); Ok(()) } } #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] mod tests { #![allow(unused_imports)] use super::*; use indoc::indoc; #[cfg(feature = "additional-controls")] #[test] fn validate_plus() -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" interval<BASE> = ( "test" => BASE .plus a ) rect = { interval<X> } X = 0 a = 10 "# ); let json = r#"{ "test": 10 }"#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, None); jv.validate()?; Ok(()) } #[cfg(feature = "additional-controls")] #[test] fn validate_feature() -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" v = JC<"v", 2> JC<J, C> = C .feature "cbor" / J .feature "json" "# ); let json = r#""v""#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, Some(&["json"])); jv.validate()?; Ok(()) } #[test] fn validate_type_choice_alternate() -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" tester = [ $vals ] $vals /= 12 $vals /= 13 "# ); let json = r#"[ 13 ]"#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, None); jv.validate()?; Ok(()) } #[test] fn validate_group_choice_alternate() -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" tester = $$vals $$vals //= 18 $$vals //= 12 "# ); let json = r#"15"#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, None); jv.validate()?; Ok(()) } #[test] fn validate_group_choice_alternate_in_array_1( ) -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" tester = [$$val] $$val //= ( type: 10, data: uint, t: 11 ) $$val //= ( type: 11, data: tstr ) "# ); let json = r#"[10, 11, 11]"#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, None); jv.validate()?; Ok(()) } #[test] fn validate_group_choice_alternate_in_array_2( ) -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" tester = [$$val] $$val //= ( type: 10, extra, ) extra = ( something: uint, ) "# ); let json = r#"[10, 1]"#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, None); jv.validate()?; Ok(()) } #[test] fn size_control_validation_error() -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" start = Record Record = { id: Id } Id = uint .size 8 "# ); let json = r#"{ "id": 5 }"#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, None); jv.validate()?; Ok(()) } #[test] fn validate_occurrences_in_object() -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" limited = { 1* tstr => tstr } "# ); let json = r#"{ "A": "B" }"#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, None); jv.validate().unwrap(); Ok(()) } #[test] fn validate_optional_occurrences_in_object() -> std::result::Result<(), Box<dyn std::error::Error>> { let cddl = indoc!( r#" argument = { name: text, ? valid: "yes" / "no", } "# ); let json = r#"{ "name": "foo", "valid": "no" }"#; let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing); if let Err(e) = &cddl { println!("{}", e); } let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?; let cddl = cddl.unwrap(); let mut jv = JSONValidator::new(&cddl, json, None); jv.validate().unwrap(); Ok(()) } }
true
7c577c76ab21d26fb9226033c473f2f68391bf9f
Rust
Logicalshift/tame-tree
/src/component/pipe.rs
UTF-8
3,123
3.125
3
[ "Apache-2.0" ]
permissive
// // Copyright 2016 Andrew Hunter // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //! //! # Pipes //! //! Pipes should be familiar to anyone who has used a UNIX-like operating system before. They //! connect the output of one component to the input of another. The tuple type `Pipe` is used //! to represent the pipe between two components. For example: //! //! ``` //! # use tametree::component::*; //! let add_one = component_fn(|x: &i32| { x+1 }); //! let add_two = component_fn(|x: &i32| { x+2 }); //! //! let add_three = Pipe(add_one, add_two); //! # //! # let mut endpoint = ComponentEndPoint::<i32, i32>::new(add_three); //! # endpoint.send(1); //! # assert!(endpoint.recv().unwrap() == 4); //! ``` //! //! This pipe can be used as a component: //! //! ``` //! # use tametree::component::*; //! # let add_one = component_fn(|x: &i32| { x+1 }); //! # let add_two = component_fn(|x: &i32| { x+2 }); //! # //! # let add_three = Pipe(add_one, add_two); //! # //! let mut endpoint = ComponentEndPoint::<i32, i32>::new(add_three); //! endpoint.send(1); //! assert!(endpoint.recv().unwrap() == 4); //! ``` //! //! use std::rc::*; use super::component::*; use super::immediate_publisher::*; struct Pipeline(ComponentRef, ComponentRef); impl Component for Pipeline { } impl Drop for Pipeline { fn drop(&mut self) { } } /// /// A component that takes the output of `TFirst` and connects it to the input of `TSecond` /// pub struct Pipe<TFirst: ConvertToComponent, TSecond: ConvertToComponent>(pub TFirst, pub TSecond); impl<TFirst: ConvertToComponent, TSecond: ConvertToComponent> ConvertToComponent for Pipe<TFirst, TSecond> { #[inline] fn into_component(self, consumer: ConsumerRef, publisher: PublisherRef) -> ComponentRef { let Pipe(first, second) = self; let pipeline_start = ImmediatePublisher::new(); let pipeline_end = pipeline_start.create_consumer(); let first_component = first.into_component(consumer, pipeline_start); let second_component = second.into_component(pipeline_end, publisher); Rc::new(Pipeline(first_component, second_component)) } } /* * TODO: would like to do this for function components as it's more efficient * but figuring out how to write the types so we don't get a conflict with the more generic version isn't easy * * use rustc_serialize::*; impl<TIn: 'static + DecodeFromTreeNode, TResult: Decodable + Encodable + EncodeToTreeNode + 'static, TOut: 'static + ToTreeNode> ConvertToComponent for Pipe<Box<Fn(&TIn) -> TResult>, Box<Fn(&TResult) -> TOut>> { ... } */
true
01b55733ec8ab7c126803d178c95b223bafea4b8
Rust
MindFlavor/azure-sdk-for-rust
/sdk/cosmos/src/operations/replace_user.rs
UTF-8
855
2.609375
3
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
use crate::prelude::*; use azure_core::Request as HttpRequest; #[derive(Debug, Clone, Default)] pub struct ReplaceUserOptions { consistency_level: Option<ConsistencyLevel>, } impl ReplaceUserOptions { pub fn new() -> Self { Self { consistency_level: None, } } setters! { consistency_level: ConsistencyLevel => Some(consistency_level), } pub(crate) fn decorate_request( &self, request: &mut HttpRequest, user_name: &str, ) -> crate::Result<()> { azure_core::headers::add_optional_header2(&self.consistency_level, request)?; let body = ReplaceUserBody { id: user_name }; request.set_body(bytes::Bytes::from(serde_json::to_string(&body)?).into()); Ok(()) } } #[derive(Serialize)] struct ReplaceUserBody<'a> { id: &'a str, }
true
0a8893377ae64bf4289eb8ac635bfa6e7c0d97d9
Rust
BonsaiDen/td-shooter-rs
/shared/src/level/collision.rs
UTF-8
5,232
2.921875
3
[]
no_license
// STD Dependencies ----------------------------------------------------------- use std::f32::consts; // Internal Dependencies ------------------------------------------------------ use ::level::{Level, MAX_LEVEL_SIZE}; use ::collision::{ aabb_intersect_circle, line_intersect_line, line_intersect_circle }; // Statics -------------------------------------------------------------------- pub const COLLISION_GRID_SPACING: f32 = 200.0; // Traits --------------------------------------------------------------------- pub trait LevelCollision { fn collide(&self, x: &mut f32, y: &mut f32, radius: f32, active: bool); fn collide_beam(&self, x: f32, y: f32, r: f32, l: f32) -> Option<(usize, [f32; 3])>; fn collide_beam_wall(&self, x: f32, y: f32, r: f32, l: f32) -> Option<f32>; fn collide_line(&self, line: &[f32; 4]) -> Option<(usize, [f32; 3])>; } impl LevelCollision for Level { fn collide(&self, x: &mut f32, y: &mut f32, radius: f32, active: bool) { let mut iterations = 0; let mut collisions = 1; while collisions > 0 && iterations < 10 { collisions = 0; let mut overlap = (0.0, 0.0); for wall in &self.walls { if aabb_intersect_circle( &wall.aabb, *x, *y, radius + 1.0 ) { if let Some(collision) = line_intersect_circle( &wall.collision, *x, *y, radius + 1.0 ) { overlap.0 += collision[7].cos() * collision[6]; overlap.1 += collision[7].sin() * collision[6]; collisions += 1; } } } // Avoid edge sliding without player input if !active && overlap.0.abs() < 0.1 && overlap.1.abs() < 0.1 { break; } *x -= overlap.0; *y -= overlap.1; iterations += 1; // No need to iterate idle entities multiple times per frame if !active { break; } } *x = x.min(MAX_LEVEL_SIZE).max(-MAX_LEVEL_SIZE); *y = y.min(MAX_LEVEL_SIZE).max(-MAX_LEVEL_SIZE); } fn collide_beam(&self, x: f32, y: f32, r: f32, l: f32) -> Option<(usize, [f32; 3])> { let line = [ x, y, x + r.cos() * l, y + r.sin() * l ]; self.collide_line(&line) } fn collide_beam_wall(&self, x: f32, y: f32, r: f32, l: f32) -> Option<f32> { let line = [ x, y, x + r.cos() * l, y + r.sin() * l ]; // Return wall angle if let Some(intersect) = self.collide_line(&line) { let wall = &self.walls[intersect.0]; // Vertical | if wall.is_vertical { // Left or right of the wall if x > wall.points[0] { Some(consts::PI) } else { Some(0.0) } // Horizontal -- } else if wall.is_horizontal { // Above or below the wall if y > wall.points[1] { Some(-consts::PI * 0.5) } else { Some(consts::PI * 0.5) } // Diagonal \ } else if wall.points[0] < wall.points[2] && wall.points[1] < wall.points[3] { if r > consts::PI * 0.35 && r < consts::PI * 1.25 { Some(consts::PI * 0.75) } else { Some(consts::PI * 1.75) } // Diagonal / } else if r > consts::PI * 0.75 && r < consts::PI * 1.75 { Some(consts::PI * 1.25) } else { Some(consts::PI * 0.25) } } else { None } } fn collide_line(&self, line: &[f32; 4]) -> Option<(usize, [f32; 3])> { self.collide_beam_with_walls(line) } } // Internal Helpers ----------------------------------------------------------- impl Level { pub fn w2g(&self, x: f32, y: f32) -> (isize, isize) { let gx = ((x - COLLISION_GRID_SPACING * 0.5) / COLLISION_GRID_SPACING).round(); let gy = ((y - COLLISION_GRID_SPACING * 0.5) / COLLISION_GRID_SPACING).round(); (gx as isize, gy as isize) } fn collide_beam_with_walls(&self, line: &[f32; 4]) -> Option<(usize, [f32; 3])> { let mut intersection: Option<(usize, [f32; 3])> = None; for (i, wall) in self.walls.iter().enumerate() { if let Some(new) = line_intersect_line(line, &wall.points) { let is_closer = if let Some(existing) = intersection { new[2] < existing.1[2] } else { true }; if is_closer { intersection = Some((i, new)); } } } intersection } }
true
f8ac324dd30c4189dfde44943b08c32314bcc1fb
Rust
silky/synless
/forest/src/lib.rs
UTF-8
17,222
3.625
4
[]
no_license
//! A general represenation of trees. mod forest; mod tree; mod tree_ref; pub use self::tree::{Tree, Forest, ReadLeaf, WriteLeaf, ReadData, WriteData}; pub use self::tree_ref::TreeRef; #[cfg(test)] mod forest_tests { use super::*; fn family(forest: &Forest<&'static str, &'static str>) -> Tree<&'static str, &'static str> { let leaves = vec!(forest.new_leaf("elder"), forest.new_leaf("younger")); forest.new_branch("parent", leaves) } fn mirror(forest: &Forest<u32, u32>, height: u32, id: u32) -> Tree<u32, u32> { if height == 0 { forest.new_leaf(id) } else { let mut children = vec!(); for i in 0..height { children.push(mirror(forest, i, id + 2_u32.pow(i))); } forest.new_branch(id, children) } } impl<'f> TreeRef<'f, u32, u32> { fn sum(&self) -> u32 { if self.is_leaf() { *self.leaf() } else { let mut sum = *self.data(); for child in self.children() { sum += child.sum(); } sum } } } #[test] fn test_leaves() { let forest: Forest<(), u32> = Forest::new(); // Begin with a leaf of 2 let mut tree = forest.new_leaf(2); assert!(tree.is_leaf()); assert_eq!(*tree.leaf(), 2); // Mutate it to be 3 *tree.leaf_mut() = 3; assert!(tree.borrow().is_leaf()); assert_eq!(*tree.borrow().leaf(), 3); } #[test] fn test_data() { let forest: Forest<u32, ()> = Forest::new(); // Begin with data of 2 let mut tree = forest.new_branch(2, vec!()); assert!(!tree.borrow().is_leaf()); assert_eq!(*tree.borrow().data(), 2); // Mutate it to be 3 *tree.data_mut() = 3; assert!(!tree.is_leaf()); assert_eq!(*tree.data(), 3); } #[test] fn test_num_children() { let forest: Forest<(), ()> = Forest::new(); let leaves = vec!(forest.new_leaf(()), forest.new_leaf(()), forest.new_leaf(())); println!("before"); let tree = forest.new_branch((), leaves); println!("after"); assert_eq!(tree.borrow().num_children(), 3); assert_eq!(tree.num_children(), 3); } #[test] fn test_navigation_ref() { let forest: Forest<&'static str, &'static str> = Forest::new(); let tree = family(&forest); assert_eq!(*tree.borrow().child(0).leaf(), "elder"); assert_eq!(*tree.borrow().child(1).leaf(), "younger"); assert_eq!(*tree.borrow().child(0).parent().unwrap().data(), "parent"); assert!(tree.borrow().child(0).parent().unwrap().parent().is_none()); let children: Vec<&'static str> = tree.borrow() .children() .map(|child| *child.leaf()) .collect(); assert_eq!(children, vec!("elder", "younger")); } #[test] fn test_at_root_mut() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); assert!(tree.at_root()); tree.goto_child(1); assert!(!tree.at_root()); } #[test] fn test_navigation_mut() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); tree.goto_child(1); assert_eq!(*tree.leaf(), "younger"); tree.goto_parent(); assert_eq!(*tree.data(), "parent"); tree.goto_child(0); assert_eq!(*tree.leaf(), "elder"); tree.goto_root(); assert_eq!(*tree.data(), "parent"); assert_eq!(*tree.borrow().child(1).leaf(), "younger"); } #[test] fn test_bookmark_ref() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); let mut other_tree = forest.new_leaf("stranger"); let bookmark = tree.borrow().child(1).bookmark(); assert!(other_tree.borrow().lookup_bookmark(bookmark).is_none()); assert!(!other_tree.goto_bookmark(bookmark)); assert_eq!(*tree.borrow() .lookup_bookmark(bookmark).unwrap() .leaf(), "younger"); tree.goto_child(0); assert!(tree.goto_bookmark(bookmark)); assert_eq!(*tree.leaf(), "younger"); } #[test] fn test_bookmark_mut() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); let mut other_tree = forest.new_leaf("stranger"); tree.goto_child(1); let bookmark = tree.bookmark(); tree.goto_parent(); assert!(other_tree.borrow().lookup_bookmark(bookmark).is_none()); assert!(!other_tree.goto_bookmark(bookmark)); assert_eq!(*tree.borrow().lookup_bookmark(bookmark).unwrap().leaf(), "younger"); tree.goto_child(0); assert!(tree.goto_bookmark(bookmark)); assert_eq!(*tree.leaf(), "younger"); } #[test] fn test_bookmark_deleted() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); let bookmark = tree.borrow().child(1).bookmark(); let _ = tree.remove_child(1); assert!(tree.borrow().lookup_bookmark(bookmark).is_none()); assert!(!tree.goto_bookmark(bookmark)); } #[test] fn test_replace_child() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); let old_imposter = forest.new_leaf("oldImposter"); let young_imposter = forest.new_leaf("youngImposter"); let elder = tree.replace_child(0, old_imposter); let younger = tree.replace_child(1, young_imposter); assert_eq!(*elder.borrow().leaf(), "elder"); assert_eq!(*younger.borrow().leaf(), "younger"); assert_eq!(tree.borrow().num_children(), 2); assert_eq!(*tree.borrow().child(0).leaf(), "oldImposter"); assert_eq!(*tree.borrow().child(1).leaf(), "youngImposter"); } #[test] fn test_remove_child() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); // Remove elder child from the family let elder = tree.remove_child(0); assert_eq!(*elder.borrow().leaf(), "elder"); assert!(elder.borrow().parent().is_none()); assert_eq!(tree.borrow().num_children(), 1); assert_eq!(*tree.borrow().child(0).leaf(), "younger"); assert_eq!(*tree.borrow().child(0).parent().unwrap().data(), "parent"); // Remove younger child from the family let younger = tree.remove_child(0); assert_eq!(*younger.borrow().leaf(), "younger"); assert!(younger.borrow().parent().is_none()); assert_eq!(tree.borrow().num_children(), 0); } #[test] fn test_insert_child() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); let malcolm = forest.new_leaf("Malcolm"); let reese = forest.new_leaf("Reese"); let dewey = forest.new_leaf("Dewey"); tree.insert_child(1, malcolm); // Malcolm is in the middle tree.insert_child(0, reese); tree.insert_child(4, dewey); let children: Vec<&'static str> = tree.borrow() .children() .map(|child| *child.leaf()) .collect(); assert_eq!(children, vec!("Reese", "elder", "Malcolm", "younger", "Dewey")); assert_eq!(*tree.borrow().child(0).parent().unwrap().data(), "parent"); assert_eq!(*tree.borrow().child(1).parent().unwrap().data(), "parent"); } #[test] fn comprehensive_exam() { let forest: Forest<u32, u32> = Forest::new(); { let mut tree = mirror(&forest, 3, 0); let mut canada = forest.new_branch(721, vec!()); let mut mexico = forest.new_leaf(3767); assert_eq!(forest.read_lock().tree_count(), 8+1+1); // tree: // 0 // / | \ // 1 2 4 // | / \ // 3 5 6 // | // 7 // Test TreeRef let (mark2, mark4) = { // Data Access assert_eq!(tree.borrow().sum(), 28); assert_eq!(tree.borrow().num_children(), 3); // Navigation, Data Access let node5 = tree.borrow().child(2).child(0); assert!(node5.is_leaf()); assert_eq!(*node5.leaf(), 5); let node4 = node5.parent().unwrap(); assert_eq!(*node4.data(), 4); assert!(node5 .parent().unwrap() .parent().unwrap() .parent() .is_none()); // Bookmarks: successful lookup let subtree = tree.borrow().child(1); let mark5 = node5.bookmark(); assert_eq!(*subtree .lookup_bookmark(mark5).unwrap() .parent().unwrap() .data(), 4); let mark4 = node4.bookmark(); assert_eq!(*node5 .lookup_bookmark(mark4).unwrap() .parent().unwrap() .child(1) .data(), 2); // Bookmarks: failing lookup assert!(canada.borrow().lookup_bookmark(mark5).is_none()); let mark_mexico = mexico.borrow().bookmark(); assert!(node4.lookup_bookmark(mark_mexico).is_none()); // Save some bookmarks for later testing let mark2 = tree.borrow().child(1).bookmark(); let mark4 = node4.bookmark(); (mark2, mark4) }; // Test Tree // To start: // // tree: 0 // / | \ // 1 2* 4* // | / \ // 3 5 6 // | // 7 // canada: 721 // mexico: 3767 // Navigate assert!(!tree.is_leaf()); tree.goto_child(1); assert_eq!(*tree.data(), 2); // Data Mutation *tree.data_mut() = 22; assert_eq!(*tree.data(), 22); assert_eq!(tree.num_children(), 1); // Navigate assert!(!tree.at_root()); tree.goto_parent(); let mark0 = tree.bookmark(); assert!(tree.at_root()); // Cut let mut snip = tree.remove_child(1); // tree: 0+ // / \ // 1 4* // / \ // 5 6 // | // 7 // snip: 2* // | // 3 // canada: 721 // mexico: 3767 assert_eq!(*snip.borrow().data(), 22); assert_eq!(tree.borrow().sum(), 23); assert_eq!(forest.read_lock().tree_count(), 10); // Paste tree.goto_child(1); tree.insert_child(1, snip); tree.insert_child(3, mexico); // tree: 0+ // / \ // 1 4* _ // / | \ \ // 5 22* 6 3767 // | | // 3 7 // canada: 721 // Leaf Mutation tree.goto_child(3); assert!(tree.is_leaf()); assert_eq!(*tree.leaf(), 3767); let mark3767 = tree.bookmark(); *tree.leaf_mut() = 376; assert_eq!(*tree.leaf(), 376); assert!(!tree.at_root()); tree.goto_parent(); assert!(!tree.is_leaf()); // tree: 0+ // / \ // 1 4* _ // / | \ \ // 5 22* 6 376+ // | | // 3 7 // canada: 721 // Replace snip = tree.replace_child(1, canada); assert!(snip.borrow().parent().is_none()); tree.goto_child(1); assert_eq!(*tree.data(), 721); tree.goto_parent(); assert_eq!(*tree.data(), 4); // Further mucking mexico = tree.remove_child(3); assert!(mexico.borrow().parent().is_none()); snip.insert_child(0, mexico); canada = snip; tree.goto_child(2); // tree: 0+ // / \ // 1 4* // / | \ // 5 721 6 // | // 7 // canada: 22* // / \ // 3 376+ // Bookmarks after mutation assert!( ! tree.goto_bookmark(mark2)); assert_eq!(*tree.data(), 6); assert!(tree.goto_bookmark(mark4)); assert_eq!(*tree.data(), 4); assert_eq!(*canada.borrow() .lookup_bookmark(mark3767).unwrap() .leaf(), 376); assert!( ! canada.goto_bookmark(mark0)); // Some final bookmark checks assert!(tree.borrow().child(0).lookup_bookmark(mark2).is_none()); assert_eq!(tree.borrow() .child(0) .lookup_bookmark(mark4).unwrap() .sum(), 743); // Summation checks tree.goto_parent(); assert_eq!(tree.borrow().sum(), 744); assert_eq!(canada.borrow().sum(), 401); } // Check for leaks assert_eq!(forest.read_lock().tree_count(), 0); } // Error Testing // #[test] #[should_panic(expected="leaf node has no children")] fn test_num_chilren_panic() { let forest: Forest<(), ()> = Forest::new(); let tree = forest.new_leaf(()); tree.borrow().num_children(); } #[test] #[should_panic(expected="leaf node has no data")] fn test_data_panic() { let forest: Forest<(), ()> = Forest::new(); let tree = forest.new_leaf(()); *tree.borrow().data(); } #[test] #[should_panic(expected="branch node has no leaf")] fn test_leaf_panic() { let forest: Forest<(), ()> = Forest::new(); let mut tree = forest.new_branch((), vec!()); *tree.leaf_mut(); } #[test] #[should_panic(expected="leaf node has no children")] fn test_navigation_panic_leaf_ref() { let forest: Forest<(), ()> = Forest::new(); let tree = forest.new_leaf(()); tree.borrow().child(0); } #[test] #[should_panic(expected="leaf node has no children")] fn test_navigation_panic_leaf_mut() { let forest: Forest<(), ()> = Forest::new(); let mut tree = forest.new_leaf(()); tree.goto_child(0); } #[test] #[should_panic(expected="child index out of bounds")] fn test_navigation_panic_oob_ref() { let forest: Forest<(), ()> = Forest::new(); let tree = forest.new_branch((), vec!()); tree.borrow().child(0); } #[test] #[should_panic(expected="child index out of bounds")] fn test_navigation_panic_oob_mut() { let forest: Forest<(), ()> = Forest::new(); let mut tree = forest.new_branch((), vec!()); tree.goto_child(0); } #[test] #[should_panic(expected="child index out of bounds")] fn test_insert_panic_oob() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); let leaf = forest.new_leaf(""); tree.insert_child(3, leaf); } #[test] #[should_panic(expected="child index out of bounds")] fn test_remove_panic_oob() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); tree.remove_child(2); } #[test] #[should_panic(expected="child index out of bounds")] fn test_replace_panic_oob() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); let leaf = forest.new_leaf(""); tree.replace_child(2, leaf); } #[test] #[should_panic(expected="root node has no parent")] fn test_parent_of_root_panic() { let forest: Forest<&'static str, &'static str> = Forest::new(); let mut tree = family(&forest); tree.goto_parent(); } }
true
e9f050764f3425ce08826fe985489df961fda509
Rust
weiznich/inflector
/src/cases/kebabcase/mod.rs
UTF-8
5,635
3.46875
3
[]
no_license
use regex::Regex; use cases::snakecase::to_snake_case; /// Converts a `String` to `kebab-case` `String` /// /// #Examples /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// /// /// // kebab_case_foo_dash_bar_as_foo_dash_bar() { /// let mock_string: String = "foo-bar".to_string(); /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// /// /// // kebab_case_FOO_BAR_as_foo_bar() { /// let mock_string: String = "FOO_BAR".to_string(); /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// /// /// // kebab_case_foo_bar_as_foo_bar() { /// let mock_string: String = "foo_bar".to_string(); /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// /// /// // kebab_case_Foo_space_Bar_as_foo_bar() { /// let mock_string: String = "Foo Bar".to_string(); /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// /// /// // kebab_case_Foo_space_bar_as_foo_bar() { /// let mock_string: String = "Foo bar".to_string(); /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// /// /// // kebab_case_FooBar_as_foo_bar() { /// let mock_string: String = "FooBar".to_string(); /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// /// /// // kebab_case_fooBar_as_foo_bar() { /// let mock_string: String = "fooBar".to_string(); /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn is_kebab_case(test_string: String) -> bool{ let kebab_matcher = Regex::new(r"(?:[^_]?=^|[-])([a-z]+)").unwrap(); let upcase_matcher = Regex::new(r"[A-Z]").unwrap(); kebab_matcher.is_match(test_string.as_ref()) && !upcase_matcher.is_match(test_string.as_ref()) } /// Determines if a `String` is `kebab-case` /// /// #Examples /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// /// /// // returns_truthy_value_for_is_kebab_case_when_kebab() { /// let mock_string: String = "foo-bar-string-that-is-really-really-long".to_string(); /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// /// /// // returns_falsey_value_for_is_kebab_case_when_class() { /// let mock_string: String = "FooBarIsAReallyReallyLongString".to_string(); /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// /// /// // returns_falsey_value_for_is_kebab_case_when_camel() { /// let mock_string: String = "fooBarIsAReallyReallyLongString".to_string(); /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// /// /// // returns_falsey_value_for_is_kebab_case_when_screaming_snake() { /// let mock_string: String = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG".to_string(); /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// /// /// // returns_falsey_value_for_is_kebab_case_when_snake() { /// let mock_string: String = "foo_bar_string_that_is_really_really_long".to_string(); /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// /// /// // returns_falsey_value_for_is_kebab_case_when_sentence() { /// let mock_string: String = "Foo bar string that is really really long".to_string(); /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// /// /// // returns_falsey_value_for_is_kebab_case_when_title() { /// let mock_string: String = "Foo Bar Is A Really Really Long String".to_string(); /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` pub fn to_kebab_case(non_kebab_case_string: String) -> String { to_kebab_from_snake(to_snake_case(non_kebab_case_string)) } fn to_kebab_from_snake(non_kebab_case_string: String) -> String { non_kebab_case_string.replace("_", "-") }
true
e8260e106b87cd02709298928aefc28c844ad318
Rust
chandero/patternfly-yew
/src/form.rs
UTF-8
13,840
2.8125
3
[ "Apache-2.0" ]
permissive
use crate::{Button, Validator}; use yew::prelude::*; use yew::web_sys::HtmlInputElement; #[derive(Clone, PartialEq, Properties)] pub struct Props { #[prop_or_default] pub children: Children, } pub struct Form { props: Props, } impl Component for Form { type Message = (); type Properties = Props; fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _msg: Self::Message) -> bool { true } fn change(&mut self, props: Self::Properties) -> bool { if self.props != props { self.props = props; true } else { false } } fn view(&self) -> Html { html! { <form novalidate=true class="pf-c-form"> { for self.props.children.iter().map(|child|{ child }) } </form> } } } // form group #[derive(Clone, PartialEq, Properties)] pub struct FormGroupProps { pub children: Children, #[prop_or_default] pub label: String, #[prop_or_default] pub required: bool, #[prop_or_default] pub helper_text: String, } pub struct FormGroup { props: FormGroupProps, } impl Component for FormGroup { type Message = (); type Properties = FormGroupProps; fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _msg: Self::Message) -> bool { true } fn change(&mut self, props: Self::Properties) -> bool { if self.props != props { self.props = props; true } else { false } } fn view(&self) -> Html { let classes = Classes::from("pf-c-form__group"); html! { <div class=classes> <div class="pf-c-form__group-label"> {if !self.props.label.is_empty() { html!{ <div class="pf-c-form__label"> <span class="pf-c-form__label-text">{&self.props.label}</span> {if self.props.required { html!{ <span class="pf-c-form__label-required" aria-hidden="true">{"*"}</span> } } else { html!{} }} </div> } } else { html!{} }} </div> <div class="pf-c-form__group-control"> { for self.props.children.iter() } { if !self.props.helper_text.is_empty() {html!{ <p class="pf-c-form__helper-text" aria-live="polite">{ &self.props.helper_text }</p> }} else {html!{}}} </div> </div> } } } // form control #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum InputState { Default, Success, Warning, Error, } impl Default for InputState { fn default() -> Self { Self::Default } } impl InputState { pub fn convert(&self, mut classes: Classes) -> (Classes, bool) { let mut aria_invalid = false; match self { InputState::Default => {} InputState::Success => classes.push("pf-m-success"), InputState::Warning => classes.push("pf-m-warning"), InputState::Error => aria_invalid = true, }; (classes, aria_invalid) } } #[derive(Copy, Clone, Eq, PartialEq)] pub enum TextInputIcon { None, Calendar, Clock, Search, Custom, } impl Default for TextInputIcon { fn default() -> Self { Self::None } } #[derive(Clone, PartialEq, Properties)] pub struct TextInputProps { #[prop_or_default] pub name: String, #[prop_or_default] pub value: String, #[prop_or_default] pub required: bool, #[prop_or_default] pub disabled: bool, #[prop_or_default] pub readonly: bool, #[prop_or_default] pub state: InputState, #[prop_or_default] pub icon: TextInputIcon, #[prop_or("text".into())] pub r#type: String, #[prop_or_default] pub placeholder: String, #[prop_or_default] pub onchange: Callback<String>, #[prop_or_default] pub oninput: Callback<String>, #[prop_or_default] pub validator: Validator, } pub struct TextInput { props: TextInputProps, link: ComponentLink<Self>, value: String, input_ref: NodeRef, } pub enum TextInputMsg { Changed(String), Input(String), } impl Component for TextInput { type Message = TextInputMsg; type Properties = TextInputProps; fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self { let value = props.value.clone(); Self { props, link, value, input_ref: Default::default(), } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { TextInputMsg::Changed(data) => { self.value = data.clone(); self.props.onchange.emit(data); } TextInputMsg::Input(data) => { self.props.oninput.emit(data); if let Some(value) = self.extract_value() { self.value = value.clone(); self.props.onchange.emit(value); } // only re-render if we have a validator return self.props.validator.is_custom(); } } true } fn change(&mut self, props: Self::Properties) -> ShouldRender { if self.props != props { self.props = props; if self.props.readonly { self.value = self.props.value.clone(); } true } else { false } } fn view(&self) -> Html { let mut classes = Classes::from("pf-c-form-control"); classes = match self.props.icon { TextInputIcon::None => classes, TextInputIcon::Search => classes.extend("pf-m-search"), TextInputIcon::Calendar => classes.extend(vec!["pf-m-icon", "pf-m-calendar"]), TextInputIcon::Clock => classes.extend(vec!["pf-m-icon", "pf-m-clock"]), TextInputIcon::Custom => classes.extend(vec!["pf-m-icon"]), }; let (classes, aria_invalid) = self.input_state().convert(classes); let onchange = self.link.batch_callback(|data| match data { ChangeData::Value(data) => vec![TextInputMsg::Changed(data)], _ => vec![], }); let oninput = self .link .callback(|data: InputData| TextInputMsg::Input(data.value)); html! { <input ref=self.input_ref.clone() class=classes type=self.props.r#type name=self.props.name required=self.props.required disabled=self.props.disabled readonly=self.props.readonly aria-invalid=aria_invalid value=self.value placeholder=self.props.placeholder onchange=onchange oninput=oninput /> } } } impl TextInput { /// Extract the current value from the input element fn extract_value(&self) -> Option<String> { self.input_ref .cast::<HtmlInputElement>() .map(|input| input.value()) } /// Get the effective input state /// /// This may be the result of the validator, or if none was set, the provided input state /// from the properties. fn input_state(&self) -> InputState { match &self.props.validator { Validator::Custom(validator) => validator(&self.value), _ => self.props.state, } } } // // Text area // #[derive(Clone, PartialEq, Eq)] pub enum ResizeOrientation { Horizontal, Vertical, Both, } impl Default for ResizeOrientation { fn default() -> Self { Self::Both } } #[derive(Clone, PartialEq, Properties)] pub struct TextAreaProps { #[prop_or_default] pub name: String, #[prop_or_default] pub value: String, #[prop_or_default] pub required: bool, #[prop_or_default] pub disabled: bool, #[prop_or_default] pub readonly: bool, #[prop_or_default] pub state: InputState, #[prop_or_default] pub resize: ResizeOrientation, #[prop_or_default] pub onchange: Callback<String>, #[prop_or_default] pub oninput: Callback<String>, #[prop_or_default] pub validator: Validator, } pub struct TextArea { props: TextAreaProps, link: ComponentLink<Self>, value: String, input_ref: NodeRef, } pub enum TextAreaMsg { Changed(String), Input(String), } impl Component for TextArea { type Message = TextAreaMsg; type Properties = TextAreaProps; fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self { let value = props.value.clone(); Self { props, link, value, input_ref: NodeRef::default(), } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { TextAreaMsg::Changed(data) => { self.value = data.clone(); self.props.onchange.emit(data); false } TextAreaMsg::Input(data) => { self.props.oninput.emit(data); if let Some(value) = self.extract_value() { self.value = value.clone(); self.props.onchange.emit(value); } false } } } fn change(&mut self, props: Self::Properties) -> ShouldRender { if self.props != props { self.props = props; true } else { false } } fn view(&self) -> Html { let classes = Classes::from("pf-c-form-control"); let (mut classes, aria_invalid) = self.input_state().convert(classes); match self.props.resize { ResizeOrientation::Horizontal => classes.push("pf-m-resize-horizontal"), ResizeOrientation::Vertical => classes.push("pf-m-resize-vertical"), _ => {} } let onchange = self.link.batch_callback(|data| match data { ChangeData::Value(data) => vec![TextAreaMsg::Changed(data)], _ => vec![], }); let oninput = self .link .callback(|data: InputData| TextAreaMsg::Input(data.value)); html! { <textarea ref=self.input_ref.clone() class=classes name=self.props.name required=self.props.required disabled=self.props.disabled readonly=self.props.readonly aria-invalid=aria_invalid value=self.props.value onchange=onchange oninput=oninput /> } } } impl TextArea { /// Extract the current value from the input element fn extract_value(&self) -> Option<String> { self.input_ref .cast::<HtmlInputElement>() .map(|input| input.value()) } /// Get the effective input state /// /// This may be the result of the validator, or if none was set, the provided input state /// from the properties. fn input_state(&self) -> InputState { match &self.props.validator { Validator::Custom(validator) => validator(&self.value), _ => self.props.state, } } } // // Action group // #[derive(Clone, PartialEq, Properties)] pub struct ActionGroupProps { children: ChildrenWithProps<Button>, } pub struct ActionGroup { props: ActionGroupProps, } impl Component for ActionGroup { type Message = (); type Properties = ActionGroupProps; fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _msg: Self::Message) -> ShouldRender { true } fn change(&mut self, props: Self::Properties) -> ShouldRender { if self.props != props { self.props = props; true } else { false } } fn view(&self) -> Html { html! { <div class="pf-c-form__group pf-m-action"> <div class="pf-c-form__actions"> { for self.props.children.iter() } </div> </div> } } } // // Input group // #[derive(Clone, PartialEq, Properties)] pub struct InputGroupProps { children: Children, } pub struct InputGroup { props: InputGroupProps, } impl Component for InputGroup { type Message = (); type Properties = InputGroupProps; fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _msg: Self::Message) -> ShouldRender { true } fn change(&mut self, props: Self::Properties) -> ShouldRender { if self.props != props { self.props = props; true } else { false } } fn view(&self) -> Html { html! { <div class="pf-c-input-group"> { for self.props.children.iter() } </div> } } }
true
655b0da45bed45bd3225fddbb37a04693a7bee14
Rust
amling/r4
/ars/aa/src/lattice.rs
UTF-8
3,326
2.578125
3
[]
no_license
use ars_ds::tuple::TupleEnd; use crate::misc; use crate::zmodule; use zmodule::ZModule; is_tuple_trait!(IsTuple); pub trait LatticeCanonicalizer<S: ZModule + Clone> { fn canonicalize(&self, s: S) -> S; fn canonicalize_delta(&self, s: S) -> (S, S) { let mut s2 = s.clone(); s2 = self.canonicalize(s2); let mut sd = s2.clone(); sd.addmul(-1, &s); (s, sd) } fn materialize_mut(&self, acc: impl FnMut(S)); fn materialize(&self) -> Vec<S> { let mut acc = Vec::new(); self.materialize_mut(|s| acc.push(s)); acc } } pub trait LatticeCanonicalizable: ZModule + Clone + Sized { type Output: LatticeCanonicalizer<Self>; fn canonicalize(vs: Vec<Self>) -> Self::Output; } impl LatticeCanonicalizable for () { type Output = (); fn canonicalize(_: Vec<Self>) { } } impl LatticeCanonicalizer<()> for () { fn canonicalize(&self, _: ()) -> () { } fn materialize_mut(&self, _: impl FnMut(())) { } } impl LatticeCanonicalizable for isize { type Output = isize; fn canonicalize(vs: Vec<isize>) -> isize { let mut d = 0; for mut v in vs { misc::egcd_mut(&mut v, &mut d, &mut (), &mut ()); } d } } impl LatticeCanonicalizer<isize> for isize { fn canonicalize(&self, v: isize) -> isize { v.rem_euclid(*self) } fn materialize_mut(&self, mut acc: impl FnMut(isize)) { if *self != 0 { acc(*self); } } } impl<S: LatticeCanonicalizable + Eq, T: ZModule + TupleEnd<F=S, B=isize> + IsTuple + Clone> LatticeCanonicalizable for T { type Output = (Option<T>, S::Output); fn canonicalize(vs: Vec<T>) -> (Option<T>, S::Output) { let mut l = (S::zero(), 0); let mut vs: Vec<_> = vs.into_iter().map(|t| T::split_tuple_end(t)).collect(); for v in vs.iter_mut() { let (sv, nv) = v; let (sl, nl) = &mut l; misc::egcd_mut(nv, nl, sv, sl); } let vs = vs.into_iter().map(|(s, n)| { assert_eq!(0, n); s }).collect(); let so = S::canonicalize(vs); let l = match l.1 != 0 { true => Some(T::join_tuple_end(so.canonicalize(l.0), l.1)), false => { assert!(S::zero() == l.0); None }, }; (l, so) } } impl<S: LatticeCanonicalizable, T: ZModule + TupleEnd<F=S, B=isize> + Clone> LatticeCanonicalizer<T> for (Option<T>, S::Output) { fn canonicalize(&self, t: T) -> T { let (mut s, mut n) = T::split_tuple_end(t); if let Some(t) = &self.0 { let (s1, n1) = T::split_tuple_end(t.clone()); // unbelievably, this absolutely smokes using div_euclid while n < 0 { n += n1; s.addmul(1, &s1); } while n >= n1 { n -= n1; s.addmul(-1, &s1); } } s = self.1.canonicalize(s); T::join_tuple_end(s, n) } fn materialize_mut(&self, mut acc: impl FnMut(T)) { if let Some(t) = &self.0 { acc(t.clone()); } self.1.materialize_mut(|s| { acc(T::join_tuple_end(s, 0)); }); } }
true
36ef249111d4a965e98d7e54c2db7091c9728716
Rust
souravbadami/ion-rust
/src/text/text_data_source.rs
UTF-8
1,135
3.375
3
[ "Apache-2.0" ]
permissive
use std::io; use std::io::{BufRead, BufReader}; /// Types that implement this trait can be converted into an implementation of [io::BufRead], /// allowing them to be passed to the [TextReader::new] constructor. This allows [TextReader::new] /// to support reading Strings, &str slices, &[u8] slices, files, etc. pub trait TextIonDataSource { type TextSource: BufRead; fn to_text_ion_data_source(self) -> Self::TextSource; } impl TextIonDataSource for String { type TextSource = io::Cursor<Self>; fn to_text_ion_data_source(self) -> Self::TextSource { io::Cursor::new(self) } } impl<'a> TextIonDataSource for &'a str { type TextSource = io::Cursor<Self>; fn to_text_ion_data_source(self) -> Self::TextSource { io::Cursor::new(self) } } impl<'a> TextIonDataSource for &'a &[u8] { type TextSource = io::Cursor<Self>; fn to_text_ion_data_source(self) -> Self::TextSource { io::Cursor::new(self) } } impl<T: io::Read> TextIonDataSource for BufReader<T> { type TextSource = Self; fn to_text_ion_data_source(self) -> Self::TextSource { self } }
true
70881ec765a8d9877bebb8eb76040b4e7aa64897
Rust
jedestep/rust-scratchpad
/src/mongo-demo/main.rs
UTF-8
2,943
3.234375
3
[]
no_license
extern mod bson; use bson::encode::*; use bson::decode::*; use bson::formattable::*; fn main() { println(fmt!("5 as a bson repr: %s", 5f.to_bson_t().to_str())); println(fmt!("5 as a bson string: %s", 5f.to_bson_t().to_bson().to_str())); println(fmt!("[1,2,3] as a bson repr: %s", (~[1u16,2,3]).to_bson_t().to_str())); println(fmt!("[1,2,3] as a bson string: %s", (~[1u16,2,3]).to_bson_t().to_bson().to_str())); println(fmt!("{foo: 'bar'} as a bson repr: %s", (~"{ \"foo\": \"bar\" }").to_bson_t().to_str())); println(fmt!("{foo: 'bar'} as a bson string: %s", (~"{ \"foo\": \"bar\" }").to_bson_t().to_bson().to_str())); println(fmt!("New FooStruct as a bson repr: %s", (FooStruct::new()).to_bson_t().to_str())); println(fmt!("New FooStruct as a bson string: %s", (FooStruct::new()).to_bson_t().to_bson().to_str())); println(""); println(fmt!("Roundtripping representations: %? -> %s -> %?", FooStruct::new(), (FooStruct::new()).to_bson_t().to_str(), BsonFormattable::from_bson_t::<FooStruct>((FooStruct::new()).to_bson_t()).unwrap())); println(fmt!("Roundtripping strings: %? -> %s -> %s", FooStruct::new(), (FooStruct::new()).to_bson_t().to_bson().to_str(), (decode((FooStruct::new()).to_bson_t().to_bson()).unwrap()).to_str())); } #[deriving(ToStr)] impl FooStruct { fn new() -> FooStruct { FooStruct { flag: true, widget: false, value: 0 } } } impl BsonFormattable for FooStruct { fn to_bson_t(&self) -> Document { let mut doc = BsonDocument::new(); doc.put(~"flag", Bool(self.flag)); doc.put(~"widget", Bool(self.widget)); doc.put(~"value", Int32(self.value as i32)); Embedded(~doc) } fn from_bson_t(doc: Document) -> Result<FooStruct, ~str> { match doc { Embedded(d) => { let mut s = FooStruct::new(); if d.contains_key(~"flag") { s.flag = match d.find(~"flag").unwrap() { &Bool(b) => b, _ => fail!("flag must be boolean") } } if d.contains_key(~"widget") { s.widget = match d.find(~"widget").unwrap() { &Bool(b) => b, _ => fail!("widget must be boolean") } } if d.contains_key(~"value") { s.value = match d.find(~"value").unwrap() { &Int32(i) => i as uint, &Int64(i) => i as uint, &Double(f) => f as uint, _ => fail!("value must be numeric") } } return Ok(s); }, _ => fail!("can only format Embedded as FooStruct") } } } struct FooStruct { flag: bool, widget: bool, value: uint }
true
df09b188f8de65b8cb831fc5571b433e0824e5bb
Rust
codeworm96/hikari
/src/yz_rect.rs
UTF-8
1,630
2.90625
3
[]
no_license
use crate::aabb::AABB; use crate::hitable::{HitRecord, Hitable}; use crate::material::Material; use crate::ray::Ray; use crate::vec3::Vec3; pub struct YzRect { y0: f64, y1: f64, z0: f64, z1: f64, k: f64, mat: Box<dyn Material + Sync>, } impl YzRect { pub fn new( y0: f64, y1: f64, z0: f64, z1: f64, k: f64, mat: Box<dyn Material + Sync>, ) -> YzRect { YzRect { y0, y1, z0, z1, k, mat, } } } impl Hitable for YzRect { fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { let t = (self.k - r.origin().x()) / r.direction().x(); if t < t_min || t > t_max { None } else { let y = r.origin().y() + t * r.direction().y(); let z = r.origin().z() + t * r.direction().z(); if y < self.y0 || y > self.y1 || z < self.z0 || z > self.z1 { None } else { Some(HitRecord { t, u: (y - self.y0) / (self.y1 - self.y0), v: (z - self.z0) / (self.z1 - self.z0), p: r.point_at_parameter(t), normal: Vec3::new(1.0, 0.0, 0.0), mat: &*self.mat, }) } } } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<AABB> { Some(AABB { min: Vec3::new(self.k - 0.0001, self.y0, self.z0), max: Vec3::new(self.k + 0.0001, self.y1, self.z1), }) } }
true
52b6ebddc24e44fa96126ff956e80387668e13e1
Rust
ravron/adventofcode2020
/src/day5.rs
UTF-8
1,504
3.703125
4
[]
no_license
pub fn day5() { let (p1, p2) = day5_impl(); println!("part 1: max seat is {}", p1); println!("part 2: your seat is {}", p2); } fn day5_impl() -> (usize, usize) { let input = include_str!("../inputs/day5.txt"); let mut all_seats = [false; 1024]; let mut min_seat: usize = u16::MAX as usize; let mut max_seat: usize = u16::MIN as usize; for seat in input.lines().map(parse_seat) { all_seats[seat] = true; min_seat = if seat < min_seat { seat } else { min_seat }; max_seat = if seat > max_seat { seat } else { max_seat }; } let mut part_2_seat: usize = 0; for (i, seat) in all_seats[min_seat..=max_seat].iter().enumerate() { if !seat { part_2_seat = i + min_seat; break; } } (max_seat, part_2_seat) } fn parse_seat(seat: &str) -> usize { let mut seat_id: usize = 0; for (i, c) in seat.bytes().enumerate() { match c { b'B' | b'R' => seat_id |= 0x200 >> i, b'F' | b'L' => (), _ => panic!("invalid char {}", c), } } seat_id } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn test_day5() { let (p1, p2) = day5_impl(); assert_eq!(p1, 850); assert_eq!(p2, 599); } #[bench] fn bench_day5(b: &mut Bencher) { b.iter(|| day5_impl()); } #[bench] fn bench_parse(b: &mut Bencher) { b.iter(|| parse_seat("BFFBFBFLRL")); } }
true
c49a563c7771bdba4ce8ea6299ef27ea8d4765e9
Rust
AliceLanniste/adventofcode
/day07/src/main.rs
UTF-8
5,229
2.96875
3
[]
no_license
/// day 7的part 1问题是有向图,从顶点到终点的要经过哪些,当遇到多条路径,按字母大小选择 /// part2的问题是现有5个通道,从顶点开始,依次安排5个通道,每个点运行的时间是('X' -'A' + 1)运行的时间总共是多少 #[macro_use] extern crate lazy_static; extern crate regex; use regex::Regex; use std::io::{self, Write}; use std::fs; use std::str::FromStr; use std::error::Error; use std::collections::{HashMap, HashSet}; type Result<T> = std::result::Result<T,Box<Error>>; type RequiredFor = HashMap<char, HashSet<char>>; fn main() ->Result<()>{ let input = fs::read_to_string("data/day7.txt").unwrap(); let mut instructions:Vec<Instruction> = vec![]; for line in input.lines() { let ins = line.parse().expect("failed parse"); instructions.push(ins); } let mut required_for: RequiredFor = HashMap::new(); for dep in &instructions { required_for.entry(dep.cur).or_default().insert(dep.last); required_for.entry(dep.last).or_default(); } part1(&required_for)?; part2(&required_for)?; Ok(()) } fn part1(require: &RequiredFor) -> Result<()> { let mut taken : HashSet<char>= HashSet::new(); let mut order: Vec<char> = vec![]; let mut next: Vec<char> = vec![]; loop { next_step(require, &taken, &taken, &mut next); let next_step = match next.pop(){ None => break, Some(s) => s, }; taken.insert(next_step); order.push(next_step); } let answer: String = order.iter().cloned().collect(); writeln!(io::stdout(), "step order: {}", answer)?; Ok(()) } fn part2(require: &RequiredFor) -> Result<()> { let mut workers = Worker::new(5); let mut gg :HashSet<char> = HashSet::new(); let mut done: HashSet<char> = HashSet::new(); let mut store: Vec<char> = vec![]; let mut next: Vec<char> = vec![]; let mut second = 0; loop { workers.run_one(&mut store, &mut done); next_step(require, &gg, &done, &mut next); if next.is_empty() && workers.all_idle() { break; } for worker in workers.available() { let next_step = match next.pop() { Some(next_step) => next_step, None => break, }; gg.insert(next_step); workers.work_on(worker, next_step); } second += 1 } let answer: String = store.iter().cloned().collect(); writeln!(io::stdout(), "step order (part 2): {}", answer)?; writeln!(io::stdout(), "total seconds: {}", second)?; Ok(()) } // fn next_step(required: &RequiredFor, taken: &HashSet<char>, done: &HashSet<char>, steps: &mut Vec<char>) { for(&step, ins) in required { if taken.contains(&step) { continue; } if ins.iter().all(|e| done.contains(e)) { steps.push(step); } } steps.sort(); steps.dedup(); steps.reverse(); } /* part 2 */ #[derive(Debug)] struct Worker { status: Vec<Status>, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum Status { Idle, Working {name: char, time: u32} } impl Worker { fn new(count: usize) -> Self { // the trait std::clone::Clone is not implemented Worker {status: vec![Status::Idle; count]} } fn available(&self) -> Vec<usize> { let mut idles = vec![]; for (worker, &status) in self.status.iter().enumerate() { if status == Status::Idle { idles.push(worker); } } idles } fn all_idle(&self) -> bool { // cannot be applied to type'Status' self.status.iter().all(|s| *s == Status::Idle) } fn work_on(&mut self, worker:usize, step:char) { let status = &mut self.status[worker]; let time =(step as u32) -b'A' as u32 + 1 + 60; *status = Status::Working{name:step, time} } fn run_one(&mut self, order: &mut Vec<char>, done: &mut HashSet<char>) { for w in 0..self.status.len() { let mut is_done = false; match self.status[w] { Status::Idle => {} Status::Working{name, ref mut time} => { *time -=1; if *time == 0 { is_done = true; order.push(name); done.insert(name); } } } if is_done { self.status[w] = Status::Idle; } } } } /* part 1 */ #[derive(Debug)] struct Instruction { cur: char, last: char, } impl FromStr for Instruction { type Err = Box<Error>; fn from_str(s: &str) -> Result<Self> { lazy_static! { static ref RE: Regex = Regex::new( r"Step ([A-Z]) must be finished before step ([A-Z]) can begin." ).unwrap(); } let caps = RE.captures(s).expect("failed to regex"); Ok(Instruction { cur: caps[2].as_bytes()[0] as char, last: caps[1].as_bytes()[0] as char, }) } }
true
df03c510ded975bb54fa41b748fa399219148aa1
Rust
across-travel/kayrx-ui
/src/widget/label.rs
UTF-8
784
2.765625
3
[ "MIT" ]
permissive
use crate::fabric::prelude::*; pub struct Label { props: Props, } #[derive(Clone, Properties)] pub struct Props { #[prop_or_default] pub value: String, #[prop_or_default] pub disabled: bool, } impl Component for Label { type Message = (); type Properties = Props; fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self { Label { props } } fn update(&mut self, _: Self::Message) -> ShouldRender { false } fn change(&mut self, props: Self::Properties) -> ShouldRender { self.props = props; true } fn view(&self) -> Html { html! { <span disabled=self.props.disabled class="bow-label">{&self.props.value}</span> } } }
true
1b203790738b4ca3d78c2cfd3de6271d8e807a18
Rust
ryanpbrewster/rust-project-euler
/src/util/prime/wheel.rs
UTF-8
1,229
3.78125
4
[]
no_license
// Specifically a [2;3;5;7] wheel pub struct Wheel { n: u64, idx: usize, } const SPOKES: [u64; 48] = [ 10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, ]; impl Wheel { pub fn new() -> Wheel { Wheel { n: 1, idx: 0 } } } impl Iterator for Wheel { type Item = u64; fn next(&mut self) -> Option<u64> { self.n += SPOKES[self.idx % SPOKES.len()]; self.idx += 1; Some(self.n) } } #[cfg(test)] mod test { use super::*; // Values produced by a [2;3;5;7] wheel should not be divisible by 2, 3, 5, or 7 fn check(n: u64) -> bool { n % 2 != 0 && n % 3 != 0 && n % 5 != 0 && n % 7 != 0 } #[test] fn definition() { for n in Wheel::new().take(1_000) { assert!(check(n)); } } #[test] fn compactness() { // Ensure that Wheel produces exactly the set of numbers not divisible for 2, 3, 5, or 7 let expected: Vec<u64> = (2..1000).filter(|&n| check(n)).collect(); let actual: Vec<u64> = Wheel::new().take_while(|&n| n < 1000).collect(); assert_eq!(actual, expected); } }
true
f11068d505a0f647f66c8ae5c5153f775f798da2
Rust
weswigham/fontdue
/src/platform/float/floor.rs
UTF-8
1,219
2.84375
3
[ "MIT" ]
permissive
#[cfg(target_arch = "x86")] use core::arch::x86::*; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::*; #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] // [See license/rust-lang/libm] Copyright (c) 2018 Jorge Aparicio pub fn floor(x: f32) -> f32 { let mut ui = x.to_bits(); let e = (((ui >> 23) as i32) & 0xff) - 0x7f; if e >= 23 { return x; } if e >= 0 { let m: u32 = 0x007fffff >> e; if (ui & m) == 0 { return x; } if ui >> 31 != 0 { ui += m; } ui &= !m; } else { if ui >> 31 == 0 { ui = 0; } else if ui << 1 != 0 { return -1.0; } } f32::from_bits(ui) } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[inline(always)] pub fn floor(mut value: f32) -> f32 { use crate::platform::is_negative; use core::mem::transmute; unsafe { // The gist: sub 1, sub epsilon, then truncate. If positive, just truncate. if is_negative(value) { value = transmute::<u32, f32>(transmute::<f32, u32>(value - 1.0) - 1); } _mm_cvtss_f32(_mm_cvtepi32_ps(_mm_cvttps_epi32(_mm_set_ss(value)))) } }
true
7091158001a28f69d81ed9642a356a170bac8cba
Rust
tp971/ccsrs
/src/parser/lexer.rs
UTF-8
9,263
3.203125
3
[]
no_license
use std::collections::vec_deque::VecDeque; use std::io; use super::*; pub struct Lexer<I: Iterator<Item = io::Result<u8>>> { input: I, row: usize, col: usize, ch: Option<char>, lookahead: usize, tokens: VecDeque<Result<TokenInfo>> } impl<I: Iterator<Item = io::Result<u8>>> Lexer<I> { pub fn new(input: I, lookahead: usize) -> Lexer<I> { Lexer { input, row: 0, col: 0, ch: None, lookahead, tokens: VecDeque::with_capacity(lookahead) } } pub fn input_mut(&mut self) -> &mut I { &mut self.input } pub fn skipline(&mut self) { self.tokens.clear(); loop { match self.ch { Some('\n') => break, None => break, _ => self._read() } } } pub fn peek(&mut self, i: usize) -> Result<TokenInfo> { assert!(i < self.lookahead); while i >= self.tokens.len() { let next = self._next(); self.tokens.push_back(next); } self.tokens[i].clone() } pub fn next(&mut self) { self.tokens.pop_front(); } fn _next(&mut self) -> Result<TokenInfo> { if self.row == 0 { self.row += 1; self._read(); } loop { match self.ch { Some(ch) if ch.is_whitespace() => self._read(), _ => break } } if self.ch.is_none() { return Ok(TokenInfo { loc: Location::new(self.row, self.col), token: Token::EOF }); } let loc = Location::new(self.row, self.col); let token = match self.ch { Some('(') => { self._read(); Ok(Token::LPAR) }, Some(')') => { self._read(); Ok(Token::RPAR) }, Some('[') => { self._read(); Ok(Token::LSQBR) }, Some(']') => { self._read(); Ok(Token::RSQBR) }, Some('{') => { self._read(); Ok(Token::LBRACE) }, Some('}') => { self._read(); Ok(Token::RBRACE) }, Some('.') => { self._read(); Ok(Token::DOT) }, Some(',') => { self._read(); Ok(Token::COMMA) }, Some(';') => { self._read(); Ok(Token::SEMICOLON) }, Some('\\') => { self._read(); Ok(Token::BACKSLASH) }, Some('+') => { self._read(); Ok(Token::PLUS) }, Some('-') => { self._read(); Ok(Token::MINUS) }, Some('*') => { self._read(); Ok(Token::STAR) }, Some('%') => { self._read(); Ok(Token::PERCENT) }, Some('?') => { self._read(); Ok(Token::QUESTIONMARK) }, Some('^') => { self._read(); Ok(Token::HAT) }, Some('/') => { self._read(); match self.ch { Some('/') => { self.skipline(); return self._next() }, Some('*') => { let mut last = '\0'; let mut depth = 1; while depth > 0 { self._read(); match (last, self.ch) { ('/', Some('*')) => { depth += 1; last = '\0'; }, ('*', Some('/')) => { depth -= 1; last = '\0'; }, (_, Some(ch)) => last = ch, (_, None) => break }; } self._read(); return self._next() }, _ => Ok(Token::SLASH) } }, Some(':') => { self._read(); match self.ch { Some('=') => { self._read(); Ok(Token::COLONEQ) }, _ => Ok(Token::COLON) } }, Some('=') => { self._read(); match self.ch { Some('=') => { self._read(); Ok(Token::EQEQ) }, _ => Ok(Token::EQ) } }, Some('!') => { self._read(); match self.ch { Some('=') => { self._read(); Ok(Token::BANGEQ) }, _ => Ok(Token::BANG) } }, Some('&') => { self._read(); match self.ch { Some('&') => { self._read(); Ok(Token::ANDAND) }, _ => Ok(Token::AND) } }, Some('|') => { self._read(); match self.ch { Some('|') => { self._read(); Ok(Token::PIPEPIPE) }, _ => Ok(Token::PIPE) } }, Some('<') => { self._read(); match self.ch { Some('=') => { self._read(); Ok(Token::LESSEQ) }, _ => Ok(Token::LESS) } }, Some('>') => { self._read(); match self.ch { Some('=') => { self._read(); Ok(Token::GREATEREQ) }, _ => Ok(Token::GREATER) } }, Some('$') => self._next_id(), Some('"') => self._next_str(), Some(ch) => { if ch.is_alphabetic() || ch == '_' { self._next_id() } else if ch.is_numeric() || ch == '.' { self._next_num() } else { Err(self._error_skip(format!("unexpected `{}`", ch))) } }, None => { Err(self._error_skip("unexpected end of file".to_string())) } }?; Ok(TokenInfo { loc, token }) } fn _next_str(&mut self) -> Result<Token> { match self.ch { Some('"') => {}, _ => return Err(ParserError::new(Location::new(self.row, self.col), "expected `'`".to_string())) } let mut s = Vec::new(); loop { match self.input.next() { Some(Ok(b'"')) => break, //TODO string escape Some(Ok(ch)) if ch == b'\r' || ch == b'\n' => { self.ch = Some(ch as char); self.row += 1; self.col = 0; return Err(ParserError::new(Location::new(self.row, self.col), "unexpected newline".to_string())) }, Some(Ok(ch)) => s.push(ch), _ => return Err(ParserError::new(Location::new(self.row, self.col), "unexpected end of file".to_string())) }; } let s = String::from_utf8_lossy(&s).to_string(); self.col += 1 + s.chars().count(); self._read(); Ok(Token::STR(s)) } fn _next_id(&mut self) -> Result<Token> { let mut name = String::new(); loop { match self.ch { Some(ch) if ch.is_alphanumeric() || ch == '_' || ch == '$' => { name.push(ch); self._read(); }, _ => { break; } } } Ok(match name.as_ref() { "true" => Token::TRUE, "false" => Token::FALSE, "when" => Token::WHEN, _ => Token::ID(name) }) } fn _next_num(&mut self) -> Result<Token> { let loc = Location::new(self.row, self.col); let mut num = String::new(); loop { match self.ch { Some(ch) if ch.is_numeric() => { num.push(ch); self._read(); }, _ => { break; } } } match num.parse::<i64>() { Ok(num) => Ok(Token::INT(num)), Err(_) => Err(ParserError::new(loc, "invalid number".to_string())) } } fn _error_skip(&mut self, desc: String) -> ParserError { let res = ParserError::new(Location::new(self.row, self.col), desc); self._read(); res } fn _read(&mut self) { let ch = match self.input.next() { Some(Ok(ch)) if ch <= 127u8 => Some(ch as char), Some(Ok(_)) => Some(std::char::REPLACEMENT_CHARACTER), _ => None }; match ch { Some('\r') | Some('\n') => { match (self.ch, ch) { (Some('\r'), Some('\n')) => {}, _ => { self.row += 1; self.col = 0; } } }, _ => { self.col += 1; } } self.ch = ch; } }
true
0195a5d44751217c9ed12ca01a6c0e5ca2dbb2af
Rust
Shizcow/emoji-rs
/generate/src/emoji.rs
UTF-8
5,916
2.65625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; use std::collections::HashMap; use crate::sanitize; use itertools::Itertools; #[derive(Debug)] pub struct Emoji { pub codepoint: String, pub status: Status, pub glyph: String, pub introduction_version: f32, pub name: String, pub variants: Vec<Emoji>, pub annotations: Vec<Annotation>, pub is_variant: bool, pub group: String, pub subgroup: String, } impl Emoji { pub fn new( line: &str, annotations_map: &HashMap<String, Vec<Annotation>>, group: String, subgroup: String, ) -> Self { let first_components: Vec<&str> = line.split(";").collect(); let reformed_first = first_components.iter().skip(1).join(";"); let codepoint = first_components[0].trim().to_owned(); let second_components: Vec<&str> = reformed_first.split("#").collect(); let status = Status::new(second_components[0].trim()); let reformed_second = second_components.iter().skip(1).join("#"); let third_components: Vec<&str> = reformed_second.trim().split("E").collect(); let glyph = third_components[0].trim().to_owned(); let reformed_third = third_components.iter().skip(1).join("E"); let introduction_version = reformed_third .split(" ") .nth(0) .unwrap() .parse::<f32>() .unwrap(); let name = reformed_third.split(" ").skip(1).join(" "); let annotations = match annotations_map.get(&glyph) { None => vec![], Some(a) => a.to_vec(), }; Self { codepoint, status, glyph, introduction_version, name, variants: vec![], annotations, is_variant: false, group, subgroup, } } pub fn add_variant(&mut self, mut variant: Emoji) { variant.is_variant = true; for a in &mut self.annotations { if let Some(a_other) = variant.annotations.iter_mut().find(|i| i.lang == a.lang) { if a_other.tts.is_some() { if a.tts.is_none() { a.tts = a_other.tts.clone(); } a_other.tts = None; } } } self.annotations.append(&mut variant.annotations); self.variants.push(variant); } pub fn ident(&self) -> String { sanitize(&self.name).to_uppercase() } fn tokens_internal(&self) -> TokenStream { let glyph = &self.glyph; let codepoint = &self.codepoint; let name = &self.name; let status = Ident::new(&self.status.to_string(), Span::call_site()); let introduction_version = self.introduction_version; let variants: Vec<TokenStream> = self.variants.iter().map(|e| e.tokens_internal()).collect(); let annotations = &self.annotations; let is_variant = &self.is_variant; let group = &self.group; let subgroup = &self.subgroup; (quote! { crate::Emoji{ glyph: #glyph, codepoint: #codepoint, status: crate::Status::#status, introduction_version: #introduction_version, name: #name, group: #group, subgroup: #subgroup, is_variant: #is_variant, variants: &[#(#variants),*], annotations: &[#(#annotations),*], } }) .into() } } impl ToTokens for Emoji { fn to_tokens(&self, tokens: &mut TokenStream) { let ident = Ident::new(&self.ident(), Span::call_site()); let tokns = self.tokens_internal(); let glyph = &self.glyph; (quote! { #[doc = #glyph] pub const #ident: crate::Emoji = #tokns; }).to_tokens(tokens); } } #[derive(Debug, PartialEq)] pub enum Status { Component, FullyQualified, MinimallyQualified, Unqualified, } impl Status { pub fn new(name: &str) -> Self { use Status::*; match name { "component" => Component, "fully-qualified" => FullyQualified, "minimally-qualified" => MinimallyQualified, "unqualified" => Unqualified, unknown => panic!("Unknown qualifier {}", unknown), } } } impl std::fmt::Display for Status { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { use Status::*; write!( f, "{}", match self { Component => "Component", FullyQualified => "FullyQualified", MinimallyQualified => "MinimallyQualified", Unqualified => "Unqualified", } ) } } #[derive(Debug, Clone)] pub struct Annotation { pub lang: String, pub tts: Option<String>, pub keywords: Vec<String>, } impl Annotation { pub fn new(lang: String, tts: Option<String>, keywords: String) -> Self { let mut s = Self { lang, tts, keywords: vec![], }; s.add_keywords(keywords); s } pub fn add_keywords(&mut self, keywords: String) { let mut v = keywords.split("|").map(|a| a.trim().to_owned()).collect(); self.keywords.append(&mut v); self.keywords.sort(); self.keywords.dedup(); } } impl ToTokens for Annotation { fn to_tokens(&self, tokens: &mut TokenStream) { let lang = &self.lang; let tts = match &self.tts { None => quote! { None }, Some(tts) => quote! { Some(#tts) }, }; let keywords = &self.keywords; (quote! { #[cfg(feature = #lang)] crate::Annotation { lang: #lang, tts: #tts, keywords: &[#(#keywords),*], } }).to_tokens(tokens); } }
true
797b2ef372b4d517c80bacd72ff31e15916cf8e2
Rust
spuyet/chip8
/rust/src/chip8/cpu.rs
UTF-8
4,490
3.09375
3
[]
no_license
use std::ptr; const REGISTER_COUNT : usize = 16; const STACK_SIZE : usize = 16; pub struct Cpu { registers: [u8; REGISTER_COUNT], stack: [u16; STACK_SIZE], opcode: u16, i: u16, sp: u16, pc: u16, } impl Cpu { pub fn new() -> Cpu { let mut cpu = Cpu { registers: [0; REGISTER_COUNT], stack: [0; STACK_SIZE], opcode: 0, i: 0, sp: 0, pc: 0x200 }; cpu.clear(); cpu } pub fn clear(&mut self) { self.pc = 0x200; unsafe { let reg_ptr = self.registers.as_mut_ptr(); ptr::write_bytes(reg_ptr, 0, REGISTER_COUNT); let stack_ptr = self.stack.as_mut_ptr(); ptr::write_bytes(stack_ptr, 0, STACK_SIZE); } } pub fn step(&mut self, memory: &mut [u8], screen: &mut [u64]) { let pc = self.pc as usize; let opcode = &memory[pc..(pc+2)]; println!("{:x?}", opcode); match opcode[0] >> 4 { 0x0 => println!("0x0 => ignored"), // 0nnn - SYS addr 0x1 => println!("0x1"), 0x2 => { // 2nnn - CALL addr self.stack[self.sp as usize] = self.pc; self.sp += 1; let mut pc = ((opcode[0] & 0xF) as u16) << 8; pc |= opcode[1] as u16; self.pc = pc; return } 0x3 => println!("0x3"), 0x4 => println!("0x4"), 0x5 => println!("0x5"), 0x6 => self.registers[(opcode[0] & 0xF) as usize] = opcode[1], // 6xkk - LD Vx, byte 0x7 => self.registers[(opcode[0] & 0xF) as usize] += opcode[1], // 7xkk - ADD Vx, byte 0x8 => { match opcode[1] & 0xF { 0x0 => self.registers[(opcode[0] & 0xF) as usize] = self.registers[(opcode[1] >> 4) as usize], // 8xy0 - LD Vx, Vy _ => () } } 0x9 => println!("0x9"), 0xA => { // Annn - LD I, addr self.i = ((opcode[0] & 0xF) as u16) << 8; self.i |= opcode[1] as u16; } 0xB => println!("0xB"), 0xC => println!("0xC"), 0xD => self.screen_update(opcode, memory, screen), // Dxyn - DRW Vx, Vy, nibble 0xE => println!("0xE"), 0xF => self.fx_instruction(opcode[1], opcode[0] & 0xF, memory), _ => () } println!("registers: {:x?}", self.registers); println!("stack: {:x?}", self.stack); println!("pc: {:x?}", self.pc); println!("I: {:x?}", self.i); println!("memory: {:x?}", memory); println!("\n"); self.pc += 2; } fn fx_instruction(&mut self, instruction: u8, register: u8, memory: &mut [u8]) { match instruction { 0x29 => self.i = (register * 5) as u16, 0x33 => { let v = self.registers[register as usize]; memory[self.i as usize] = (v / 100) as u8; memory[(self.i + 1) as usize] = (v / 10 % 10) as u8; memory[(self.i + 2) as usize] = (v % 100 % 10) as u8; }, 0x65 => { let mut count = self.i as usize; for i in 0..(register + 1) { self.registers[i as usize] = memory[count]; count += 1; } } _ => () } } fn screen_update(&mut self, opcode: &[u8], memory: &[u8], screen: &mut [u64]) { let x = self.registers[(opcode[0] & 0x0F) as usize]; let y = self.registers[(opcode[1] >> 4) as usize]; let n = (opcode[1] & 0x0F) as usize; let mut j = self.i as usize; let mut update = 0; for i in (y as usize)..((y as usize) + n) { let v = memory[j] as u64; let before = screen[i]; screen[i] ^= v << ((7 - x % 8) * 8); if before != screen[i] { update = 1; } j += 1; } self.registers[0xF] = update; } }
true
98495614c724b5433b904b9130ded5a8833a3c68
Rust
tuckerthomas/kekw_bot
/src/commands/movie.rs
UTF-8
5,924
2.859375
3
[]
no_license
use serenity::prelude::*; use serenity::model::prelude::*; use serenity::framework::standard::{ Args, CommandResult, macros::command, }; use tracing::{info, error}; use crate::db::{ DBConnectionContainer, moviesubs }; use crate::models::MovieSub; #[command] pub async fn submit(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { if args.is_empty() { if let Err(why) = msg.channel_id.say(&ctx.http, "No movie supplied.").await { error!("Error sending message: {:?}", why); } } else { let movie_submission = args.rest(); let db_pool = { // While data is a RwLock, it's recommended that you always open the lock as read. // This is mainly done to avoid Deadlocks for having a possible writer waiting for multiple // readers to close. let data_read = ctx.data.read().await; // Since the CommandCounter Value is wrapped in an Arc, cloning will not duplicate the // data, instead the reference is cloned. // We wap every value on in an Arc, as to keep the data lock open for the least time possible, // to again, avoid deadlocking it. data_read.get::<DBConnectionContainer>().expect("Expected DBConnection in TypeMap.").clone() }; let movie_subs = moviesubs::check_prev_sub(&db_pool.get().unwrap(), &msg.author.id.to_string()); let mut response = String::new(); if movie_subs.len() == 0 { let num_added = moviesubs::create_moviesub(&db_pool.get().unwrap(), &msg.author.id.to_string(), movie_submission, "test"); info!("Added {} movie submissions.", num_added); response = format!("You've submitted the movie: {}", movie_submission); info!("{}:{} submitted movie {}", msg.author, msg.author.name, movie_submission); msg.channel_id.say(&ctx.http, response).await?; } else { use std::convert::TryFrom; let mut reactions: Vec<ReactionType> = Vec::new(); reactions.push(ReactionType::try_from("✅").unwrap()); reactions.push(ReactionType::try_from("❎").unwrap()); response = format!("You've already submitted the movie: {}, would you like to update your submission?", movie_subs[0].title); let mut update_sub_msg = msg.channel_id.send_message(&ctx.http, |m| { m.content(response); m.reactions(reactions); m }).await.unwrap(); if let Some(reaction) = &update_sub_msg.await_reaction(&ctx).timeout(std::time::Duration::from_secs(10)).author_id(msg.author.id).await { let emoji = &reaction.as_inner_ref().emoji; let _ = match emoji.as_data().as_str() { "✅" => { moviesubs::delete_moviesub(&db_pool.get().unwrap(), movie_subs[0].id); moviesubs::create_moviesub(&db_pool.get().unwrap(), &msg.author.id.to_string(), movie_submission, "test"); update_sub_msg.edit(ctx, |m| m.content("Submission updated!")).await?; update_sub_msg.delete_reactions(ctx).await?; Ok(update_sub_msg) }, "❎" => { update_sub_msg.edit(ctx, |m| m.content("Submission not updated.")).await?; update_sub_msg.delete_reactions(ctx).await?; Ok(update_sub_msg) }, _ => msg.reply(ctx, "Please react with ✅ or ❎").await, }; } else { msg.reply(ctx, "No reaction within 10 seconds.").await?; } } } Ok(()) } #[command] pub async fn getsubs(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let db_pool = { // While data is a RwLock, it's recommended that you always open the lock as read. // This is mainly done to avoid Deadlocks for having a possible writer waiting for multiple // readers to close. let data_read = ctx.data.read().await; // Since the CommandCounter Value is wrapped in an Arc, cloning will not duplicate the // data, instead the reference is cloned. // We wap every value on in an Arc, as to keep the data lock open for the least time possible, // to again, avoid deadlocking it. data_read.get::<DBConnectionContainer>().expect("Expected DBConnection in TypeMap.").clone() }; // Query DB let movie_subs = moviesubs::get_moviesubs(&db_pool.get().unwrap()); info!("Got {} movie submission(s).", movie_subs.len()); // Struct to help with information gathered from the DB struct DisMovieSub { movie_sub: MovieSub, user: User, nick: String } let mut dis_movie_subs: Vec<DisMovieSub> = Vec::new(); use std::convert::TryFrom; // TODO: Move to closure once async closures are a thing. for movie_sub in movie_subs.clone() { let user_id: u64 = movie_sub.dis_user_id.parse().unwrap(); let user = UserId::try_from(user_id).unwrap().to_user(&ctx.http).await?; let nick = user.nick_in(&ctx.http, msg.guild_id.unwrap()).await.unwrap(); dis_movie_subs.push(DisMovieSub {movie_sub, user, nick}); } use serenity::model::id::UserId; msg.channel_id.send_message(&ctx.http, |m| { m.embed(|mut e| { e.title("Current Movie Submissions"); for dis_movie_sub in dis_movie_subs { e.field( format!("{}({})", dis_movie_sub.nick, dis_movie_sub.user.name), dis_movie_sub.movie_sub.title, false ); } e }); m }).await?; Ok(()) }
true
41e3b3f206d43243b1bba0d3ec14d7a8fcacb1da
Rust
VIP21/solana
/sdk/src/system_transaction.rs
UTF-8
2,459
2.734375
3
[ "Apache-2.0" ]
permissive
//! The `system_transaction` module provides functionality for creating system transactions. use crate::{ hash::Hash, pubkey::Pubkey, signature::{Keypair, KeypairUtil}, system_instruction, transaction::Transaction, }; /// Create and sign new SystemInstruction::CreateAccount transaction pub fn create_account( from_keypair: &Keypair, to_keypair: &Keypair, recent_blockhash: Hash, lamports: u64, space: u64, program_id: &Pubkey, ) -> Transaction { let from_pubkey = from_keypair.pubkey(); let to_pubkey = to_keypair.pubkey(); let create_instruction = system_instruction::create_account(&from_pubkey, &to_pubkey, lamports, space, program_id); let instructions = vec![create_instruction]; Transaction::new_signed_instructions( &[from_keypair, to_keypair], instructions, recent_blockhash, ) } /// Create and sign new system_instruction::Assign transaction pub fn assign(from_keypair: &Keypair, recent_blockhash: Hash, program_id: &Pubkey) -> Transaction { let from_pubkey = from_keypair.pubkey(); let assign_instruction = system_instruction::assign(&from_pubkey, program_id); let instructions = vec![assign_instruction]; Transaction::new_signed_instructions(&[from_keypair], instructions, recent_blockhash) } /// Create and sign new system_instruction::Transfer transaction pub fn transfer( from_keypair: &Keypair, to: &Pubkey, lamports: u64, recent_blockhash: Hash, ) -> Transaction { let from_pubkey = from_keypair.pubkey(); let transfer_instruction = system_instruction::transfer(&from_pubkey, to, lamports); let instructions = vec![transfer_instruction]; Transaction::new_signed_instructions(&[from_keypair], instructions, recent_blockhash) } /// Create and sign new nonced system_instruction::Transfer transaction pub fn nonced_transfer( from_keypair: &Keypair, to: &Pubkey, lamports: u64, nonce_account: &Pubkey, nonce_authority: &Keypair, nonce_hash: Hash, ) -> Transaction { let from_pubkey = from_keypair.pubkey(); let transfer_instruction = system_instruction::transfer(&from_pubkey, to, lamports); let instructions = vec![transfer_instruction]; Transaction::new_signed_with_nonce( instructions, Some(&from_pubkey), &[from_keypair, nonce_authority], nonce_account, &nonce_authority.pubkey(), nonce_hash, ) }
true
73f48a89765a991f8a81e00c88170119b0433935
Rust
tirust/msp432e4
/src/sysctl/pcssi.rs
UTF-8
7,494
2.8125
3
[ "BSD-3-Clause" ]
permissive
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::PCSSI { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct SYSCTL_PCSSI_P0R { bits: bool, } impl SYSCTL_PCSSI_P0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCSSI_P0W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCSSI_P0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCSSI_P1R { bits: bool, } impl SYSCTL_PCSSI_P1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCSSI_P1W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCSSI_P1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCSSI_P2R { bits: bool, } impl SYSCTL_PCSSI_P2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCSSI_P2W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCSSI_P2W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCSSI_P3R { bits: bool, } impl SYSCTL_PCSSI_P3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCSSI_P3W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCSSI_P3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - SSI Module 0 Power Control"] #[inline(always)] pub fn sysctl_pcssi_p0(&self) -> SYSCTL_PCSSI_P0R { let bits = ((self.bits >> 0) & 1) != 0; SYSCTL_PCSSI_P0R { bits } } #[doc = "Bit 1 - SSI Module 1 Power Control"] #[inline(always)] pub fn sysctl_pcssi_p1(&self) -> SYSCTL_PCSSI_P1R { let bits = ((self.bits >> 1) & 1) != 0; SYSCTL_PCSSI_P1R { bits } } #[doc = "Bit 2 - SSI Module 2 Power Control"] #[inline(always)] pub fn sysctl_pcssi_p2(&self) -> SYSCTL_PCSSI_P2R { let bits = ((self.bits >> 2) & 1) != 0; SYSCTL_PCSSI_P2R { bits } } #[doc = "Bit 3 - SSI Module 3 Power Control"] #[inline(always)] pub fn sysctl_pcssi_p3(&self) -> SYSCTL_PCSSI_P3R { let bits = ((self.bits >> 3) & 1) != 0; SYSCTL_PCSSI_P3R { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - SSI Module 0 Power Control"] #[inline(always)] pub fn sysctl_pcssi_p0(&mut self) -> _SYSCTL_PCSSI_P0W { _SYSCTL_PCSSI_P0W { w: self } } #[doc = "Bit 1 - SSI Module 1 Power Control"] #[inline(always)] pub fn sysctl_pcssi_p1(&mut self) -> _SYSCTL_PCSSI_P1W { _SYSCTL_PCSSI_P1W { w: self } } #[doc = "Bit 2 - SSI Module 2 Power Control"] #[inline(always)] pub fn sysctl_pcssi_p2(&mut self) -> _SYSCTL_PCSSI_P2W { _SYSCTL_PCSSI_P2W { w: self } } #[doc = "Bit 3 - SSI Module 3 Power Control"] #[inline(always)] pub fn sysctl_pcssi_p3(&mut self) -> _SYSCTL_PCSSI_P3W { _SYSCTL_PCSSI_P3W { w: self } } }
true
a9318bae951c7a1979e6abecfa9409be705e11ee
Rust
huggingface/tokenizers
/tokenizers/src/normalizers/bert.rs
UTF-8
4,203
3.203125
3
[ "Apache-2.0" ]
permissive
use crate::tokenizer::{NormalizedString, Normalizer, Result}; use serde::{Deserialize, Serialize}; use unicode_categories::UnicodeCategories; /// Checks whether a character is whitespace fn is_whitespace(c: char) -> bool { // These are technically control characters but we count them as whitespace match c { '\t' | '\n' | '\r' => true, _ => c.is_whitespace(), } } /// Checks whether a character is a control character fn is_control(c: char) -> bool { // These are technically control characters but we count them as whitespace match c { '\t' | '\n' | '\r' => false, // The definition of `is_control` here is quite large and contains also // Cc, Cf, Cn or Co // cf. https://unicode.org/reports/tr44/ (Table 12) _ => c.is_other(), } } /// Checks whether a character is chinese /// This defines a "chinese character" as anything in the CJK Unicode block: /// https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) /// /// Note that the CJK Unicode block is NOT all Japanese and Korean characters, /// despite its name. The modern Korean Hangul alphabet is a different block, /// as is Japanese Hiragana and Katakana. Those alphabets are used to write /// space-separated words, so they are not treated specially and handled /// like for all of the other languages. fn is_chinese_char(c: char) -> bool { matches!( c as usize, 0x4E00..=0x9FFF | 0x3400..=0x4DBF | 0x20000..=0x2A6DF | 0x2A700..=0x2B73F | 0x2B740..=0x2B81F | 0x2B920..=0x2CEAF | 0xF900..=0xFAFF | 0x2F800..=0x2FA1F ) } #[derive(Copy, Clone, Debug, Deserialize, Serialize)] #[serde(tag = "type")] #[non_exhaustive] pub struct BertNormalizer { /// Whether to do the bert basic cleaning: /// 1. Remove any control characters /// 2. Replace all sorts of whitespace by the classic one ` ` pub clean_text: bool, /// Whether to put spaces around chinese characters so they get split pub handle_chinese_chars: bool, /// Whether to strip accents pub strip_accents: Option<bool>, /// Whether to lowercase the input pub lowercase: bool, } impl Default for BertNormalizer { fn default() -> Self { Self { clean_text: true, handle_chinese_chars: true, strip_accents: None, lowercase: true, } } } impl BertNormalizer { pub fn new( clean_text: bool, handle_chinese_chars: bool, strip_accents: Option<bool>, lowercase: bool, ) -> Self { Self { clean_text, handle_chinese_chars, strip_accents, lowercase, } } fn do_clean_text(&self, normalized: &mut NormalizedString) { normalized .filter(|c| !(c as usize == 0 || c as usize == 0xfffd || is_control(c))) .map(|c| if is_whitespace(c) { ' ' } else { c }); } fn do_handle_chinese_chars(&self, normalized: &mut NormalizedString) { let mut new_chars: Vec<(char, isize)> = vec![]; normalized.for_each(|c| { if is_chinese_char(c) { new_chars.extend([(' ', 0), (c, 1), (' ', 1)]); } else { new_chars.push((c, 0)); } }); normalized.transform(new_chars, 0); } fn do_strip_accents(&self, normalized: &mut NormalizedString) { normalized.nfd().filter(|c| !c.is_mark_nonspacing()); } fn do_lowercase(&self, normalized: &mut NormalizedString) { normalized.lowercase(); } } impl Normalizer for BertNormalizer { fn normalize(&self, normalized: &mut NormalizedString) -> Result<()> { if self.clean_text { self.do_clean_text(normalized); } if self.handle_chinese_chars { self.do_handle_chinese_chars(normalized); } let strip_accents = self.strip_accents.unwrap_or(self.lowercase); if strip_accents { self.do_strip_accents(normalized); } if self.lowercase { self.do_lowercase(normalized); } Ok(()) } }
true
8f5117a93102276e0fa8648f381d5b58332ed92f
Rust
kbukum/rust_samples
/src/sample1/if_loop.rs
UTF-8
1,591
4.28125
4
[ "MIT" ]
permissive
pub fn test(){ println!("## Loops Tests "); // ## if and loop statements // ## if statement equalsFiveOrNot(5); equalsFiveOrNot(6); equalsFiveOrNot(7); let x = 5; let result = if x == 5 { "x equals 5" } else { "x is not equals 5" }; println!("check x result = {:?}", result); let mut x = 0; println!("Loop will exist if x equals 5"); /* #### loop */ loop { if x == 5 { break; } x = x + 1; println!("Loop counter = {:?}", x); } /* #### while */ println!("While will exist if x equals 0"); while x > 0 { println!("While counter = {:?}", x); x = x - 1; } /* #### for */ for i in 0..10 { println!("for counter i {:?}", i); // x: i32 } for (index, value) in (5..10).enumerate() { println!("index = {} and value = {}", index, value); } let lines = "hello\nworld".lines(); for (linenumber, line) in lines.enumerate() { println!("{}: {}", linenumber, line); } /* #### labels */ 'outer: for x in 0..10 { 'inner: for y in 0..10 { if x % 2 == 0 { continue 'outer; } // Continues the loop over `x`. if y % 2 == 0 { continue 'inner; } // Continues the loop over `y`. println!("x: {}, y: {}", x, y); } } } fn equalsFiveOrNot(x: i32){ if x == 5 { println!("{:?} is equals 5", x); } else if x == 6 { println!("{:?} is equals 6", x); } else { println!("{:?} is not equals 5 or 6", x); } }
true
7cfcd64160834b55d829c35ee6e78c33a81b53eb
Rust
GaloisInc/crucible
/crux-mir/test/conc_eval/traits/generic3.rs
UTF-8
729
3.03125
3
[ "BSD-3-Clause" ]
permissive
// Trait with generic method #![cfg_attr(not(with_main), no_std)] #[derive(Clone, Copy)] struct S; trait Foo5 { fn generic<T>(&self, x: T) -> T; } impl Foo5 for S { fn generic<T>(&self, x: T) -> T { x } } impl<T: Foo5> Foo5 for Option<T> { fn generic<U>(&self, y: U) -> U { if let Some(ref x) = *self { x.generic(y) } else { y } } } fn call_generic<T: Foo5, U>(x: &T, y: U) -> U { x.generic(y) } const ARG: i32 = 1; fn f(arg: i32) { let some_s = Some(S); assert!(call_generic(&some_s, 1) == 1); } #[cfg(with_main)] pub fn main() { println!("{:?}", f(ARG)); } #[cfg(not(with_main))] #[cfg_attr(crux, crux::test)] fn crux_test() -> () { f(ARG) }
true
8bd2e4de65efeafdc55cf9ca7f8b208ea484f122
Rust
youngqqcn/RustNotes
/examples/ch10/trait_object_1.rs
UTF-8
2,263
3.96875
4
[]
no_license
pub trait Draw { fn draw(&self); } pub struct Screen { pub components: Vec<Box<dyn Draw>>, // trait对象:它是 Box 中任何实现了 Draw trait 的类型的替身 } impl Screen { //这与定义使用了带有 trait bound 的泛型类型参数的结构体不同。 //泛型类型参数一次只能替代一个具体类型,而 trait 对象则允许在运行时替代多种具体类型 pub fn run(&self) { for component in self.components.iter() { component.draw(); //调用组件的draw方法, 其组件必须是实现了 Draw trait 的 trait对象 } } } /* //使用 泛型类型参数结构体 trait bound // 这限制了 Screen 实例必须拥有一个全是 Button 类型或者全是 TextField 类型的组件列表 pub struct Screen<T: Draw> { pub components: Vec<T>, } impl<T> Screen<T> where T: Draw { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } */ pub struct Button { pub width: u32, pub height: u32, pub label: String, } impl Draw for Button { fn draw(&self) { println!("Button draw: {}, {}, {}", self.width, self.height, self.label); } } struct SelectBox { width: u32, height: u32, options: Vec<String>, } impl Draw for SelectBox { fn draw(&self) { println!("SelectBox draw:{}, {}, {:?}", self.width, self.height, self.options); } } struct LineEdit { width: u32, } fn main() { let screen = Screen { components: vec![ Box::new(SelectBox{ width: 89, height:90, options: vec![ String::from("ok"), String::from("this"), String::from("rust"), ] }), Box::new( Button { width: 50, height: 10, label: String::from("Ok Button"), }), //尝试使用 未实现 Draw trait的 struct // 则编译报错: the trait `Draw` is not implemented for `LineEdit` Box::new(LineEdit{ width: 100, }), ], }; screen.run(); //运行 }
true
d9b4b7d15907b0c4805e9e16c2d837740766838d
Rust
Napokue/naga
/src/front/glsl/parser/declarations.rs
UTF-8
25,757
2.625
3
[ "Apache-2.0", "MIT" ]
permissive
use crate::{ front::glsl::{ ast::{ GlobalLookup, GlobalLookupKind, Precision, QualifierKey, QualifierValue, StorageQualifier, StructLayout, TypeQualifiers, }, context::{Context, ExprPos}, error::ExpectedToken, offset, token::{Token, TokenValue}, types::scalar_components, variables::{GlobalOrConstant, VarDeclaration}, Error, ErrorKind, Parser, Span, }, proc::Alignment, AddressSpace, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StructMember, Type, TypeInner, }; use super::{DeclarationContext, ParsingContext, Result}; /// Helper method used to retrieve the child type of `ty` at /// index `i`. /// /// # Note /// /// Does not check if the index is valid and returns the same type /// when indexing out-of-bounds a struct or indexing a non indexable /// type. fn element_or_member_type( ty: Handle<Type>, i: usize, types: &mut crate::UniqueArena<Type>, ) -> Handle<Type> { match types[ty].inner { // The child type of a vector is a scalar of the same kind and width TypeInner::Vector { kind, width, .. } => types.insert( Type { name: None, inner: TypeInner::Scalar { kind, width }, }, Default::default(), ), // The child type of a matrix is a vector of floats with the same // width and the size of the matrix rows. TypeInner::Matrix { rows, width, .. } => types.insert( Type { name: None, inner: TypeInner::Vector { size: rows, kind: ScalarKind::Float, width, }, }, Default::default(), ), // The child type of an array is the base type of the array TypeInner::Array { base, .. } => base, // The child type of a struct at index `i` is the type of it's // member at that same index. // // In case the index is out of bounds the same type is returned TypeInner::Struct { ref members, .. } => { members.get(i).map(|member| member.ty).unwrap_or(ty) } // The type isn't indexable, the same type is returned _ => ty, } } impl<'source> ParsingContext<'source> { pub fn parse_external_declaration( &mut self, parser: &mut Parser, global_ctx: &mut Context, global_body: &mut Block, ) -> Result<()> { if self .parse_declaration(parser, global_ctx, global_body, true)? .is_none() { let token = self.bump(parser)?; match token.value { TokenValue::Semicolon if parser.meta.version == 460 => Ok(()), _ => { let expected = match parser.meta.version { 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof], _ => vec![ExpectedToken::Eof], }; Err(Error { kind: ErrorKind::InvalidToken(token.value, expected), meta: token.meta, }) } } } else { Ok(()) } } pub fn parse_initializer( &mut self, parser: &mut Parser, ty: Handle<Type>, ctx: &mut Context, body: &mut Block, ) -> Result<(Handle<Expression>, Span)> { // initializer: // assignment_expression // LEFT_BRACE initializer_list RIGHT_BRACE // LEFT_BRACE initializer_list COMMA RIGHT_BRACE // // initializer_list: // initializer // initializer_list COMMA initializer if let Some(Token { mut meta, .. }) = self.bump_if(parser, TokenValue::LeftBrace) { // initializer_list let mut components = Vec::new(); loop { // The type expected to be parsed inside the initializer list let new_ty = element_or_member_type(ty, components.len(), &mut parser.module.types); components.push(self.parse_initializer(parser, new_ty, ctx, body)?.0); let token = self.bump(parser)?; match token.value { TokenValue::Comma => { if let Some(Token { meta: end_meta, .. }) = self.bump_if(parser, TokenValue::RightBrace) { meta.subsume(end_meta); break; } } TokenValue::RightBrace => { meta.subsume(token.meta); break; } _ => { return Err(Error { kind: ErrorKind::InvalidToken( token.value, vec![TokenValue::Comma.into(), TokenValue::RightBrace.into()], ), meta: token.meta, }) } } } Ok(( ctx.add_expression(Expression::Compose { ty, components }, meta, body), meta, )) } else { let mut stmt = ctx.stmt_ctx(); let expr = self.parse_assignment(parser, ctx, &mut stmt, body)?; let (mut init, init_meta) = ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; let scalar_components = scalar_components(&parser.module.types[ty].inner); if let Some((kind, width)) = scalar_components { ctx.implicit_conversion(parser, &mut init, init_meta, kind, width)?; } Ok((init, init_meta)) } } // Note: caller preparsed the type and qualifiers // Note: caller skips this if the fallthrough token is not expected to be consumed here so this // produced Error::InvalidToken if it isn't consumed pub fn parse_init_declarator_list( &mut self, parser: &mut Parser, mut ty: Handle<Type>, ctx: &mut DeclarationContext, ) -> Result<()> { // init_declarator_list: // single_declaration // init_declarator_list COMMA IDENTIFIER // init_declarator_list COMMA IDENTIFIER array_specifier // init_declarator_list COMMA IDENTIFIER array_specifier EQUAL initializer // init_declarator_list COMMA IDENTIFIER EQUAL initializer // // single_declaration: // fully_specified_type // fully_specified_type IDENTIFIER // fully_specified_type IDENTIFIER array_specifier // fully_specified_type IDENTIFIER array_specifier EQUAL initializer // fully_specified_type IDENTIFIER EQUAL initializer // Consume any leading comma, e.g. this is valid: `float, a=1;` if self .peek(parser) .map_or(false, |t| t.value == TokenValue::Comma) { self.next(parser); } loop { let token = self.bump(parser)?; let name = match token.value { TokenValue::Semicolon => break, TokenValue::Identifier(name) => name, _ => { return Err(Error { kind: ErrorKind::InvalidToken( token.value, vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], ), meta: token.meta, }) } }; let mut meta = token.meta; // array_specifier // array_specifier EQUAL initializer // EQUAL initializer // parse an array specifier if it exists // NOTE: unlike other parse methods this one doesn't expect an array specifier and // returns Ok(None) rather than an error if there is not one self.parse_array_specifier(parser, &mut meta, &mut ty)?; let init = self .bump_if(parser, TokenValue::Assign) .map::<Result<_>, _>(|_| { let (mut expr, init_meta) = self.parse_initializer(parser, ty, ctx.ctx, ctx.body)?; let scalar_components = scalar_components(&parser.module.types[ty].inner); if let Some((kind, width)) = scalar_components { ctx.ctx .implicit_conversion(parser, &mut expr, init_meta, kind, width)?; } meta.subsume(init_meta); Ok((expr, init_meta)) }) .transpose()?; let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; let maybe_constant = if ctx.external { if let Some((root, meta)) = init { match parser.solve_constant(ctx.ctx, root, meta) { Ok(res) => Some(res), // If the declaration is external (global scope) and is constant qualified // then the initializer must be a constant expression Err(err) if is_const => return Err(err), _ => None, } } else { None } } else { None }; let pointer = ctx.add_var(parser, ty, name, maybe_constant, meta)?; if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { ctx.flush_expressions(); ctx.body.push(Statement::Store { pointer, value }, meta); } let token = self.bump(parser)?; match token.value { TokenValue::Semicolon => break, TokenValue::Comma => {} _ => { return Err(Error { kind: ErrorKind::InvalidToken( token.value, vec![TokenValue::Comma.into(), TokenValue::Semicolon.into()], ), meta: token.meta, }) } } } Ok(()) } /// `external` whether or not we are in a global or local context pub fn parse_declaration( &mut self, parser: &mut Parser, ctx: &mut Context, body: &mut Block, external: bool, ) -> Result<Option<Span>> { //declaration: // function_prototype SEMICOLON // // init_declarator_list SEMICOLON // PRECISION precision_qualifier type_specifier SEMICOLON // // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE SEMICOLON // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER array_specifier SEMICOLON // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON if self.peek_type_qualifier(parser) || self.peek_type_name(parser) { let mut qualifiers = self.parse_type_qualifiers(parser)?; if self.peek_type_name(parser) { // This branch handles variables and function prototypes and if // external is true also function definitions let (ty, mut meta) = self.parse_type(parser)?; let token = self.bump(parser)?; let token_fallthrough = match token.value { TokenValue::Identifier(name) => match self.expect_peek(parser)?.value { TokenValue::LeftParen => { // This branch handles function definition and prototypes self.bump(parser)?; let result = ty.map(|ty| FunctionResult { ty, binding: None }); let mut body = Block::new(); let mut context = Context::new(parser, &mut body); self.parse_function_args(parser, &mut context, &mut body)?; let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; meta.subsume(end_meta); let token = self.bump(parser)?; return match token.value { TokenValue::Semicolon => { // This branch handles function prototypes parser.add_prototype(context, name, result, meta); Ok(Some(meta)) } TokenValue::LeftBrace if external => { // This branch handles function definitions // as you can see by the guard this branch // only happens if external is also true // parse the body self.parse_compound_statement( token.meta, parser, &mut context, &mut body, &mut None, )?; parser.add_function(context, name, result, body, meta); Ok(Some(meta)) } _ if external => Err(Error { kind: ErrorKind::InvalidToken( token.value, vec![ TokenValue::LeftBrace.into(), TokenValue::Semicolon.into(), ], ), meta: token.meta, }), _ => Err(Error { kind: ErrorKind::InvalidToken( token.value, vec![TokenValue::Semicolon.into()], ), meta: token.meta, }), }; } // Pass the token to the init_declarator_list parser _ => Token { value: TokenValue::Identifier(name), meta: token.meta, }, }, // Pass the token to the init_declarator_list parser _ => token, }; // If program execution has reached here then this will be a // init_declarator_list // token_falltrough will have a token that was already bumped if let Some(ty) = ty { let mut ctx = DeclarationContext { qualifiers, external, ctx, body, }; self.backtrack(token_fallthrough)?; self.parse_init_declarator_list(parser, ty, &mut ctx)?; } else { parser.errors.push(Error { kind: ErrorKind::SemanticError("Declaration cannot have void type".into()), meta, }) } Ok(Some(meta)) } else { // This branch handles struct definitions and modifiers like // ```glsl // layout(early_fragment_tests); // ``` let token = self.bump(parser)?; match token.value { TokenValue::Identifier(ty_name) => { if self.bump_if(parser, TokenValue::LeftBrace).is_some() { self.parse_block_declaration( parser, ctx, body, &mut qualifiers, ty_name, token.meta, ) .map(Some) } else { if qualifiers.invariant.take().is_some() { parser.make_variable_invariant(ctx, body, &ty_name, token.meta); qualifiers.unused_errors(&mut parser.errors); self.expect(parser, TokenValue::Semicolon)?; return Ok(Some(qualifiers.span)); } //TODO: declaration // type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON Err(Error { kind: ErrorKind::NotImplemented("variable qualifier"), meta: token.meta, }) } } TokenValue::Semicolon => { if let Some(value) = qualifiers.uint_layout_qualifier("local_size_x", &mut parser.errors) { parser.meta.workgroup_size[0] = value; } if let Some(value) = qualifiers.uint_layout_qualifier("local_size_y", &mut parser.errors) { parser.meta.workgroup_size[1] = value; } if let Some(value) = qualifiers.uint_layout_qualifier("local_size_z", &mut parser.errors) { parser.meta.workgroup_size[2] = value; } parser.meta.early_fragment_tests |= qualifiers .none_layout_qualifier("early_fragment_tests", &mut parser.errors); qualifiers.unused_errors(&mut parser.errors); Ok(Some(qualifiers.span)) } _ => Err(Error { kind: ErrorKind::InvalidToken( token.value, vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], ), meta: token.meta, }), } } } else { match self.peek(parser).map(|t| &t.value) { Some(&TokenValue::Precision) => { // PRECISION precision_qualifier type_specifier SEMICOLON self.bump(parser)?; let token = self.bump(parser)?; let _ = match token.value { TokenValue::PrecisionQualifier(p) => p, _ => { return Err(Error { kind: ErrorKind::InvalidToken( token.value, vec![ TokenValue::PrecisionQualifier(Precision::High).into(), TokenValue::PrecisionQualifier(Precision::Medium).into(), TokenValue::PrecisionQualifier(Precision::Low).into(), ], ), meta: token.meta, }) } }; let (ty, meta) = self.parse_type_non_void(parser)?; match parser.module.types[ty].inner { TypeInner::Scalar { kind: ScalarKind::Float | ScalarKind::Sint, .. } => {} _ => parser.errors.push(Error { kind: ErrorKind::SemanticError( "Precision statement can only work on floats and ints".into(), ), meta, }), } self.expect(parser, TokenValue::Semicolon)?; Ok(Some(meta)) } _ => Ok(None), } } } pub fn parse_block_declaration( &mut self, parser: &mut Parser, ctx: &mut Context, body: &mut Block, qualifiers: &mut TypeQualifiers, ty_name: String, mut meta: Span, ) -> Result<Span> { let layout = match qualifiers.layout_qualifiers.remove(&QualifierKey::Layout) { Some((QualifierValue::Layout(l), _)) => l, None => { if let StorageQualifier::AddressSpace(AddressSpace::Storage { .. }) = qualifiers.storage.0 { StructLayout::Std430 } else { StructLayout::Std140 } } _ => unreachable!(), }; let mut members = Vec::new(); let span = self.parse_struct_declaration_list(parser, &mut members, layout)?; self.expect(parser, TokenValue::RightBrace)?; let mut ty = parser.module.types.insert( Type { name: Some(ty_name), inner: TypeInner::Struct { members: members.clone(), span, }, }, Default::default(), ); let token = self.bump(parser)?; let name = match token.value { TokenValue::Semicolon => None, TokenValue::Identifier(name) => { self.parse_array_specifier(parser, &mut meta, &mut ty)?; self.expect(parser, TokenValue::Semicolon)?; Some(name) } _ => { return Err(Error { kind: ErrorKind::InvalidToken( token.value, vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()], ), meta: token.meta, }) } }; let global = parser.add_global_var( ctx, body, VarDeclaration { qualifiers, ty, name, init: None, meta, }, )?; for (i, k, ty) in members.into_iter().enumerate().filter_map(|(i, m)| { let ty = m.ty; m.name.map(|s| (i as u32, s, ty)) }) { let lookup = GlobalLookup { kind: match global { GlobalOrConstant::Global(handle) => GlobalLookupKind::BlockSelect(handle, i), GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle, ty), }, entry_arg: None, mutable: true, }; ctx.add_global(parser, &k, lookup, body); parser.global_variables.push((k, lookup)); } Ok(meta) } // TODO: Accept layout arguments pub fn parse_struct_declaration_list( &mut self, parser: &mut Parser, members: &mut Vec<StructMember>, layout: StructLayout, ) -> Result<u32> { let mut span = 0; let mut align = Alignment::ONE; loop { // TODO: type_qualifier let (mut ty, mut meta) = self.parse_type_non_void(parser)?; let (name, end_meta) = self.expect_ident(parser)?; meta.subsume(end_meta); self.parse_array_specifier(parser, &mut meta, &mut ty)?; self.expect(parser, TokenValue::Semicolon)?; let info = offset::calculate_offset( ty, meta, layout, &mut parser.module.types, &parser.module.constants, &mut parser.errors, ); let member_alignment = info.align; span = member_alignment.round_up(span); align = member_alignment.max(align); members.push(StructMember { name: Some(name), ty: info.ty, binding: None, offset: span, }); span += info.span; if let TokenValue::RightBrace = self.expect_peek(parser)?.value { break; } } span = align.round_up(span); Ok(span) } }
true
3788d6170a59fedfbb9a599b7401f4b54bf5ba43
Rust
solana-labs/solana
/sdk/program/src/rent.rs
UTF-8
6,997
3.109375
3
[ "Apache-2.0" ]
permissive
//! Configuration for network [rent]. //! //! [rent]: https://docs.solana.com/implemented-proposals/rent #![allow(clippy::arithmetic_side_effects)] use {crate::clock::DEFAULT_SLOTS_PER_EPOCH, solana_sdk_macro::CloneZeroed}; /// Configuration of network rent. #[repr(C)] #[derive(Serialize, Deserialize, PartialEq, CloneZeroed, Copy, Debug, AbiExample)] pub struct Rent { /// Rental rate in lamports/byte-year. pub lamports_per_byte_year: u64, /// Amount of time (in years) a balance must include rent for the account to /// be rent exempt. pub exemption_threshold: f64, /// The percentage of collected rent that is burned. /// /// Valid values are in the range [0, 100]. The remaining percentage is /// distributed to validators. pub burn_percent: u8, } /// Default rental rate in lamports/byte-year. /// /// This calculation is based on: /// - 10^9 lamports per SOL /// - $1 per SOL /// - $0.01 per megabyte day /// - $3.65 per megabyte year pub const DEFAULT_LAMPORTS_PER_BYTE_YEAR: u64 = 1_000_000_000 / 100 * 365 / (1024 * 1024); /// Default amount of time (in years) the balance has to include rent for the /// account to be rent exempt. pub const DEFAULT_EXEMPTION_THRESHOLD: f64 = 2.0; /// Default percentage of collected rent that is burned. /// /// Valid values are in the range [0, 100]. The remaining percentage is /// distributed to validators. pub const DEFAULT_BURN_PERCENT: u8 = 50; /// Account storage overhead for calculation of base rent. /// /// This is the number of bytes required to store an account with no data. It is /// added to an accounts data length when calculating [`Rent::minimum_balance`]. pub const ACCOUNT_STORAGE_OVERHEAD: u64 = 128; impl Default for Rent { fn default() -> Self { Self { lamports_per_byte_year: DEFAULT_LAMPORTS_PER_BYTE_YEAR, exemption_threshold: DEFAULT_EXEMPTION_THRESHOLD, burn_percent: DEFAULT_BURN_PERCENT, } } } impl Rent { /// Calculate how much rent to burn from the collected rent. /// /// The first value returned is the amount burned. The second is the amount /// to distribute to validators. pub fn calculate_burn(&self, rent_collected: u64) -> (u64, u64) { let burned_portion = (rent_collected * u64::from(self.burn_percent)) / 100; (burned_portion, rent_collected - burned_portion) } /// Minimum balance due for rent-exemption of a given account data size. pub fn minimum_balance(&self, data_len: usize) -> u64 { let bytes = data_len as u64; (((ACCOUNT_STORAGE_OVERHEAD + bytes) * self.lamports_per_byte_year) as f64 * self.exemption_threshold) as u64 } /// Whether a given balance and data length would be exempt. pub fn is_exempt(&self, balance: u64, data_len: usize) -> bool { balance >= self.minimum_balance(data_len) } /// Rent due on account's data length with balance. pub fn due(&self, balance: u64, data_len: usize, years_elapsed: f64) -> RentDue { if self.is_exempt(balance, data_len) { RentDue::Exempt } else { RentDue::Paying(self.due_amount(data_len, years_elapsed)) } } /// Rent due for account that is known to be not exempt. pub fn due_amount(&self, data_len: usize, years_elapsed: f64) -> u64 { let actual_data_len = data_len as u64 + ACCOUNT_STORAGE_OVERHEAD; let lamports_per_year = self.lamports_per_byte_year * actual_data_len; (lamports_per_year as f64 * years_elapsed) as u64 } /// Creates a `Rent` that charges no lamports. /// /// This is used for testing. pub fn free() -> Self { Self { lamports_per_byte_year: 0, ..Rent::default() } } /// Creates a `Rent` that is scaled based on the number of slots in an epoch. /// /// This is used for testing. pub fn with_slots_per_epoch(slots_per_epoch: u64) -> Self { let ratio = slots_per_epoch as f64 / DEFAULT_SLOTS_PER_EPOCH as f64; let exemption_threshold = DEFAULT_EXEMPTION_THRESHOLD * ratio; let lamports_per_byte_year = (DEFAULT_LAMPORTS_PER_BYTE_YEAR as f64 / ratio) as u64; Self { lamports_per_byte_year, exemption_threshold, ..Self::default() } } } /// The return value of [`Rent::due`]. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum RentDue { /// Used to indicate the account is rent exempt. Exempt, /// The account owes this much rent. Paying(u64), } impl RentDue { /// Return the lamports due for rent. pub fn lamports(&self) -> u64 { match self { RentDue::Exempt => 0, RentDue::Paying(x) => *x, } } /// Return 'true' if rent exempt. pub fn is_exempt(&self) -> bool { match self { RentDue::Exempt => true, RentDue::Paying(_) => false, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_due() { let default_rent = Rent::default(); assert_eq!( default_rent.due(0, 2, 1.2), RentDue::Paying( (((2 + ACCOUNT_STORAGE_OVERHEAD) * DEFAULT_LAMPORTS_PER_BYTE_YEAR) as f64 * 1.2) as u64 ), ); assert_eq!( default_rent.due( (((2 + ACCOUNT_STORAGE_OVERHEAD) * DEFAULT_LAMPORTS_PER_BYTE_YEAR) as f64 * DEFAULT_EXEMPTION_THRESHOLD) as u64, 2, 1.2 ), RentDue::Exempt, ); let custom_rent = Rent { lamports_per_byte_year: 5, exemption_threshold: 2.5, ..Rent::default() }; assert_eq!( custom_rent.due(0, 2, 1.2), RentDue::Paying( (((2 + ACCOUNT_STORAGE_OVERHEAD) * custom_rent.lamports_per_byte_year) as f64 * 1.2) as u64, ) ); assert_eq!( custom_rent.due( (((2 + ACCOUNT_STORAGE_OVERHEAD) * custom_rent.lamports_per_byte_year) as f64 * custom_rent.exemption_threshold) as u64, 2, 1.2 ), RentDue::Exempt ); } #[test] fn test_rent_due_lamports() { assert_eq!(RentDue::Exempt.lamports(), 0); let amount = 123; assert_eq!(RentDue::Paying(amount).lamports(), amount); } #[test] fn test_rent_due_is_exempt() { assert!(RentDue::Exempt.is_exempt()); assert!(!RentDue::Paying(0).is_exempt()); } #[test] fn test_clone() { let rent = Rent { lamports_per_byte_year: 1, exemption_threshold: 2.2, burn_percent: 3, }; #[allow(clippy::clone_on_copy)] let cloned_rent = rent.clone(); assert_eq!(cloned_rent, rent); } }
true
c55b512d79dd9bfc18eeea6d9a6ec204cbdb3e0c
Rust
denoland/deno
/ext/node/ops/crypto/cipher.rs
UTF-8
5,678
2.53125
3
[ "MIT" ]
permissive
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use aes::cipher::block_padding::Pkcs7; use aes::cipher::BlockDecryptMut; use aes::cipher::BlockEncryptMut; use aes::cipher::KeyIvInit; use deno_core::error::type_error; use deno_core::error::AnyError; use deno_core::Resource; use digest::KeyInit; use std::borrow::Cow; use std::cell::RefCell; use std::rc::Rc; enum Cipher { Aes128Cbc(Box<cbc::Encryptor<aes::Aes128>>), Aes128Ecb(Box<ecb::Encryptor<aes::Aes128>>), // TODO(kt3k): add more algorithms Aes192Cbc, Aes256Cbc, Aes128GCM, etc. } enum Decipher { Aes128Cbc(Box<cbc::Decryptor<aes::Aes128>>), Aes128Ecb(Box<ecb::Decryptor<aes::Aes128>>), // TODO(kt3k): add more algorithms Aes192Cbc, Aes256Cbc, Aes128GCM, etc. } pub struct CipherContext { cipher: Rc<RefCell<Cipher>>, } pub struct DecipherContext { decipher: Rc<RefCell<Decipher>>, } impl CipherContext { pub fn new(algorithm: &str, key: &[u8], iv: &[u8]) -> Result<Self, AnyError> { Ok(Self { cipher: Rc::new(RefCell::new(Cipher::new(algorithm, key, iv)?)), }) } pub fn encrypt(&self, input: &[u8], output: &mut [u8]) { self.cipher.borrow_mut().encrypt(input, output); } pub fn r#final( self, input: &[u8], output: &mut [u8], ) -> Result<(), AnyError> { Rc::try_unwrap(self.cipher) .map_err(|_| type_error("Cipher context is already in use"))? .into_inner() .r#final(input, output) } } impl DecipherContext { pub fn new(algorithm: &str, key: &[u8], iv: &[u8]) -> Result<Self, AnyError> { Ok(Self { decipher: Rc::new(RefCell::new(Decipher::new(algorithm, key, iv)?)), }) } pub fn decrypt(&self, input: &[u8], output: &mut [u8]) { self.decipher.borrow_mut().decrypt(input, output); } pub fn r#final( self, input: &[u8], output: &mut [u8], ) -> Result<(), AnyError> { Rc::try_unwrap(self.decipher) .map_err(|_| type_error("Decipher context is already in use"))? .into_inner() .r#final(input, output) } } impl Resource for CipherContext { fn name(&self) -> Cow<str> { "cryptoCipher".into() } } impl Resource for DecipherContext { fn name(&self) -> Cow<str> { "cryptoDecipher".into() } } impl Cipher { fn new( algorithm_name: &str, key: &[u8], iv: &[u8], ) -> Result<Self, AnyError> { use Cipher::*; Ok(match algorithm_name { "aes-128-cbc" => { Aes128Cbc(Box::new(cbc::Encryptor::new(key.into(), iv.into()))) } "aes-128-ecb" => Aes128Ecb(Box::new(ecb::Encryptor::new(key.into()))), _ => return Err(type_error(format!("Unknown cipher {algorithm_name}"))), }) } /// encrypt encrypts the data in the middle of the input. fn encrypt(&mut self, input: &[u8], output: &mut [u8]) { use Cipher::*; match self { Aes128Cbc(encryptor) => { assert!(input.len() % 16 == 0); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { encryptor.encrypt_block_b2b_mut(input.into(), output.into()); } } Aes128Ecb(encryptor) => { assert!(input.len() % 16 == 0); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { encryptor.encrypt_block_b2b_mut(input.into(), output.into()); } } } } /// r#final encrypts the last block of the input data. fn r#final(self, input: &[u8], output: &mut [u8]) -> Result<(), AnyError> { assert!(input.len() < 16); use Cipher::*; match self { Aes128Cbc(encryptor) => { let _ = (*encryptor) .encrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| type_error("Cannot pad the input data"))?; Ok(()) } Aes128Ecb(encryptor) => { let _ = (*encryptor) .encrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| type_error("Cannot pad the input data"))?; Ok(()) } } } } impl Decipher { fn new( algorithm_name: &str, key: &[u8], iv: &[u8], ) -> Result<Self, AnyError> { use Decipher::*; Ok(match algorithm_name { "aes-128-cbc" => { Aes128Cbc(Box::new(cbc::Decryptor::new(key.into(), iv.into()))) } "aes-128-ecb" => Aes128Ecb(Box::new(ecb::Decryptor::new(key.into()))), _ => return Err(type_error(format!("Unknown cipher {algorithm_name}"))), }) } /// decrypt decrypts the data in the middle of the input. fn decrypt(&mut self, input: &[u8], output: &mut [u8]) { use Decipher::*; match self { Aes128Cbc(decryptor) => { assert!(input.len() % 16 == 0); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { decryptor.decrypt_block_b2b_mut(input.into(), output.into()); } } Aes128Ecb(decryptor) => { assert!(input.len() % 16 == 0); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { decryptor.decrypt_block_b2b_mut(input.into(), output.into()); } } } } /// r#final decrypts the last block of the input data. fn r#final(self, input: &[u8], output: &mut [u8]) -> Result<(), AnyError> { assert!(input.len() == 16); use Decipher::*; match self { Aes128Cbc(decryptor) => { let _ = (*decryptor) .decrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| type_error("Cannot unpad the input data"))?; Ok(()) } Aes128Ecb(decryptor) => { let _ = (*decryptor) .decrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| type_error("Cannot unpad the input data"))?; Ok(()) } } } }
true
0cf4566bef28cdf35a31ea95644cdc08c3476f83
Rust
delta62/soundtest
/src/macros.rs
UTF-8
553
3.1875
3
[]
no_license
/// Run some code that returns a number and return Ok(result) if >= 0 or Err(result) if < 0 macro_rules! code { ( $try:expr ) => {{ let result = $try; if result < 0 { Err(result) } else { Ok(()) } }} } /// Initialize a pointer with the given callback macro_rules! ptr_init { ( $typ:ty, $initfn:expr ) => {{ let mut p = ptr::null_mut() as $typ; let ret = $initfn(&mut p); if ret < 0 { Err(ret) } else { Ok(p) } }} }
true
8f161ae6e22b269ea1efeb15fc20b86b0b937b3a
Rust
maelvls/termscp
/src/ui/layout/components/msgbox.rs
UTF-8
6,922
3
3
[ "MIT", "GPL-3.0-only" ]
permissive
//! ## MsgBox //! //! `MsgBox` component renders a simple readonly no event associated centered text /** * MIT License * * termscp - Copyright (c) 2021 Christian Visintin * * 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. */ // deps extern crate textwrap; // locals use super::{Canvas, Component, InputEvent, Msg, Payload, Props, PropsBuilder}; use crate::utils::fmt::align_text_center; // ext use tui::{ layout::{Corner, Rect}, style::{Color, Style}, text::{Span, Spans}, widgets::{Block, BorderType, List, ListItem}, }; // -- component pub struct MsgBox { props: Props, } impl MsgBox { /// ### new /// /// Instantiate a new Text component pub fn new(props: Props) -> Self { MsgBox { props } } } impl Component for MsgBox { /// ### render /// /// Based on the current properties and states, renders a widget using the provided render engine in the provided Area /// If focused, cursor is also set (if supported by widget) #[cfg(not(tarpaulin_include))] fn render(&self, render: &mut Canvas, area: Rect) { // Make a Span if self.props.visible { let lines: Vec<ListItem> = match self.props.texts.rows.as_ref() { None => Vec::new(), Some(rows) => { let mut lines: Vec<ListItem> = Vec::new(); for line in rows.iter() { // Keep line color, or use default let line_fg: Color = match line.fg { Color::Reset => self.props.foreground, _ => line.fg, }; let line_bg: Color = match line.bg { Color::Reset => self.props.background, _ => line.bg, }; let message_row = textwrap::wrap(line.content.as_str(), area.width as usize); for msg in message_row.iter() { lines.push(ListItem::new(Spans::from(vec![Span::styled( align_text_center(msg, area.width), Style::default() .add_modifier(line.get_modifiers()) .fg(line_fg) .bg(line_bg), )]))); } } lines } }; let title: String = match self.props.texts.title.as_ref() { Some(t) => t.clone(), None => String::new(), }; render.render_widget( List::new(lines) .block( Block::default() .borders(self.props.borders) .border_style(Style::default().fg(self.props.foreground)) .border_type(BorderType::Rounded) .title(title), ) .start_corner(Corner::TopLeft) .style( Style::default() .fg(self.props.foreground) .bg(self.props.background), ), area, ); } } /// ### update /// /// Update component properties /// Properties should first be retrieved through `get_props` which creates a builder from /// existing properties and then edited before calling update. /// Returns a Msg to the view fn update(&mut self, props: Props) -> Msg { self.props = props; // Return None Msg::None } /// ### get_props /// /// Returns a props builder starting from component properties. /// This returns a prop builder in order to make easier to create /// new properties for the element. fn get_props(&self) -> PropsBuilder { PropsBuilder::from(self.props.clone()) } /// ### on /// /// Handle input event and update internal states. /// Returns a Msg to the view. /// Returns always None, since cannot have any focus fn on(&mut self, ev: InputEvent) -> Msg { // Return key if let InputEvent::Key(key) = ev { Msg::OnKey(key) } else { Msg::None } } /// ### get_value /// /// Get current value from component /// For this component returns always None fn get_value(&self) -> Payload { Payload::None } // -- events /// ### blur /// /// Blur component fn blur(&mut self) {} /// ### active /// /// Active component fn active(&mut self) {} } #[cfg(test)] mod tests { use super::*; use crate::ui::layout::props::{TextParts, TextSpan, TextSpanBuilder}; use crossterm::event::{KeyCode, KeyEvent}; use tui::style::Color; #[test] fn test_ui_layout_components_msgbox() { let mut component: MsgBox = MsgBox::new( PropsBuilder::default() .with_texts(TextParts::new( None, Some(vec![ TextSpan::from("Press "), TextSpanBuilder::new("<ESC>") .with_foreground(Color::Cyan) .bold() .build(), TextSpan::from(" to quit"), ]), )) .build(), ); // Get value assert_eq!(component.get_value(), Payload::None); // Event assert_eq!( component.on(InputEvent::Key(KeyEvent::from(KeyCode::Delete))), Msg::OnKey(KeyEvent::from(KeyCode::Delete)) ); } }
true
4b959e61c08a3d1f36e86183dd5436045bec7209
Rust
KatsuyaKikuchi/programming_contest_rust
/src/VirtualContest/graph/051.rs
UTF-8
2,297
3.125
3
[]
no_license
use proconio::input; use proconio::marker::Usize1; use std::collections::HashMap; struct UnionFind { parent: Vec<usize>, rank: Vec<i32>, size: usize, } #[allow(dead_code)] impl UnionFind { fn new(size: usize) -> Self { UnionFind { parent: (0..size).map(|i| i).collect(), rank: vec![1; size], size: size, } } fn find(&mut self, n: usize) -> usize { if self.parent[n] == n { return n; }; self.parent[n] = self.find(self.parent[n]); self.parent[n] } fn same(&mut self, n: usize, m: usize) -> bool { self.find(n) == self.find(m) } fn unit(&mut self, n: usize, m: usize) { let n = self.find(n); let m = self.find(m); if n == m { return; } if self.rank[n] > self.rank[m] { self.parent[m] = n; } else { self.parent[n] = m; if self.rank[n] == self.rank[m] { self.rank[n] += self.rank[m]; } } } fn groups(&mut self) -> Vec<Vec<usize>> { let mut parent_buf = vec![0; self.size]; let mut group_size = vec![0; self.size]; for i in 0..self.size { parent_buf[i] = self.find(i); group_size[parent_buf[i]] += 1; } let mut ret = vec![Vec::new(); self.size]; for i in 0..self.size { ret[i].reserve(group_size[i]); } for i in 0..self.size { ret[parent_buf[i]].push(i); } ret .into_iter() .filter(|x| !x.is_empty()) .collect() } } fn main() { input! { (n,k,l):(usize,usize,usize), v0:[(Usize1,Usize1);k], v1:[(Usize1,Usize1);l], } let mut uf0 = UnionFind::new(n); let mut uf1 = UnionFind::new(n); for (a, b) in v0 { uf0.unit(a, b); } for (a, b) in v1 { uf1.unit(a, b); } let mut m = HashMap::new(); for i in 0..n { let x = (uf0.find(i), uf1.find(i)); let val = m.entry(x).or_insert(0); *val += 1; } for i in 0..n { let x = (uf0.find(i), uf1.find(i)); let val = m.get(&x).unwrap(); print!("{} ", val); } println!(""); }
true
2f038791624efd06258c26a9765e03b38582fab5
Rust
laohanlinux/rust-libp2p
/stores/peerstore/src/peerstore.rs
UTF-8
4,456
2.875
3
[ "MIT" ]
permissive
// Copyright 2017 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. use multiaddr::Multiaddr; use std::time::Duration; use {PeerId, TTL}; /// Implemented on objects that store peers. /// /// Note that the methods of this trait take by ownership (i.e. `self` instead of `&self` or /// `&mut self`). This was made so that the associated types could hold `self` internally and /// because Rust doesn't have higher-ranked trait bounds yet. /// /// Therefore this trait should likely be implemented on `&'a ConcretePeerstore` instead of /// on `ConcretePeerstore`. pub trait Peerstore { /// Grants access to the a peer inside the peer store. type PeerAccess: PeerAccess; /// List of the peers in this peer store. type PeersIter: Iterator<Item = PeerId>; /// Grants access to a peer by its ID. fn peer(self, peer_id: &PeerId) -> Option<Self::PeerAccess>; /// Grants access to a peer by its ID or creates it. fn peer_or_create(self, peer_id: &PeerId) -> Self::PeerAccess; /// Returns a list of peers in this peer store. /// /// Keep in mind that the trait implementation may allow new peers to be added or removed at /// any time. If that is the case, you have to take into account that this is only an /// indication. fn peers(self) -> Self::PeersIter; } /// Implemented on objects that represent an open access to a peer stored in a peer store. /// /// The exact semantics of "open access" depend on the trait implementation. pub trait PeerAccess { /// Iterator returned by `addrs`. type AddrsIter: Iterator<Item = Multiaddr>; /// Returns all known and non-expired addresses for a given peer. /// /// > **Note**: Keep in mind that this function is racy because addresses can expire between /// > the moment when you get them and the moment when you process them. fn addrs(&self) -> Self::AddrsIter; /// Adds an address to a peer. /// /// If the manager already has this address stored and with a longer TTL, then the operation /// is a no-op. fn add_addr(&mut self, addr: Multiaddr, ttl: TTL); // Similar to calling `add_addr` multiple times in a row. #[inline] fn add_addrs<I>(&mut self, addrs: I, ttl: TTL) where I: IntoIterator<Item = Multiaddr>, { for addr in addrs.into_iter() { self.add_addr(addr, ttl); } } /// Removes an address from a peer. #[inline] fn rm_addr(&mut self, addr: Multiaddr) { self.set_addr_ttl(addr, Duration::new(0, 0)); } // Similar to calling `rm_addr` multiple times in a row. fn rm_addrs<I>(&mut self, addrs: I) where I: IntoIterator<Item = Multiaddr>, { for addr in addrs.into_iter() { self.rm_addr(addr); } } /// Sets the TTL of an address of a peer. Adds the address if it is currently unknown. /// /// Contrary to `add_addr`, this operation is never a no-op. #[inline] fn set_addr_ttl(&mut self, addr: Multiaddr, ttl: TTL); // Similar to calling `set_addr_ttl` multiple times in a row. fn set_addrs_ttl<I>(&mut self, addrs: I, ttl: TTL) where I: IntoIterator<Item = Multiaddr>, { for addr in addrs.into_iter() { self.set_addr_ttl(addr, ttl); } } /// Removes all previously stored addresses. fn clear_addrs(&mut self); }
true
7e27f6cd89849366b3b6843472aaa35679867142
Rust
novacrazy/rust-plot
/src/plot/line.rs
UTF-8
3,186
3.59375
4
[]
no_license
//! Line drawing routines /// Uses Bresenham's algorithm to draw a line. /// /// [https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) pub fn draw_line_bresenham<F>(mut x0: i64, mut y0: i64, x1: i64, y1: i64, mut plot: F) where F: FnMut(i64, i64, f64) { let dx = (x1 - x0).abs(); let dy = -(y1 - y0).abs(); let sx = if x0 < x1 { 1 } else { -1 }; let sy = if y0 < y1 { 1 } else { -1 }; let mut err = dx + dy; loop { plot(x0, y0, 1.0); if x0 == x1 && y0 == y1 { break; } let e2 = 2 * err; if e2 >= dy { err += dy; x0 += sx; } if e2 <= dx { err += dx; y0 += sy; } } } /// Uses Xiaolin Wu's algorithm to draw an anti-aliased line. /// /// [https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm](https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm) /// /// Despite the ropey appearance up close, at a 1 to 1 resolution Xiaolin Wu's technique /// looks much better than non-antialiased techniques. pub fn draw_line_xiaolin_wu<F>(mut x0: f64, mut y0: f64, mut x1: f64, mut y1: f64, mut plot: F) where F: FnMut(i64, i64, f64) { use std::mem::swap; let mut plot_float = |x: f64, y: f64, opacity: f64| { plot(x as i64, y as i64, opacity) }; let steep = (y1 - y0).abs() > (x1 - x0).abs(); if steep { swap(&mut x0, &mut y0); swap(&mut x1, &mut y1); } if x0 > x1 { swap(&mut x0, &mut x1); swap(&mut y0, &mut y1); } let dx = x1 - x0; let dy = y1 - y0; let gradient = if dx < 0.0001 { 1.0 } else { dy / dx }; let xend = x0.round(); let yend = y0 + gradient * (xend - x0); let xgap = 1.0 - (x0 + 0.5).fract(); let xpxl1 = xend; let ypxl1 = yend.trunc(); if steep { plot_float(ypxl1, xpxl1, (1.0 - yend.fract()) * xgap); plot_float(ypxl1 + 1.0, xpxl1, yend.fract() * xgap); } else { plot_float(xpxl1, ypxl1, (1.0 - yend.fract()) * xgap); plot_float(xpxl1, ypxl1 + 1.0, yend.fract() * xgap); } let mut intery = yend + gradient; let xend = x1.round(); let yend = y1 + gradient * (xend - x1); let xgap = (x1 + 0.5).fract(); let xpxl2 = xend; let ypxl2 = yend.trunc(); if steep { plot_float(ypxl2, xpxl2, (1.0 - yend.fract()) * xgap); plot_float(ypxl2 + 1.0, xpxl2, yend.fract() * xgap); } else { plot_float(xpxl2, ypxl2, (1.0 - yend.fract()) * xgap); plot_float(xpxl2, ypxl2 + 1.0, yend.fract() * xgap); } let mut x = xpxl1 + 1.0; if steep { while x <= (xpxl2 - 1.0) { let y = intery.trunc(); plot_float(y, x, 1.0 - intery.fract()); plot_float(y + 1.0, x, intery.fract()); intery += gradient; x += 1.0; } } else { while x <= (xpxl2 - 1.0) { let y = intery.trunc(); plot_float(x, y, 1.0 - intery.fract()); plot_float(x, y + 1.0, intery.fract()); intery += gradient; x += 1.0; } } }
true
0eda584de25655ce533bbed6c7b6d00b9175b147
Rust
jlb6740/wasmtime
/cranelift/src/compile.rs
UTF-8
3,089
2.703125
3
[ "LLVM-exception", "Apache-2.0" ]
permissive
//! CLI tool to read Cranelift IR files and compile them into native code. use crate::disasm::print_all; use crate::utils::{parse_sets_and_triple, read_to_string}; use anyhow::{Context as _, Result}; use clap::Parser; use cranelift_codegen::print_errors::pretty_error; use cranelift_codegen::settings::FlagsOrIsa; use cranelift_codegen::timing; use cranelift_codegen::Context; use cranelift_reader::{parse_test, ParseOptions}; use std::path::Path; use std::path::PathBuf; /// Compiles Cranelift IR into target language #[derive(Parser)] pub struct Options { /// Print the resulting Cranelift IR #[clap(short)] print: bool, /// Print pass timing report #[clap(short = 'T')] report_times: bool, /// Print machine code disassembly #[clap(short = 'D', long)] disasm: bool, /// Configure Cranelift settings #[clap(long = "set")] settings: Vec<String>, /// Specify the Cranelift target #[clap(long = "target")] target: String, /// Specify an input file to be used. Use '-' for stdin. files: Vec<PathBuf>, } pub fn run(options: &Options) -> Result<()> { let parsed = parse_sets_and_triple(&options.settings, &options.target)?; for path in &options.files { let name = String::from(path.as_os_str().to_string_lossy()); handle_module(options, path, &name, parsed.as_fisa())?; } Ok(()) } fn handle_module(options: &Options, path: &Path, name: &str, fisa: FlagsOrIsa) -> Result<()> { let buffer = read_to_string(&path)?; let test_file = parse_test(&buffer, ParseOptions::default()) .with_context(|| format!("failed to parse {}", name))?; // If we have an isa from the command-line, use that. Otherwise if the // file contains a unique isa, use that. let isa = fisa.isa.or(test_file.isa_spec.unique_isa()); if isa.is_none() { anyhow::bail!("compilation requires a target isa"); }; for (func, _) in test_file.functions { if let Some(isa) = isa { let mut context = Context::new(); context.func = func; let mut mem = vec![]; // Compile and encode the result to machine code. let compiled_code = context .compile_and_emit(isa, &mut mem) .map_err(|err| anyhow::anyhow!("{}", pretty_error(&err.func, err.inner)))?; let code_info = compiled_code.code_info(); if options.print { println!("{}", context.func.display()); } if options.disasm { let result = context.compiled_code().unwrap(); print_all( isa, &context.func.params, &mem, code_info.total_size, options.print, result.buffer.relocs(), result.buffer.traps(), result.buffer.stack_maps(), )?; } } } if options.report_times { print!("{}", timing::take_current()); } Ok(()) }
true
011dc3678db9038dbdb19f2e402c0257041f58d1
Rust
sga001/mpir
/src/pbc/choices.rs
UTF-8
5,124
2.953125
3
[]
no_license
use super::BatchCode; use super::Tuple; use bincode::serialize; use serde::Serialize; use std::collections::HashMap; use std::ops::{BitXor, BitXorAssign}; use std::{cmp, hash}; pub struct ChoicesCode { k: usize, d: usize, // d choices } impl ChoicesCode { pub fn new(k: usize, d: usize) -> ChoicesCode { let bound = retry_bound!(k, d); assert!(bound < k, "You are better off using replication"); ChoicesCode { k, d } } } impl<K, V> BatchCode<K, V> for ChoicesCode where K: Clone + Serialize + BitXor<Output = K> + BitXorAssign + cmp::Eq + hash::Hash, V: Clone + Serialize + BitXor<Output = V> + BitXorAssign, { // Encoding is placing each entry to d logical buckets. // We also replicate each logical bucket b times (b = retry bound). fn encode(&self, collection: &[Tuple<K, V>]) -> Vec<Vec<Tuple<K, V>>> { let bound = retry_bound!(self.k, self.d); let total_buckets = self.k * bound; let mut collections: Vec<Vec<Tuple<K, V>>> = Vec::with_capacity(total_buckets); for _ in 0..self.k { collections.push(Vec::new()); } for entry in collection { // First get the binary representation of the key let bytes = serialize(&entry.t.0).unwrap(); let mut bucket_choices = Vec::with_capacity(self.d); // Map entry's key to d buckets (no repeats) for id in 0..self.d { let mut nonce = 0; // The following computes bucket = sha_d(key) % k; let mut bucket = super::hash_and_mod(id, nonce, &bytes, self.k); // Ensure each key maps to *different* buckets while bucket_choices.contains(&bucket) { nonce += 1; bucket = super::hash_and_mod(id, nonce, &bytes, self.k); } bucket_choices.push(bucket); collections[bucket].push(entry.clone()); } } // Replicate each of the k logical buckets into b buckets // Every i mod k has the same collection, where 0 <= i < b. for i in self.k..total_buckets { let clone = collections[i % self.k].clone(); collections.push(clone); } assert_eq!(collections.len(), total_buckets); collections } // This is an adaptation of the "Greedy" algorithm of Azar et al.'s // Balanced allocations paper, STOC '94. // The difference is that for each of the k buckets, we have b replicas. // If two balls map to the same bucket in Greedy, it just places the 2 balls in the same bucket. // In our case, if 2 balls map to the same bucket, we place each ball in a different // replicas of each bucket. // This is different from Po2C in that we are doing this for retrieval rather than // storage. What this means is that Po2C is being applied with respect to the // client's keys (not the keys that the storage server received!). This is a crucial // but subtle difference. fn get_schedule(&self, keys: &[K]) -> Option<HashMap<K, Vec<usize>>> { assert!(keys.len() <= self.k); let bound = retry_bound!(self.k, self.d); let mut schedule = HashMap::new(); for key in keys { let bytes = serialize(&key).unwrap(); let mut bucket_choices = Vec::with_capacity(self.d); let mut found = false; // Map entry's key to d buckets (no repeats) for id in 0..self.d { let mut nonce = 0; // The following computes bucket = sha_d(key) % k; let mut bucket = super::hash_and_mod(id, nonce, &bytes, self.k); // Ensure each key maps to *different* buckets while bucket_choices.contains(&bucket) { nonce += 1; bucket = super::hash_and_mod(id, nonce, &bytes, self.k); } bucket_choices.push(bucket); } // Find a bucket that has not been used. This is sort of analogous // to Greedy, but not quite. 'bucket_loop: for bucket in bucket_choices { for i in 0..bound { let entry = vec![bucket + i * self.k]; if !schedule.values().any(|e| e == &entry) { schedule.insert(key.clone(), entry); found = true; break 'bucket_loop; } } } if !found { return None; } } // maps each index into a vector of 1 entry containing that index // We do this only to meet the return type: each entry represents the // set of indices that must be queried (in our case, our encoding is // systematic so we don't need to have multiple indices per item). Some(schedule) } fn decode(&self, results: &[Tuple<K, V>]) -> Tuple<K, V> { assert_eq!(results.len(), 1); results[0].clone() } }
true
b2726a13a18b0e54d980db3fa2f3ee5de309f911
Rust
elipmoc/Ruscall
/src/compile/semantic_analysis/type_inference/assump_env.rs
UTF-8
1,359
3.078125
3
[ "MIT" ]
permissive
use compile::types::*; use std::collections::HashMap; use std::fmt; #[derive(PartialEq)] pub struct AssumpEnv { env: Vec<HashMap<String, Scheme>>, nest: usize, } impl fmt::Debug for AssumpEnv { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let assump_list = self.env[0].iter().fold("".to_string(), |acc, (name, scheme)| acc + &format!("{}=>\n{:?}\n\n", name, scheme), ); write!(f, "{}", assump_list) } } //型環境 impl AssumpEnv { pub fn new() -> AssumpEnv { AssumpEnv { env: vec![HashMap::new()], nest: 0, } } //環境をネスト pub fn in_nest(&mut self) { self.nest += 1; self.env.push(HashMap::new()); } //環境のネストを抜ける pub fn out_nest(&mut self) { self.nest -= 1; self.env.pop(); } pub fn global_get(&self, symbol: &String) -> Option<&Scheme> { self.env[0].get(symbol) } pub fn get(&self, symbol: &String) -> Option<&Scheme> { self.env[self.nest].get(symbol) } pub fn global_set(&mut self, symbol: String, q: Scheme) { println!("global_set {} {:?}", symbol, q); self.env[0].insert(symbol, q); } pub fn set(&mut self, symbol: String, q: Scheme) { self.env[self.nest].insert(symbol, q); } }
true
0ed1cdf5deca53cb88311344d393581154c5ff1c
Rust
jpdvi/scout
/src/lexer/mod.rs
UTF-8
3,429
3.46875
3
[]
no_license
use super::data; use super::token; pub trait Lexing { fn read(&mut self); fn read_char(&mut self); fn next_token(&mut self) -> token::Token; fn peek_char(&mut self)-> Option<char>; } pub struct Lexer { pub read_position: u32, pub input: String, pub tokens : Vec<token::Token>, pub pattern: token::Pattern, pub position: u32, pub data: data::Data, pub ch : Option<char>, } impl Lexer { pub fn new(input: &str, data: &data::Data, pattern: &token::Pattern) -> Self { Self { input: input.to_string(), read_position: 0, pattern: pattern.clone(), position: 0, data : data.clone(), ch: None, tokens : vec![], } } } impl Lexing for Lexer { fn read(&mut self) { let mut v : Vec<token::Token> = vec![]; while self.read_position as usize <= self.input.len() { let tok = self.next_token(); v.push(tok); } self.tokens = v; } fn next_token(&mut self) -> token::Token { self.read_char(); let tok : token::Token = match self.ch { None => token::Token::new(token::EOF, self.ch), Some('{') => { if self.peek_char() != None && self.peek_char().unwrap() == '{' && self.pattern.left == token::DOUBLELEFTBRACKET { let mut t : token::Token = token::Token::new(token::DOUBLELEFTBRACKET, None); t.literal = self.ch.unwrap().to_string() + &self.peek_char().unwrap().to_string(); self.read_char(); return t; } if self.pattern.left == token::LEFTBRACKET { return token::Token::new(token::LEFTBRACKET, self.ch) } return token::Token::new(token::TEXT, self.ch) }, Some('}') => { if self.peek_char() != None && self.peek_char().unwrap() == '}' && self.pattern.right == token::DOUBLERIGHTBRACKET { let mut t : token::Token = token::Token::new(token::DOUBLERIGHTBRACKET, None); t.literal = self.ch.unwrap().to_string() + &self.peek_char().unwrap().to_string(); self.read_char(); return t; } if self.pattern.right == token::RIGHTBRACKET { return token::Token::new(token::RIGHTBRACKET, self.ch) } return token::Token::new(token::TEXT, self.ch) }, Some(' ') => token::Token::new(token::SPACE, self.ch), _=> token::Token::new(token::TEXT, self.ch), }; return tok; } fn read_char(&mut self) { if self.read_position >= self.input.len() as u32 { self.ch = None } else { self.ch = Some(self.input.chars().nth(self.read_position as usize).unwrap()); } self.position = self.read_position; self.read_position += 1; } fn peek_char(&mut self) -> Option<char> { if self.read_position >= self.input.len() as u32 { return None } return Some(self.input.chars().nth(self.read_position as usize).unwrap()); } }
true
d864ec7027b181d3d34aaf6e1bd574678a59e385
Rust
Nov11/rust-pl
/ref-scope/src/main.rs
UTF-8
346
3.65625
4
[]
no_license
fn main() { let mut s = String::from("string"); let r1 = &s; // no problem let r2 = &s; // no problem println!("{}, {}", r1, r2); //not that same with variable scope //r1/r2's scope is not used below, their scopes end and it's valid to create mutable ref. let r3 = &mut s; // BIG PROBLEM println!("r3 {}", r3); }
true
8dcbb0bdaf7f08d977c5ab78fa4ff78350f45b51
Rust
KKhan02/iot
/function/src/main.rs
UTF-8
656
3.796875
4
[]
no_license
fn main() { paper(); let (number1,number2) = (2,8); let (x,y) = square(number1,number2); println!("The square of the number {} is {}",number1,x); println!("The square of the number {} is {}",number2,y) } fn paper(){ println!("1. Add milk"); println!("2. Add Butter"); println!("3. Add eggs"); println!("4. Add sugar"); println!("5. Stir it"); println!("6. Heat on gentle flame"); } fn square(x:u32,y:u32) -> (u32,u32){ let result = x*x; let result_1 = y*y; // println!("The square of the number {} is {}",x,result); // println!("The square of the number {} is {}",y,result_1) (result,result_1) }
true
2d05cdb6d10984f79d5382ecab0efd484e5bb002
Rust
DannyStoyanov/Programming-with-Rust
/lifetimes/src/main.rs
UTF-8
1,483
3.84375
4
[]
no_license
use std::str; fn longer<'a>(s1: &'a str, s2: &'a str) -> &'a str{ if s1.len() > s2.len() { s1 } else { s2 } } fn first_occurrence<'a, 'b>(s: &'a str, pattern: &'b str) -> Option<&'a str> { s.matches(pattern).next() } #[derive(Debug)] struct Words<'a> { text: Option<&'a str>, } impl<'a> Words<'a> { fn new(text: &'a str) -> Self { Words { text: Some(text) } } fn next_word(&mut self) -> Option<&'a str> { let text = self.text?; let mut iter = text.splitn(2, char::is_whitespace); match (iter.next(), iter.next()) { (Some(word), rest) => { self.text = rest; Some(word) }, _ => unreachable!() } } } fn hello() -> &'static str { let mut words = Words::new("hello world"); words.next_word().unwrap() } trait MyTrait {} impl MyTrait for String {} struct Wrapper<T: MyTrait>(T); fn save_for_later<T: MyTrait>(something: T) -> Wrapper<T> { Wrapper(something) } fn main() { let text = String::from("To be or no to be?"); let result = { let pattern = String::from("no"); first_occurrence(&text, &pattern) }; println!("{:?}", result); println!("{}", hello()); let saved = { let s = String::from("Great!"); save_for_later(s) }; let inner = &saved.0; println!("{}", inner); } #[cfg(test)] mod tests { #[test] fn it_works_from_main() { assert_eq!(2 + 2, 4); } }
true
53b6cab794e5d393ef30a505eafd4f74bb24e17f
Rust
arielhenryson/cheetah
/cheetah_lib/src/jit/jit.rs
UTF-8
2,822
2.828125
3
[]
permissive
use cranelift::prelude::*; use cranelift_module::{ DataContext, Linkage, Module }; use cranelift_simplejit::{ SimpleJITBackend, SimpleJITBuilder }; use crate::types::expression::Expression; pub struct JIT { /// The function builder context, which is reused across multiple /// FunctionBuilder instances. pub builder_context: FunctionBuilderContext, /// The main Cranelift context, which holds the state for codegen. Cranelift /// separates this from `Module` to allow for parallel compilation, with a /// context per thread, though this isn't in the simple demo here. pub ctx: codegen::Context, /// The data context, which is to data objects what `ctx` is to functions. pub _data_ctx: DataContext, /// The module, with the simplejit backend, which manages the JIT'd /// functions. pub module: Module<SimpleJITBackend>, } impl JIT { pub fn new() -> Self { let builder = SimpleJITBuilder::new( cranelift_module::default_libcall_names() ); let module = Module::new(builder); Self { builder_context: FunctionBuilderContext::new(), ctx: module.make_context(), _data_ctx: DataContext::new(), module, } } pub fn compile(&mut self, expression: Expression) -> Result<*const u8, String> { self.translate(expression)?; // Next, declare the function to simplejit. Functions must be declared // before they can be called, or defined. // // TODO: This may be an area where the API should be streamlined; should // we have a version of `declare_function` that automatically declares // the function? let id = self .module .declare_function("func1", Linkage::Export, &self.ctx.func.signature) .map_err(|e| e.to_string())?; // Define the function to simplejit. This finishes compilation, although // there may be outstanding relocations to perform. Currently, simplejit // cannot finish relocations until all functions to be called are // defined. For this toy demo for now, we'll just finalize the function // below. self.module .define_function(id, &mut self.ctx) .map_err(|e| e.to_string())?; // Now that compilation is finished, we can clear out the context state. self.module.clear_context(&mut self.ctx); // Finalize the functions which we just defined, which resolves any // outstanding relocations (patching in addresses, now that they're // available). self.module.finalize_definitions(); // We can now retrieve a pointer to the machine code. let code = self.module.get_finalized_function(id); Ok(code) } }
true
06a636a653d21f280e27a3df224248cc892a8bba
Rust
paopao-chen/blog
/杂货箱/编程语言/rust/demo/src/main.rs
UTF-8
329
3.046875
3
[]
no_license
use std::io; use rand::Rng; fn main() { println!("Hello, world!"); println!("please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Fail to read line"); println!("this is you guessed: {}",guess); let secret_num = rand::thread_rng().gen_range(1,101); }
true
a91ad78258cdde4b706b4712b435b35d3cbdeaa4
Rust
battesonb/entry
/src/schema.rs
UTF-8
8,320
3.09375
3
[ "MIT" ]
permissive
use chrono::{ prelude::{NaiveDate, NaiveDateTime}, DateTime, }; use serde::{Deserialize, Serialize}; use serde_json::{Number, Value}; use std::{ collections::{btree_map::IntoIter, BTreeMap}, fs::{self, File, OpenOptions}, io::BufReader, str::FromStr, }; use crate::{config::Config, errors::SchemaError}; #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] pub enum SchemaCount { #[serde(rename = "one")] One, #[serde(rename = "many")] Many, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub enum SchemaDataType { #[serde(rename = "string")] String, #[serde(rename = "number")] Number, #[serde(rename = "date")] Date, #[serde(rename = "datetime")] DateTime, } impl std::fmt::Display for SchemaDataType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&format_args!("{:?}", self).to_string().to_lowercase()) } } impl FromStr for SchemaDataType { type Err = SchemaError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().as_str() { "date" => Ok(SchemaDataType::Date), "number" => Ok(SchemaDataType::Number), "string" => Ok(SchemaDataType::String), _ => Err(SchemaError::ParseError), } } } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub struct SchemaType { pub count: SchemaCount, pub data_type: SchemaDataType, } impl std::fmt::Display for SchemaType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.count { SchemaCount::One => f.write_fmt(format_args!("{}", self.data_type)), SchemaCount::Many => f.write_fmt(format_args!("array of {}s", self.data_type)), } } } impl SchemaType { pub fn parse(&self, value: &str) -> Option<Value> { let trimmed = value.trim(); if trimmed.is_empty() { return match self.count { SchemaCount::Many => Some(Value::Array(vec![])), SchemaCount::One => None, }; } match self.count { SchemaCount::Many => { let split = trimmed.split(','); let mut vec: Vec<Value> = Vec::new(); for v in split { if let Some(parsed) = self.parse_individual(v) { vec.push(parsed); } else { return None; } } Some(Value::Array(vec)) } SchemaCount::One => self.parse_individual(trimmed), } } fn parse_individual(&self, value: &str) -> Option<Value> { match self.data_type { SchemaDataType::Date => { let custom_date_formats = ["%Y-%m-%d", "%Y/%m/%d"]; for &format in custom_date_formats.iter() { if NaiveDate::parse_from_str(value, format).is_ok() { return Some(Value::String(value.to_string())); } } None } SchemaDataType::DateTime => { if DateTime::parse_from_rfc2822(value).is_ok() { return Some(Value::String(value.to_string())); } if DateTime::parse_from_rfc3339(value).is_ok() { return Some(Value::String(value.to_string())); } let custom_datetime_formats = [ "%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y/%m/%d %H:%M", ]; for &format in custom_datetime_formats.iter() { if NaiveDateTime::parse_from_str(value, format).is_ok() { return Some(Value::String(value.to_string())); } } None } SchemaDataType::Number => Number::from_str(value).map(Value::Number).ok(), SchemaDataType::String => Some(Value::String(value.to_string())), } } } #[derive(Deserialize, Serialize)] pub struct Schema { shape: BTreeMap<String, SchemaType>, } impl Default for Schema { fn default() -> Self { Schema { shape: BTreeMap::new(), } } } impl IntoIterator for Schema { type Item = (String, SchemaType); type IntoIter = IntoIter<String, SchemaType>; fn into_iter(self) -> Self::IntoIter { self.shape.into_iter() } } impl Schema { pub fn insert(&mut self, key: String, value: SchemaType) { self.shape.insert(key, value); } pub fn is_empty(&self) -> bool { self.shape.is_empty() } pub fn list(config: &Config) -> Vec<String> { if let Ok(dir) = fs::read_dir(format!("{}/schema", &config.data_directory())) { let names: Vec<String> = dir .filter_map(|f| { if let Ok(entry) = f { let file_name = entry.file_name().to_string_lossy().to_string(); if file_name.ends_with(".json") { Some(file_name[..file_name.len() - 5].to_string()) } else { None } } else { None } }) .collect(); return names; } Vec::new() } pub fn print(&self) { if let Ok(json_str) = serde_json::to_string(&self) { println!("{}", json_str); } } pub fn save(&self, path: &str, name: &str) -> Result<(), SchemaError> { let full_path = format!("{}/{}.json", path, name); let result = OpenOptions::new() .create(true) .write(true) .truncate(true) .open(full_path); match result { Ok(file) => { let write_result = serde_json::to_writer_pretty(file, &self); match write_result { Ok(_) => Ok(()), Err(_) => Err(SchemaError::SaveError), } } Err(_) => Err(SchemaError::SaveError), } } pub fn load(path: &str, name: &str) -> Result<Schema, SchemaError> { let full_path = format!("{}/{}.json", path, name); let result = File::open(full_path); match result { Ok(file) => { let reader = BufReader::new(file); let schema_result = serde_json::from_reader(reader); match schema_result { Ok(schema) => Ok(schema), Err(_) => Err(SchemaError::ParseError), } } Err(_) => Err(SchemaError::LoadError), } } pub fn remove(path: &str, name: &str) -> Result<(), SchemaError> { let full_path = format!("{}/{}.json", path, name); match fs::remove_file(full_path) { Ok(_) => Ok(()), Err(_) => Err(SchemaError::RemoveError), } } } #[cfg(test)] mod tests { use super::*; #[test] fn schema_types_can_parse_individual_data_types() { let data_types = [ ( SchemaDataType::Date, "2021/04/25", Value::String("2021/04/25".to_string()), ), ( SchemaDataType::DateTime, "2021/04/25 11:17:00", Value::String("2021/04/25 11:17:00".to_string()), ), ( SchemaDataType::Number, "20.5", Value::Number(Number::from_f64(20.5).unwrap()), ), ( SchemaDataType::String, "anything531", Value::String("anything531".to_string()), ), ]; for (data_type, input, value) in data_types.iter() { let schema_type = SchemaType { count: SchemaCount::One, data_type: *data_type, }; assert_eq!(schema_type.parse(*input).unwrap(), value.clone()); } } }
true
37778255419c7c400e4da201c2aa0b6f90c2c432
Rust
ekarademir/rust-learning
/sdl2-base-project/src/main.rs
UTF-8
3,243
2.71875
3
[]
no_license
#[macro_use] extern crate log; extern crate env_logger; extern crate sdl2; use std::env; use log::Level; use sdl2::render::{ WindowCanvas }; use sdl2::surface::Surface; use sdl2::pixels::PixelFormatEnum; #[allow(unused_imports)] use sdl2::gfx::primitives::DrawRenderer; mod rotatingwave; mod pacman; use crate::rotatingwave::core::{ Application, ApplicationOptions, }; use crate::rotatingwave::color::NamedColours; use crate::rotatingwave::paint::{ Drawing, Painter, MyWindow, Drawable }; use crate::pacman::scene::Container; #[derive(Clone)] pub struct Tile { pub x: i32, pub y: i32, pub width: u32, pub height: u32 } impl Tile { pub fn new() -> Tile { Tile { x: 0, y: 0, width: 30, height: 30 } } pub fn set_x(&mut self, x: i32) -> &Self { self.x = x; self } } impl Drawable for Tile { fn get_x(&self) -> i32 { self.x } fn get_y(&self) -> i32 { self.y } fn draw(&self) -> Surface { let s = Surface::new(self.width, self.height, PixelFormatEnum::RGBA8888).unwrap(); let mut c = s.into_canvas().unwrap(); c.set_draw_color(NamedColours::CYAN); c.clear(); // c.set_draw_color(NamedColours::CYAN); // c.fill_rect(rect: R) c.into_surface() } } struct MyModel; fn main() { env_logger::init(); let current_dir = match env::current_dir() { Ok(dir) => { info!("Running from {:?}", dir); dir }, Err(msg) => panic!(format!("Could not find current directory. {}", msg)) }; let options = ApplicationOptions { width: Some(1000), height: Some(800), fullscreen: None, resource_folder: Some(current_dir.join("resources")), }; let mut app = Application::new(MyModel{}); app.init("Application", options); app.start(Some(update)); } fn update(_model: &mut MyModel, painter: &mut Painter) { painter.canvas.set_draw_color(NamedColours::BLACK); painter.canvas.clear(); let tile = Tile::new(); let mut scene = Container::new(800, 200); for i in 0..10 { let mut a = tile.clone(); a.set_x(i * (10 + a.width as i32)); scene.push(a); } painter.copy_to_window(&scene.draw(), 10, 10); // painter.canvas.aa_circle(300, 300, 30, NamedColours::LIGHT_WALNUT).unwrap(); // painter.canvas.circle(500, 300, 30, NamedColours::MATTE_FUCHSIA).unwrap(); // painter.text("test TEST Thinnest", 24, 50, 50, Some("font_thinnest")); // painter.text("test TEST Thinner", 24, 50, 100, Some("font_thinner")); // painter.text("test TEST Thin", 24, 50, 150, Some("font_thin")); // painter.text("test TEST Normal", 24, 50, 200, None); // painter.text("test TEST Bold", 24, 50, 250, Some("font_bold")); // painter.text("test TEST Bolder", 24, 50, 300, Some("font_bolder")); // painter.text("test TEST Boldest", 24, 50, 350, Some("font_boldest")); // painter.text("test TEST Black", 24, 50, 400, Some("font_black")); // Drawing::draw(&mut painter.canvas); // let myw = MyWindow::new(200, 100); // myw.copy_to_window(&mut painter.canvas, 10, 10); // painter.copy_to_window(&myw.draw(), 10, 10); }
true
567efb5a37519b9574a58ff96d84448ce8c44fc8
Rust
tasgon/synthy
/src/midi_interpreter.rs
UTF-8
2,046
2.859375
3
[]
no_license
use midly::{Event, EventKind, MetaMessage}; use std::vec::Vec; // Algorithms and concepts taken from 'https://github.com/mido/mido/', covered by the MIT license /// Convert all events' delay items from relative to absolute timings. pub fn to_abstime(v: Vec<Event<'_>>) -> Vec<Event<'_>> { let mut now: u32 = 0; v.iter() .map(move |i: &Event<'_>| { let delta: u32 = i.delta.into(); now += delta; let mut n = i.clone(); n.delta = now.into(); n }) .collect() } /// Convert all events' delay items from absolute to relative timings. pub fn to_reltime(v: Vec<Event<'_>>) -> Vec<Event<'_>> { let mut now: u32 = 0; v.iter() .map(move |i: &Event<'_>| { let delta: u32 = i.delta.into(); let mut n = i.clone(); n.delta = (delta - now).into(); now = delta; n }) .collect() } /// Remove all extra `EndOfTrack` messages. pub fn fix_track_end(v: Vec<Event<'_>>) -> Vec<Event<'_>> { let mut out: Vec<Event<'_>> = vec![]; let mut accum: u32 = 0; for msg in v { if msg.kind == EventKind::Meta(MetaMessage::EndOfTrack) { let delta: u32 = msg.delta.into(); accum += delta; } else { let mut ev = msg.clone(); if accum > 0 { let delta: u32 = msg.delta.into(); ev.delta = (delta + accum).into(); } out.push(ev) } } out.push(Event { delta: accum.into(), kind: EventKind::Meta(MetaMessage::EndOfTrack), }); out } /// Convert an array of tracks to one array containing all the events. pub fn as_merged(v: Vec<Vec<Event<'_>>>) -> Vec<Event<'_>> { let mut messages: Vec<Event<'_>> = vec![]; v.iter() .for_each(|i| messages.extend(to_abstime(i.clone()))); messages.sort_by_key(|i: &Event<'_>| { let n: u32 = i.delta.into(); n }); fix_track_end(to_reltime(messages)) }
true
f0e9a21c899c34dbf2f90ec8c2535bca2c2d6542
Rust
sria91-rlox/rlox-31
/src/token_type.rs
UTF-8
495
2.890625
3
[ "MIT" ]
permissive
pub enum TokenType { // Single-character tokens. LeftParen, RightParen, LeftBrace, RightBrace, Comma, Dot, Minus, Plus, SemiColon, Slash, Star, // One or two character tokens. Bang, BangEqual, Equal, EqualEqual, Greater, GreaterEqual, Less, LessEqual, // Literals. Identifier, STRING, Number, // Keywords. And, Class, Else, False, Fun, For, If, Nil, Or, Print, Return, Super, This, True, Var, While, Eof }
true
b1882fae3c06b64a18c2e31ff2afd0e8974cfd28
Rust
ZentaChainAdmin/zkinterface
/cpp/libsnark-rust/src/gadgetlib.rs
UTF-8
5,239
2.5625
3
[ "MIT" ]
permissive
// // @author Aurélien Nicolas <aurel@qed-it.com> // @date 2019 use std::slice; use std::error::Error; use zkinterface::{ reading::Messages, owned::circuit::CircuitOwned, owned::command::CommandOwned, }; #[allow(improper_ctypes)] extern "C" { fn gadgetlib_call_gadget( circuit_msg: *const u8, command_msg: *const u8, constraints_callback: extern fn(context_ptr: *mut Messages, message: *const u8) -> bool, constraints_context: *mut Messages, witness_callback: extern fn(context_ptr: *mut Messages, message: *const u8) -> bool, witness_context: *mut Messages, return_callback: extern fn(context_ptr: *mut Messages, message: *const u8) -> bool, return_context: *mut Messages, ) -> bool; } /// Collect the stream of any messages into the context. extern "C" fn receive_message_callback( context_ptr: *mut Messages, message_ptr: *const u8, ) -> bool { let (context, buf) = from_c(context_ptr, message_ptr); context.push_message(Vec::from(buf)).is_ok() } // Read a size prefix (4 bytes, little-endian). fn read_size_prefix(ptr: *const u8) -> u32 { let buf = unsafe { slice::from_raw_parts(ptr, 4) }; ((buf[0] as u32) << 0) | ((buf[1] as u32) << 8) | ((buf[2] as u32) << 16) | ((buf[3] as u32) << 24) } // Bring arguments from C calls back into the type system. fn from_c<'a, CTX>( context_ptr: *mut CTX, response: *const u8, ) -> (&'a mut CTX, &'a [u8]) { let context = unsafe { &mut *context_ptr }; let response_len = read_size_prefix(response) + 4; let buf = unsafe { slice::from_raw_parts(response, response_len as usize) }; (context, buf) } pub fn call_gadget(circuit: &CircuitOwned, command: &CommandOwned) -> Result<Messages, Box<dyn Error>> { let mut circuit_buf = vec![]; circuit.write(&mut circuit_buf)?; let mut command_buf = vec![]; command.write(&mut command_buf)?; let mut output_context = Messages::new(circuit.free_variable_id); let ok = unsafe { gadgetlib_call_gadget( circuit_buf.as_ptr(), command_buf.as_ptr(), receive_message_callback, &mut output_context as *mut Messages, receive_message_callback, &mut output_context as *mut Messages, receive_message_callback, &mut output_context as *mut Messages, ) }; match ok { true => Ok(output_context), false => Err("call_gadget failed".into()), } } #[test] fn test_cpp_gadget() { use zkinterface::owned::variables::VariablesOwned; let mut subcircuit = CircuitOwned { connections: VariablesOwned { variable_ids: vec![100, 101, 102, 103], // Some input variables. values: None, }, free_variable_id: 104, field_maximum: None, }; println!("==== R1CS generation ===="); let command = CommandOwned { constraints_generation: true, witness_generation: false }; let r1cs_response = call_gadget(&subcircuit, &command).unwrap(); println!("R1CS: Rust received {} messages including {} gadget return.", r1cs_response.messages.len(), r1cs_response.circuits().len()); assert!(r1cs_response.messages.len() == 2); assert!(r1cs_response.circuits().len() == 1); println!("R1CS: Got constraints:"); for c in r1cs_response.iter_constraints() { println!("{:?} * {:?} = {:?}", c.a, c.b, c.c); } let free_variable_id_after = r1cs_response.last_circuit().unwrap().free_variable_id(); println!("R1CS: Free variable id after the call: {}\n", free_variable_id_after); assert!(free_variable_id_after == 104 + 36); println!("==== Witness generation ===="); // Specify input values. subcircuit.connections.values = Some(vec![11, 12, 9, 14 as u8]); let command = CommandOwned { constraints_generation: false, witness_generation: true }; let witness_response = call_gadget(&subcircuit, &command).unwrap(); println!("Assignment: Rust received {} messages including {} gadget return.", witness_response.messages.len(), witness_response.circuits().len()); assert!(witness_response.messages.len() == 2); assert!(witness_response.circuits().len() == 1); { let assignment: Vec<_> = witness_response.iter_witness().collect(); println!("Assignment: Got witness:"); for var in assignment.iter() { println!("{:?}", var); } assert_eq!(assignment.len(), 36); assert_eq!(assignment[0].id, 104 + 0); // First gadget-allocated variable. assert_eq!(assignment[0].value.len(), 32); assert_eq!(assignment[1].id, 104 + 1); // Second " assert_eq!(assignment[1].value.len(), 32); let free_variable_id_after2 = witness_response.last_circuit().unwrap().free_variable_id(); println!("Assignment: Free variable id after the call: {}", free_variable_id_after2); assert!(free_variable_id_after2 == free_variable_id_after); let out_vars = witness_response.connection_variables().unwrap(); println!("Output variables: {:?}", out_vars); assert_eq!(out_vars.len(), 2); } println!(); }
true
77a6e3b2d25a8c34cfd9b6fb16eda193cfe3e67e
Rust
Yosshi999/slackbot
/ricochet-robots/src/main.rs
UTF-8
8,849
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::env; use std::collections::VecDeque; use std::collections::HashSet; use std::hash::{Hash, Hasher}; extern crate rand; use rand::Rng; use rand::prelude::SliceRandom; use std::cmp; extern crate atoi; use atoi::atoi; extern crate itertools; use itertools::Itertools; use std::rc::Rc; #[derive(PartialEq,Eq,Debug,Clone)] struct Pos { y: i8, x: i8 } impl Hash for Pos { fn hash<H: Hasher>(&self,state: &mut H) { self.y.hash(state); self.x.hash(state); } } #[derive(Debug)] struct WallPos { y: i8, x: i8, d: i8 } #[derive(Debug)] struct Board { w: usize, h: usize, walls: Vec<WallPos>, haswall: Vec<Vec<Vec<bool>>>, robots: Vec<Pos>, } const DIRECTIONS: [Pos; 4] = [ (Pos{y: 1,x: 0}), (Pos{y: 0,x: 1}), (Pos{y: -1,x: 0}), (Pos{y: 0,x: -1}) ]; impl Board { fn good_board(&mut self) -> bool { let mut gone = vec![vec![false;self.w];self.h]; fn dfs<'a>(gone: &'a mut Vec<Vec<bool>>,self_: &'a Board,y: usize, x: usize) -> usize { //println!("{} {}",y,x); if gone[y][x] { return 0; } gone[y][x] = true; let mut res = 1; for i in 0..4 { if self_.haswall[y][x][i] { continue; } let ty = (y as i8 + DIRECTIONS[i].y) as usize; let tx = (x as i8 + DIRECTIONS[i].x) as usize; if ty < self_.h && tx < self_.w { res += dfs(gone,self_,ty,tx); } } return res; } let cn = dfs(&mut gone,self,0,0); //println!("{}",cn); if cn != self.h * self.w { // all cells aren't connected return false; } //println!("{:?}",self.board); for y in 0..self.h { for x in 0..self.w { let mut d = 0; for i in 0..4 { if !self.haswall[y][x][i] { d += 1; } } //println!("{}",d); if d < 2 { // This cell is not interesting. return false; } } } return true; } fn init(&mut self,wall_num: usize){ self.haswall = vec![vec![vec![false;4];self.w];self.h]; //println!("{} {} {} {}",self.board.len(), self.h, self.board[0].len(), self.w); for y in 0..self.h { self.haswall[y][0][3] = true; self.haswall[y][self.w-1][1] = true; } for x in 0..self.w { self.haswall[0][x][2] = true; self.haswall[self.h-1][x][0] = true; } let mut rng = rand::thread_rng(); for _ in 0..wall_num { let mem_haswall = self.haswall.clone(); let mut add_walls = vec![]; let cy = rng.gen_range(0,self.h); let cx = rng.gen_range(0,self.w); { let y = cy + rng.gen_range(0,2); let x = cx; if 0 < y && y < self.h { add_walls.push(WallPos{y: y as i8, x: x as i8, d: 0}); self.haswall[y-1][x][0] = true; self.haswall[y][x][2] = true; } } { let y = cy; let x = cx + rng.gen_range(0,2); if 0 < x && x < self.w { add_walls.push(WallPos{y: y as i8, x: x as i8, d: 1}); self.haswall[y][x-1][1] = true; self.haswall[y][x][3] = true; } } if self.good_board() { println!("add walls {:?}",add_walls); self.walls.append(&mut add_walls); } else{ self.haswall = mem_haswall; } } let mut i = 0; while i < 4 { let tp = Pos{y: rng.gen_range(0,self.h) as i8, x: rng.gen_range(0,self.w) as i8}; let mut ok = true; for j in 0..i { ok &= tp != self.robots[j]; } if ok { self.robots.push(tp); i += 1; } } } pub fn new(board_h: usize,board_w: usize,wall_num: usize) -> Board { let mut res = Board {w: board_w, h: board_h, walls: vec![],haswall: vec![], robots: vec![]}; res.init(wall_num); return res; } } #[derive(Debug,Clone,Copy)] struct Move{ c: usize, d: usize } struct SinglyLinkedListNode{ v: Move, next: Option<Rc<SinglyLinkedListNode>> } struct SinglyLinkedList { head: Option<Rc<SinglyLinkedListNode>> } impl SinglyLinkedList{ pub fn nil() -> SinglyLinkedList { //SinglyLinkedList{node: SinglyLinkedList_data::Nil} SinglyLinkedList{head: None} } fn cons(&self,data: Move) -> SinglyLinkedList { SinglyLinkedList{head: Some(Rc::new( SinglyLinkedListNode { v: data, next: self.head.clone() } ))} //SinglyLinkedList{node: Some(Box::new((self,data)))} //SinglyLinkedList{node: SinglyLinkedList_data::Cons(Box::new(&self.node),data)} } fn to_vec(&self) -> Vec<Move> { let mut res = vec![]; let mut head = &self.head; while let Some(ref p) = head { res.push(p.v); head = &p.next; } return res; } } struct State<'a> { bo: &'a Board, robots: Vec<Pos>, log: SinglyLinkedList } impl<'a> State<'a> { pub fn init_state(bo:&'a Board,_log: SinglyLinkedList) -> State<'a> { State{bo: &bo,robots: bo.robots.clone(), log: SinglyLinkedList::nil()} } fn move_to(&self,robot_index: usize, robot_dir: usize) -> State<'a>{ let dir = &DIRECTIONS[robot_dir]; let mut p = self.robots[robot_index].clone(); let mut mind = cmp::max(self.bo.h,self.bo.w) as i8; for j in 0..4 { if j != robot_index { let dx = self.robots[j].x - p.x; let dy = self.robots[j].y - p.y; if dx.signum() == dir.x.signum() && dy.signum() == dir.y.signum() { if dx.signum() == 0 { mind = cmp::min(mind,dy.abs()-1); } else { mind = cmp::min(mind,dx.abs()-1); } } } } //println!("{} {:?} {:?}",mind,p,self.robots); for _ in 0..mind { if self.bo.haswall[p.y as usize][p.x as usize][robot_dir] { break; } p = Pos{y: p.y + dir.y, x: p.x + dir.x}; } let tolog = self.log.cons(Move{c: robot_index,d: robot_dir}); let mut res = State{bo: self.bo,robots: self.robots.clone(),log: tolog}; res.robots[robot_index] = p; res } fn enumerate_states(&self) -> Vec<State<'a>> { let mut res = vec![]; for i in 0..self.robots.len() { for j in 0..4 { let ts = self.move_to(i,j); res.push(ts); } } //println!("add {} {}",self.robots.len() ,res.len()); return res; } } impl<'a,'b> PartialEq for State<'a> { fn eq(&self,ts:&State) -> bool { return self.robots == ts.robots; } } impl<'a,'b> Eq for State<'a> {} impl<'a,'b> Hash for State<'a> { fn hash<H: Hasher>(&self,state: &mut H) { self.robots.hash(state); } } fn bfs<'a,'b>(target: u8, bo:&'a Board) -> ((usize,Pos),Vec<Move>){ //let log = &SinglyLinkedList::Nil; let log = SinglyLinkedList::nil(); let init = State::init_state(&bo,log); let mut res = init.log.head.clone(); let mut goal = (0,init.robots[0].clone()); //let mut gone: HashSet<State,BuildHasherDefault<FnvHasher>> = HashSet::new(); let mut gone: HashSet<State> = HashSet::new(); let mut que = VecDeque::new(); let mut depth = 0; que.push_back(Some(init)); que.push_back(None); let mut found : Vec<Vec<Vec<bool>>> = vec![vec![vec![false;bo.robots.len()];bo.w];bo.h]; let mut found_count = 0; let mut dnum = 1; while !que.is_empty() { match que.pop_front() { Some(Some(st)) => { if !gone.contains(&st) { dnum += 1; //println!("{:?}",st.robots); let mut ok = false; for i in 0..st.robots.len() { let p = &st.robots[i]; if !found[p.y as usize][p.x as usize][i] { //println!("{} {} {} : {} ",p.y,p.x,i,depth); found[p.y as usize][p.x as usize][i] = true; found_count += 1; res = st.log.head.clone(); goal = (i,p.clone()); if depth >= target || found_count >= bo.h * bo.w * bo.robots.len() { ok = true; break; } } } if ok { break; } for ts in st.enumerate_states() { if !gone.contains(&ts) { //println!("{:?}",ts.robots); que.push_back(Some(ts)); } } gone.insert(st); } }, Some(None) => { depth += 1; if depth > target { break; } println!("{} {}",depth,dnum); dnum = 0; que.push_back(None); }, None => {} } } //return None; let l = SinglyLinkedList{head: res}; return (goal,l.to_vec()); //return l.to_vec(); //SinglyLinkedList::to_vec(l); } fn main(){ let args: Vec<String> = env::args().collect(); let (depth,board_h,board_w,wall_num) = match args[1..5].into_iter().map(|x| atoi(x.as_bytes())).tuples().next() { Some((Some(a),Some(b),Some(c),Some(d))) => (a,b,c,d), v => panic!("invalid argument. expect \"depth board_h board_w wall_num\", got {:?}.",v) }; let mut bo = Board::new(board_h,board_w,wall_num); let ((mut goalcolour,goalpos),mut log) = bfs(depth as u8,&bo); //randomize colour let mut rng = rand::thread_rng(); let mut perm: Vec<usize> = (0..bo.robots.len()).collect(); perm.shuffle(&mut rng); let mut perminv: Vec<usize> = vec![0;perm.len()]; for i in 0..perm.len() { perminv[perm[i]] = i; } goalcolour = perm[goalcolour]; log = log.into_iter().map(|x| Move{c: perm[x.c],d: x.d}).rev().collect(); bo.robots = (0..bo.robots.len()).map(|k| bo.robots[perminv[k]].clone()).collect(); println!("{:?}",bo); println!("{:?}",goalcolour); println!("{:?}",goalpos); println!("{:?}",log); }
true
b9f82a8bfe8660a7ed686888289d14829a5ab595
Rust
ondrowan/dgraph-cli
/src/commands/query.rs
UTF-8
1,176
2.578125
3
[ "MIT" ]
permissive
use clap::ArgMatches; use dgraph; use crate::error; pub fn handler( query_matches: &ArgMatches, dgraph_client: &dgraph::Dgraph, ) -> Result<(), error::Error> { let mut txn = dgraph_client.new_readonly_txn(); let response = txn.query( query_matches .value_of("query_value") .expect("Query should contain query_value.") .to_string(), )?; if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&response.json) { if let Ok(pretty_json) = serde_json::to_string_pretty(&json) { println!("{}", pretty_json); } let latency = response.get_latency(); println!( "\nLatency:\n\nProcessing: {}\nParsing: {}\nEncoding: {}", convert_and_format_ns(latency.processing_ns), convert_and_format_ns(latency.parsing_ns), convert_and_format_ns(latency.encoding_ns) ); } Ok(()) } fn convert_and_format_ns(time: u64) -> std::string::String { let ms = time as f64 / 1_000_000.0; if ms > 1000 as f64 { let s = ms / 1000 as f64; return format!("{}s", s); } format!("{}ms", ms) }
true
d1c5b6e4a33c5778baa0e5b04f793852f316c166
Rust
Eldhrimer/spot
/src/app/components/window/mod.rs
UTF-8
3,297
2.59375
3
[ "MIT" ]
permissive
use gtk::prelude::*; use std::cell::RefCell; use std::rc::Rc; use crate::app::components::EventListener; use crate::app::{AppEvent, AppModel}; use crate::settings::WindowGeometry; thread_local! { static WINDOW_GEOMETRY: RefCell<WindowGeometry> = RefCell::new(WindowGeometry { width: 0, height: 0, is_maximized: false }); } pub struct MainWindow { initial_window_geometry: WindowGeometry, window: libadwaita::ApplicationWindow, } impl MainWindow { pub fn new( initial_window_geometry: WindowGeometry, app_model: Rc<AppModel>, window: libadwaita::ApplicationWindow, search_bar: gtk::SearchBar, ) -> Self { window.connect_close_request( clone!(@weak app_model => @default-return gtk::Inhibit(false), move |window| { let state = app_model.get_state(); if state.playback.is_playing() { window.hide(); gtk::Inhibit(true) } else { gtk::Inhibit(false) } }), ); let window_controller = gtk::EventControllerKey::new(); window.add_controller(&window_controller); window_controller.set_propagation_phase(gtk::PropagationPhase::Bubble); window_controller.connect_key_pressed(clone!(@weak search_bar, @weak window => @default-return gtk::Inhibit(false), move |controller, _, _, _| { let search_triggered = controller.forward(&search_bar) || search_bar.is_search_mode(); if search_triggered { search_bar.set_search_mode(true); gtk::Inhibit(true) } else if let Some(child) = window.first_child().as_ref() { gtk::Inhibit(controller.forward(child)) } else { gtk::Inhibit(false) } })); window.connect_default_height_notify(Self::save_window_geometry); window.connect_default_width_notify(Self::save_window_geometry); window.connect_maximized_notify(Self::save_window_geometry); window.connect_unrealize(|_| { WINDOW_GEOMETRY.with(|g| g.borrow().save()); }); Self { initial_window_geometry, window, } } fn start(&self) { self.window.set_default_size( self.initial_window_geometry.width, self.initial_window_geometry.height, ); if self.initial_window_geometry.is_maximized { self.window.maximize(); } self.window.present(); } fn raise(&self) { self.window.present(); } fn save_window_geometry<W: GtkWindowExt>(window: &W) { let (width, height) = window.default_size(); let is_maximized = window.is_maximized(); WINDOW_GEOMETRY.with(|g| { let mut g = g.borrow_mut(); g.is_maximized = is_maximized; if !is_maximized { g.width = width; g.height = height; } }); } } impl EventListener for MainWindow { fn on_event(&mut self, event: &AppEvent) { match event { AppEvent::Started => self.start(), AppEvent::Raised => self.raise(), _ => {} } } }
true
cae8052a775fd5423212715ba0537b6f5d74c29c
Rust
HareInWeed/slice_2d
/src/fill.rs
UTF-8
695
2.859375
3
[ "MIT" ]
permissive
use crate::{ iter::Slice2DIterMut, slice::{Shape2D, SlicePtrMut}, }; pub trait Slice2DFill<T> { fn fill(&mut self, value: T) where T: Clone; fn fill_with<F>(&mut self, f: F) where F: FnMut() -> T; } impl<T: Clone, S> Slice2DFill<T> for S where S: Shape2D + SlicePtrMut<T> + Slice2DIterMut<T, S>, { #[inline] fn fill(&mut self, value: T) where T: Clone, { self.row_iter_mut() .flatten() .for_each(|e| *e = value.clone()); } #[inline] fn fill_with<F>(&mut self, mut f: F) where F: FnMut() -> T, { self.row_iter_mut().flatten().for_each(|e| *e = f()); } }
true
f5d0a2455805aa25cb7f2204b8698445b76b3624
Rust
pkpkpk/serde-fressian
/tests/rt.rs
UTF-8
7,099
2.5625
3
[ "MIT" ]
permissive
#![allow(dead_code)] #![allow(unused_imports)] #![allow(non_snake_case)] #[macro_use] extern crate maplit; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_bytes; extern crate serde_fressian; extern crate ordered_float; use std::collections::{BTreeSet, BTreeMap}; use ordered_float::OrderedFloat; use serde_bytes::{ByteBuf, Bytes}; // use serde_fressian::inst::{INST}; // use serde_fressian::uuid::{UUID}; // use serde_fressian::uri::{URI}; // use serde_fressian::regex::{REGEX}; use serde_fressian::sym::{SYM}; use serde_fressian::key::{KEY}; // use serde_fressian::typed_arrays::*; use serde_fressian::set::{SET}; use serde_fressian::value::{self, Value}; use serde_fressian::de::{self}; use serde_fressian::ser::{self}; #[test] fn bytes_rt(){ // (write (u8-array [0 1 2 126 127 128 253 254 255])) let control_bytes: Vec<u8> = vec![217,9,0,1,2,126,127,128,253,254,255]; let control_slice: &[u8] = &[0,1,2,126,127,128,253,254,255]; let control_bb = ByteBuf::from(control_slice); // strongly typed let test_bb: ByteBuf = de::from_vec(&control_bytes).unwrap(); assert_eq!(control_bb, test_bb); let test_bytes: Vec<u8> = ser::to_vec(&test_bb).unwrap(); assert_eq!(control_bytes, test_bytes); // VALUE let control_value = Value::BYTES(control_bb); let test_value: Value = de::from_vec(&control_bytes).unwrap(); assert_eq!(test_value, control_value); let test_bytes: Vec<u8> = ser::to_vec(&test_value).unwrap(); assert_eq!(control_bytes, test_bytes); } #[test] fn set_rt(){ // (write #{0 1 2 3}) let control_bytes: Vec<u8> = vec![193,232,0,1,3,2]; let control_set: BTreeSet<i64> = btreeset!{0,1,2,3}; // strongly typed let test_set: BTreeSet<i64> = de::from_vec(&control_bytes).unwrap(); assert_eq!(test_set, control_set); let s: SET<i64> = SET::from(control_set); let test_bytes: Vec<u8> = ser::to_vec(&s).unwrap(); // sets write with nondet ordering so cannot compare bytes directly let derived_set: BTreeSet<i64> = de::from_vec(&test_bytes).unwrap(); assert_eq!(*s, derived_set); // VALUE let control_set: BTreeSet<i64> = btreeset!{0,1,2,3}; let control_value: Value = Value::from(control_set); let test_value: Value = de::from_vec(&test_bytes).unwrap(); assert_eq!(control_value, test_value); let test_bytes: Vec<u8> = ser::to_vec(&test_value).unwrap(); // sets write with nondet ordering so cannot compare bytes directly let derived_set_value: Value = de::from_vec(&test_bytes).unwrap(); assert_eq!(control_value, derived_set_value); } #[test] fn homogenous_map_rt(){ // simpl valid rust maps, all keys are same T, all vals same T // (write {"a" 0 "b" 1}) let control_bytes: Vec<u8> = vec![192,232,219,97,0,219,98,1]; let control_map: BTreeMap<String, i64> = btreemap!{ "a".to_string() => 0, "b".to_string() => 1 }; // strongly typed let test_map: BTreeMap<String, i64> = de::from_vec(&control_bytes).unwrap(); assert_eq!(control_map, test_map); let test_bytes: Vec<u8> = ser::to_vec(&test_map).unwrap(); // maps write with nondet ordering so cannot compare bytes directly let derived_map: BTreeMap<String, i64> = de::from_vec(&test_bytes).unwrap(); assert_eq!(control_map, derived_map); // VALUE let control_map_value: Value = Value::from(control_map); let test_map_value: Value = de::from_vec(&control_bytes).unwrap(); assert_eq!(control_map_value, test_map_value); let test_bytes: Vec<u8> = ser::to_vec(&test_map_value).unwrap(); let derived_map_value: Value = de::from_vec(&test_bytes).unwrap(); assert_eq!(control_map_value, derived_map_value); // (write {:a/b []}) let control_bytes: Vec<u8> = vec![192,230, //KEY 202, //PUT_PRIORITY_CACHE 205, //STRING_PACKED 1 219, 97, // 'a' // PUT_PRIORITY_CACHE 205, //STRING_PACKED 1 219, 98,// 'b' //LIST_PACKED_LENGTH_START 0 228]; let k = KEY::namespaced("a".to_string(),"b".to_string()); let control_map: BTreeMap<KEY, Vec<i64>> = btreemap!{ k => vec![]}; // strongly typed let test_map: BTreeMap<KEY, Vec<i64>> = de::from_vec(&control_bytes).unwrap(); assert_eq!(control_map, test_map); let test_bytes: Vec<u8> = ser::to_vec(&test_map).unwrap(); let derived_map: BTreeMap<KEY, Vec<i64>> = de::from_vec(&test_bytes).unwrap(); assert_eq!(control_map, derived_map); // Value let control_map_value: Value = Value::from(control_map); let test_map_value: Value = de::from_vec(&control_bytes).unwrap(); assert_eq!(control_map_value, test_map_value); let test_bytes: Vec<u8> = ser::to_vec(&test_map_value).unwrap(); let derived_map_value: Value = de::from_vec(&test_bytes).unwrap(); assert_eq!(control_map_value, derived_map_value); // (write {:a [1 2 3] :b/b []}) let control_bytes: Vec<u8> = vec![192,232,202,247,205,219,97,231,1,2,3,202,205,219,98,129,228]; let a = KEY::simple("a".to_string()); let b = KEY::namespaced("b".to_string(),"b".to_string()); let control_map: BTreeMap<KEY, Vec<i64>> = btreemap!{ a => vec![1, 2, 3], b => vec![] }; // strongly typed let test_map: BTreeMap<KEY, Vec<i64>> = de::from_vec(&control_bytes).unwrap(); assert_eq!(control_map, test_map); let test_bytes: Vec<u8> = ser::to_vec(&test_map).unwrap(); let derived_map: BTreeMap<KEY, Vec<i64>>= de::from_vec(&test_bytes).unwrap(); assert_eq!(control_map, derived_map); // Value let control_map_value: Value = Value::from(control_map); let test_map_value: Value = de::from_vec(&control_bytes).unwrap(); assert_eq!(control_map_value, test_map_value); let test_bytes: Vec<u8> = ser::to_vec(&test_map_value).unwrap(); let derived_map_value: Value = de::from_vec(&test_bytes).unwrap(); assert_eq!(control_map_value, derived_map_value); } #[test] fn cache_hits(){ // (write [:foo :foo :foo :foo]) let control_bytes: Vec<u8> = vec![232,202,247,205,221,102,111,111,202,247,128,202,247,128,202,247,128]; let k = KEY::simple("foo".to_string()); let control_vec: Vec<KEY> = vec![k.clone(),k.clone(),k.clone(),k]; // strongly typed let test_vec: Vec<KEY> = de::from_vec(&control_bytes).unwrap(); assert_eq!(control_vec, test_vec); let test_bytes: Vec<u8> = ser::to_vec(&test_vec).unwrap(); assert_eq!(&control_bytes, &test_bytes); } // need serde-with + type extraction
true
0161d93adc1c071141442eda29032dbb15be2269
Rust
LightHero/lightspeed
/hash/src/service/validation_code_service.rs
UTF-8
2,788
2.859375
3
[ "MIT" ]
permissive
use crate::dto::{ ValidationCodeDataDto, ValidationCodeRequestDto, VerifyValidationCodeRequestDto, VerifyValidationCodeResponseDto, }; use crate::service::hash_service::HashService; use lightspeed_core::error::LightSpeedError; use lightspeed_core::service::jwt::{JwtService, JWT}; use lightspeed_core::utils::current_epoch_seconds; use log::*; use serde::Serialize; use std::sync::Arc; #[derive(Clone)] pub struct ValidationCodeService { jwt_service: Arc<JwtService>, hash_service: Arc<HashService>, } #[derive(Clone, Serialize)] struct ValidationCodeData<'a, Data: Serialize> { to_be_validated: &'a Data, code: &'a str, created_ts_seconds: i64, expiration_ts_seconds: i64, } impl ValidationCodeService { pub fn new(hash_service: Arc<HashService>, jwt_service: Arc<JwtService>) -> Self { Self { jwt_service, hash_service } } pub fn generate_validation_code<Data: Serialize>( &self, request: ValidationCodeRequestDto<Data>, ) -> Result<ValidationCodeDataDto<Data>, LightSpeedError> { info!("Generate validation code"); let created_ts_seconds = current_epoch_seconds(); let expiration_ts_seconds = created_ts_seconds + request.validation_code_validity_seconds; let token_hash = self.hash(ValidationCodeData { expiration_ts_seconds, created_ts_seconds, code: &request.code, to_be_validated: &request.to_be_validated, })?; Ok(ValidationCodeDataDto { to_be_validated: request.to_be_validated, expiration_ts_seconds, created_ts_seconds, token_hash, }) } pub fn verify_validation_code<Data: Serialize>( &self, request: VerifyValidationCodeRequestDto<Data>, ) -> Result<VerifyValidationCodeResponseDto<Data>, LightSpeedError> { debug!("Verify code {}", request.code); let calculated_token_hash = self.hash(ValidationCodeData { expiration_ts_seconds: request.data.expiration_ts_seconds, created_ts_seconds: request.data.created_ts_seconds, code: &request.code, to_be_validated: &request.data.to_be_validated, })?; Ok(VerifyValidationCodeResponseDto { to_be_validated: request.data.to_be_validated, code_valid: calculated_token_hash.eq(&request.data.token_hash), }) } fn hash<Data: Serialize>(&self, data: ValidationCodeData<Data>) -> Result<String, LightSpeedError> { let jwt = JWT { iat: data.created_ts_seconds, exp: data.expiration_ts_seconds, sub: "".to_owned(), payload: data }; let token = self.jwt_service.generate_from_token(&jwt)?; Ok(self.hash_service.hash(&token)) } }
true
67070c8f830db65c59447b27ab7acc698163fe64
Rust
waywardmonkeys/limn
/src/app.rs
UTF-8
4,303
2.65625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
use std::time::{Instant, Duration}; use std::rc::Rc; use std::cell::RefCell; use glutin; use window::Window; use ui::Ui; use input::InputEvent; use widget::WidgetBuilder; use event::{self, EventHandler, EventArgs}; use geometry::Size; /// This is contains the core of a Limn application, /// the Ui, event queue, and the handlers that operate /// directly on the UI. These handlers are used to handle /// global events and modify the UI graph. /// A small set of handlers are configured by default that /// are used in a typical desktop app. This set of handlers /// could be configured differently for a mobile app, for example. pub struct App { ui: Ui, next_frame_time: Instant, events_loop: Rc<RefCell<glutin::EventsLoop>>, } impl App { pub fn new(window: Window, events_loop: glutin::EventsLoop) -> Self { event::queue_set_events_loop(&events_loop); let ui = Ui::new(window, &events_loop); let mut app = App { ui: ui, next_frame_time: Instant::now(), events_loop: Rc::new(RefCell::new(events_loop)), }; app.initialize_handlers(); app } /// Initialize the handlers that are used in a typical desktop app. /// The handlers that make up the event flow in an application are configurable fn initialize_handlers(&mut self) { self.add_ui_handlers(); self.add_layout_handlers(); self.add_input_handlers(); self.add_mouse_handlers(); self.add_keyboard_handlers(); self.add_drag_handlers(); } fn handle_window_event(&mut self, event: glutin::Event) { debug!("handle window event {:?}", event); if let glutin::Event::WindowEvent { event, .. } = event { if let glutin::WindowEvent::Resized(width, height) = event { self.ui.window_resized(Size::new(width as f32, height as f32)); } else { self.ui.event(InputEvent(event)); } } } /// Application main loop pub fn main_loop(mut self, root: WidgetBuilder) { self.ui.root.add_child(root); let events_loop = self.events_loop.clone(); let mut events_loop = events_loop.borrow_mut(); // Handle set up events to allow layout to 'settle' and initialize the window size to the initial layout size self.handle_events(); self.ui.resize_window_to_fit(); loop { events_loop.poll_events(|event| { self.handle_window_event(event); }); if self.ui.should_close() { self.ui.render.deinit(); return; } self.handle_events(); let now = Instant::now(); if now > self.next_frame_time { let frame_length = Duration::new(0, 1_000_000_000 / 60); if self.next_frame_time + frame_length > now { self.next_frame_time = now + frame_length; } else { self.next_frame_time += frame_length; } self.ui.draw_if_needed(); } self.ui.update(); if !self.ui.needs_redraw() && !self.ui.render.frame_ready() { let mut events = Vec::new(); events_loop.run_forever(|window_event| { events.push(window_event); glutin::ControlFlow::Break }); for event in events { self.handle_window_event(event); } } } } /// Handle all the pending events in the event queue fn handle_events(&mut self) { while let Some((event_address, type_id, data)) = event::queue_next() { self.ui.handle_event(event_address, type_id, data.as_ref()); } } /// Add a new stateful global event handler pub fn add_handler<E: 'static, T: EventHandler<E> + 'static>(&mut self, handler: T) -> &mut Self { self.ui.get_root().add_handler(handler); self } /// Add a new stateless global event handler pub fn add_handler_fn<E: 'static, T: Fn(&E, EventArgs) + 'static>(&mut self, handler: T) -> &mut Self { self.ui.get_root().add_handler_fn(handler); self } }
true
33b517ddbb8f6a902f5ec2dfd8ebaf3e8db085bb
Rust
stkerr/RustySea
/src/testing/basic_rem_test.rs
UTF-8
726
2.5625
3
[]
no_license
extern crate rusty_sea; use rusty_sea::bigint::*; use rusty_sea::bigint::utilities::*; op_test!(basic_rem_1, "0x1" % "0x1" == "0x0"); op_test!(basic_rem_2, "0x1" % "0x2" == "0x1"); op_test!(basic_rem_3, "0x2" % "0x1" == "0x0"); op_test!(basic_rem_4, "0x3" % "0x2" == "0x1"); op_test!(basic_rem_5, "0x10" % "0xF" == "0x1"); // 0x10 % 0xF op_test!(basic_rem_6, "0x1F" % "0xF" == "0x1"); op_test!(basic_rem_7, "0x100" % "0x10" == "0x0"); // 0x100 % 0x10 => 1024 % 16 op_test!(basic_rem_8, "0x10000000000000000" % "0x1" == "0x0"); op_test!(basic_rem_9, "0x10000000000000000" % "0x10" == "0x0"); op_test!(basic_rem_10, "0x1000000000000000F" % "0x10" == "0xF"); op_test!(basic_rem_11, "0x51000000000000030F" % "0x400" == "0x30F");
true
dec97d63b0e2879eee030c781e9957098eee324e
Rust
paolosimone/advent-of-code-2020
/src/days/day_17.rs
UTF-8
5,458
3.15625
3
[]
no_license
use std::cmp::min; use itertools::Itertools; use super::Day; pub struct Day17 { input: Plane<Cube>, } impl Day17 { pub fn load(input: &str) -> Self { Self { input: Self::parse_input(input), } } fn parse_input(s: &str) -> Plane<Cube> { s.lines() .map(|l| l.chars().map(Self::parse_cube).collect::<Vec<_>>()) .collect::<Vec<_>>() } fn parse_cube(c: char) -> Cube { match c { '#' => Cube::Active, '.' => Cube::Inactive, _ => panic!("Invalid cube!"), } } fn run(&self, iter: usize, enable_4d: bool) -> HyperSpace<Cube> { let expansion = 2 * iter; let size = ( 1 + if enable_4d { expansion } else { 0 }, 1 + expansion, self.input.len() + expansion, self.input[0].len() + expansion, ); let mut state = HyperSpace::new(Cube::Inactive, size); // initialize middle plane for i in 0..self.input.len() { for j in 0..self.input[0].len() { let coord = (size.0 / 2, size.1 / 2, iter + i, iter + j); state.set(coord, self.input[i][j]); } } // run the simulation for _ in 0..iter { let active = &Self::count_active_adjacent(&state); Self::update(&mut state, active); } state } fn update(state: &mut HyperSpace<Cube>, active: &HyperSpace<usize>) { let to_update = state .coords .iter() .filter(|&coord| Self::should_update_cube(state.get(*coord), active.get(*coord))) .cloned() .collect::<Vec<_>>(); to_update .into_iter() .for_each(|coord| match state.get(coord) { Cube::Active => state.set(coord, Cube::Inactive), Cube::Inactive => state.set(coord, Cube::Active), }); } fn should_update_cube(cube: Cube, active: usize) -> bool { match (cube, active) { (Cube::Active, 2) => false, (Cube::Active, 3) => false, (Cube::Active, _) => true, (Cube::Inactive, 3) => true, (Cube::Inactive, _) => false, } } fn count_active_adjacent(state: &HyperSpace<Cube>) -> HyperSpace<usize> { let mut active = HyperSpace::new(0, state.size); for &coord in state.coords.iter() { active.set(coord, Self::count_active_adjacent_cube(state, coord)); } active } fn count_active_adjacent_cube(state: &HyperSpace<Cube>, (t, k, i, j): Coord) -> usize { let range_t = t.saturating_sub(1)..min(t + 2, state.size.0); let range_k = k.saturating_sub(1)..min(k + 2, state.size.1); let range_i = i.saturating_sub(1)..min(i + 2, state.size.2); let range_j = j.saturating_sub(1)..min(j + 2, state.size.3); let mut res = 0; for tt in range_t { for kk in range_k.clone() { for ii in range_i.clone() { for jj in range_j.clone() { if state.get((tt, kk, ii, jj)) == Cube::Active { res += 1; } } } } } if state.get((t, k, i, j)) == Cube::Active { res -= 1; } res } fn count_active(state: &HyperSpace<Cube>) -> usize { state .coords .iter() .filter(|&coord| state.get(*coord) == Cube::Active) .count() } } impl Day for Day17 { fn first_challenge(&self) -> String { let state = &self.run(6, false); Self::count_active(state).to_string() } fn second_challenge(&self) -> String { let state = &self.run(6, true); Self::count_active(state).to_string() } } #[derive(Debug, PartialEq, Copy, Clone)] enum Cube { Inactive, Active, } type Coord = (usize, usize, usize, usize); type Size = (usize, usize, usize, usize); type Plane<T> = Vec<Vec<T>>; type Space<T> = Vec<Plane<T>>; struct HyperSpace<T> { space: Vec<Space<T>>, coords: Vec<Coord>, size: Size, } impl<T> HyperSpace<T> where T: Clone + Copy, { fn new(value: T, (wsize, zsize, xsize, ysize): Size) -> HyperSpace<T> { let space = vec![vec![vec![vec![value; ysize]; xsize]; zsize]; wsize]; let coords = (0..wsize) .cartesian_product(0..zsize) .cartesian_product(0..xsize) .cartesian_product(0..ysize) .map(|(((t, k), i), j)| (t, k, i, j)) .collect(); let size = (wsize, zsize, xsize, ysize); Self { space, coords, size, } } fn get(&self, (t, k, i, j): Coord) -> T { self.space[t][k][i][j] } fn set(&mut self, (t, k, i, j): Coord, value: T) { self.space[t][k][i][j] = value } } /* tests */ #[cfg(test)] mod tests { use super::*; #[test] fn test_first_challenge() { let input = ".#. ..# ###"; let day = Day17::load(input); assert_eq!(day.first_challenge(), "112"); } #[test] #[ignore] fn test_second_challenge() { let input = ".#. ..# ###"; let day = Day17::load(input); assert_eq!(day.second_challenge(), "848"); } }
true
5a58baad17a6d522a2e619f72d14fdcebb1c12fb
Rust
justahero/ok-sudoku
/src/strategy/algorithms/naked_subset.rs
UTF-8
7,393
3.109375
3
[]
no_license
use itertools::Itertools; use crate::{ strategy::{step::Step, Strategy}, Candidates, Cell, Sudoku, }; #[derive(Debug)] pub struct NakedSubset { count: usize, } impl NakedSubset { /// Create a new Naked Subset for pairs of 2 pub fn pair() -> Self { Self { count: 2 } } /// Create a new Naked Subset for triples pub fn triple() -> Self { Self { count: 3 } } /// Create a new Naked Subset for quadruplets pub fn quadruple() -> Self { Self { count: 4 } } fn find_tuple(&self, cells: &Vec<&Cell>) -> Option<Step> { // get all neighbors, cells that have only candidates let neighbors = cells .iter() .filter(|&cell| cell.is_empty()) .collect::<Vec<_>>(); // for all available neighbors check if there is a naked subset if neighbors.len() > self.count { for group in neighbors.iter().permutations(self.count) { let subset = group .iter() .fold(Candidates::empty(), |mut candidates, &&cell| { candidates |= cell.candidates(); candidates }); // In case the subset contains the same number of candidates if subset.count() == self.count { let mut step = Step::new(); for cell in &group { step.lock_candidate(cell.index(), cell.candidates()); } // for all cells outside the naked subset eliminate these candidates neighbors .iter() .filter(|index| !group.contains(index)) .for_each(|&&cell| { for c in subset.iter() { if cell.candidates().get(c) { step.eliminate_candidate(cell.index(), c); } } }); if !step.eliminated_candidates().is_empty() { return Some(step); } } } } None } } impl Strategy for NakedSubset { fn find(&self, sudoku: &Sudoku) -> Option<Step> { for row in sudoku.get_rows() { if let Some(step) = self.find_tuple(&row) { return Some(step); } } for col in sudoku.get_cols() { if let Some(step) = self.find_tuple(&col) { return Some(step); } } for block in sudoku.get_blocks() { if let Some(step) = self.find_tuple(&block) { return Some(step); } } None } fn name(&self) -> String { format!("Naked Subset ({})", self.count) } } #[cfg(test)] mod tests { use std::convert::TryFrom; use crate::{Candidates, Sudoku, strategy::Strategy}; use super::NakedSubset; /// Example of naked pair: http://hodoku.sourceforge.net/en/show_example.php?file=n201&tech=Naked+Pair #[test] fn find_naked_pair() { let sudoku = r" 7..849.3. 928135..6 4..267.89 642783951 397451628 8156923.. 2.4516.93 1....8.6. 5....4.1. "; let sudoku = Sudoku::try_from(sudoku).unwrap(); let strategy = NakedSubset::pair(); let step = strategy.find(&sudoku).unwrap(); println!("SUDOKU: {}", sudoku); assert_eq!(&vec![(64, 3)], step.eliminated_candidates()); assert_eq!( &vec![ (65, Candidates::new(&[3, 9])), (66, Candidates::new(&[3, 9])), ], step.locked_candidates(), ); } /// Example: https://github.com/dimitri/sudoku/blob/master/top95.txt #[test] fn find_naked_subset_triple_with_issue() { let sudoku = r" 4.....8.5 .3....... ...7..... .2.....6. ....8.4.. ....1.... ...6.3.7. 5..2..... 1.4...... "; let sudoku = Sudoku::try_from(sudoku).unwrap(); let strategy = NakedSubset::triple(); let step = strategy.find(&sudoku).unwrap(); assert_eq!( &vec![(58, 9), (60, 2), (60, 9), (62, 2), (62, 8), (62, 9)], step.eliminated_candidates(), ); } /// Example: http://hodoku.sourceforge.net/en/show_example.php?file=n301&tech=Naked+Triple #[test] fn find_naked_triple() { let sudoku = r" ...29438. ...17864. 48.3561.. ..48375.1 ...4157.. 5..629834 953782416 126543978 .4.961253 "; let sudoku = Sudoku::try_from(sudoku).unwrap(); let strategy = NakedSubset::triple(); let step = strategy.find(&sudoku).unwrap(); assert_eq!(&vec![(1, 6)], step.eliminated_candidates(),); assert_eq!( &vec![ (10, Candidates::new(&[3, 9])), (28, Candidates::new(&[6, 9])), (37, Candidates::new(&[3, 6, 9])), ], step.locked_candidates(), ); } /// Example: http://hodoku.sourceforge.net/en/show_example.php?file=n402&tech=Naked+Quadruple #[test] fn find_naked_quadruple() { let sudoku = r" 532786... 978241.6. ..1953287 .254..67. ..3617.52 7..5..... ...1..... ...8.51.6 ...3...98 "; let sudoku = Sudoku::try_from(sudoku).unwrap(); let strategy = NakedSubset::quadruple(); let step = strategy.find(&sudoku).unwrap(); assert_eq!( &vec![ (54, 4), (54, 6), (55, 4), (55, 6), (55, 9), (63, 4), (72, 4), (72, 6), (73, 4), (73, 6) ], step.eliminated_candidates(), ); assert_eq!( &vec![ (56, Candidates::new(&[4, 6, 7, 9])), (64, Candidates::new(&[4, 9])), (65, Candidates::new(&[4, 7, 9])), (74, Candidates::new(&[4, 6, 7])), ], step.locked_candidates(), ); } #[test] fn fix_naked_subset_pair() { let sudoku = r" ..81..... 5.392.... ...78.6.. 145698237 .3.247.1. 7823..964 3.4869.5. 8..5..4.9 .5.4..386 "; let mut sudoku = Sudoku::try_from(sudoku).unwrap(); sudoku.get_mut(23).unset_candidate(4); sudoku.get_mut(26).unset_candidate(1); sudoku.get_mut(26).unset_candidate(2); sudoku.get_mut(5).unset_candidate(3); sudoku.get_mut(5).unset_candidate(5); println!("BEFORE: {}", sudoku); let strategy = NakedSubset::pair(); let step = strategy.find(&sudoku); dbg!(step); } }
true
46f772edd72f465f89e4c250419aca79a8ee0e78
Rust
acmcarther/next_space_coop
/cargo/vendor/ncollide_geometry-0.2.0/query/point_internal/point_support_map.rs
UTF-8
3,231
2.65625
3
[]
no_license
use na::{self, Translation, Rotate, Transform}; use query::algorithms::gjk; use query::algorithms::minkowski_sampling; use query::algorithms::simplex::Simplex; use query::algorithms::johnson_simplex::JohnsonSimplex; use query::{PointQuery, PointProjection}; use shape::{SupportMap, Cylinder, Cone, Capsule, ConvexHull}; use math::{Point, Vector}; /// Projects a point on a shape using the GJK algorithm. pub fn support_map_point_projection<P, M, S, G>(m: &M, shape: &G, simplex: &mut S, point: &P, solid: bool) -> PointProjection<P> where P: Point, M: Translation<P::Vect>, S: Simplex<P>, G: SupportMap<P, M> { let m = na::append_translation(m, &-*point.as_vector()); let support_point = shape.support_point(&m, &-*point.as_vector()); simplex.reset(support_point); match gjk::project_origin(&m, shape, simplex) { Some(p) => { PointProjection::new(false, p + *point.as_vector()) }, None => { let proj; // Fallback algorithm. // FIXME: we use the Minkowski Sampling for now, but this should be changed for the EPA // in the future. if !solid { match minkowski_sampling::project_origin(&m, shape, simplex) { Some(p) => proj = p + *point.as_vector(), None => proj = point.clone() } } else { proj = point.clone() } PointProjection::new(true, proj) } } } impl<P, M> PointQuery<P, M> for Cylinder<<P::Vect as Vector>::Scalar> where P: Point, M: Transform<P> + Rotate<P::Vect> + Translation<P::Vect> { #[inline] fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> { support_map_point_projection(m, self, &mut JohnsonSimplex::<P>::new_w_tls(), point, solid) } } impl<P, M> PointQuery<P, M> for Cone<<P::Vect as Vector>::Scalar> where P: Point, M: Transform<P> + Rotate<P::Vect> + Translation<P::Vect> { #[inline] fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> { support_map_point_projection(m, self, &mut JohnsonSimplex::<P>::new_w_tls(), point, solid) } } impl<P, M> PointQuery<P, M> for Capsule<<P::Vect as Vector>::Scalar> where P: Point, M: Transform<P> + Rotate<P::Vect> + Translation<P::Vect> { #[inline] fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> { support_map_point_projection(m, self, &mut JohnsonSimplex::<P>::new_w_tls(), point, solid) } } impl<P, M> PointQuery<P, M> for ConvexHull<P> where P: Point, M: Transform<P> + Rotate<P::Vect> + Translation<P::Vect> { #[inline] fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> { support_map_point_projection(m, self, &mut JohnsonSimplex::<P>::new_w_tls(), point, solid) } }
true
74f79f13153c145b5c8cd27a888bf6cff0e2581c
Rust
FL33TW00D/kiddo
/src/kiddo.rs
UTF-8
31,201
3.3125
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
use std::collections::BinaryHeap; use num_traits::{Float, One, Zero}; #[cfg(feature = "serialize")] use crate::custom_serde::*; use crate::heap_element::HeapElement; use crate::util; trait Stack<T> where T: Ord, { fn stack_push(&mut self, _: T); fn stack_pop(&mut self) -> Option<T>; } impl<T> Stack<T> for Vec<T> where T: Ord, { #[inline(always)] fn stack_push(&mut self, element: T) { Vec::<T>::push(self, element) } #[inline(always)] fn stack_pop(&mut self) -> Option<T> { Vec::<T>::pop(self) } } impl<T> Stack<T> for BinaryHeap<T> where T: Ord, { #[inline(always)] fn stack_push(&mut self, element: T) { BinaryHeap::<T>::push(self, element) } #[inline(always)] fn stack_pop(&mut self) -> Option<T> { BinaryHeap::<T>::pop(self) } } #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] #[derive(Clone, Debug)] pub struct KdTree<A, T: std::cmp::PartialEq, const K: usize> { size: usize, #[cfg_attr(feature = "serialize", serde(with = "arrays"))] min_bounds: [A; K], #[cfg_attr(feature = "serialize", serde(with = "arrays"))] max_bounds: [A; K], content: Node<A, T, K>, } #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] #[derive(Clone, Debug)] pub enum Node<A, T: std::cmp::PartialEq, const K: usize> { Stem { left: Box<KdTree<A, T, K>>, right: Box<KdTree<A, T, K>>, split_value: A, split_dimension: u8, }, Leaf { #[cfg_attr(feature = "serialize", serde(with = "vec_arrays"))] points: Vec<[A; K]>, bucket: Vec<T>, capacity: usize, }, } #[derive(Debug, PartialEq)] pub enum ErrorKind { NonFiniteCoordinate, ZeroCapacity, Empty, } impl<A: Float + Zero + One, T: std::cmp::PartialEq, const K: usize> KdTree<A, T, K> { /// Creates a new KdTree with default capacity per node of 16 /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn new() -> Self { KdTree::with_capacity(16).unwrap() } /// Creates a new KdTree with a specific capacity per node /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::with_capacity(8)?; /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn with_capacity(capacity: usize) -> Result<Self, ErrorKind> { if capacity == 0 { return Err(ErrorKind::ZeroCapacity); } Ok(KdTree { size: 0, min_bounds: [A::infinity(); K], max_bounds: [A::neg_infinity(); K], content: Node::Leaf { points: Vec::with_capacity(capacity), bucket: Vec::with_capacity(capacity), capacity, }, }) } /// Returns the current number of elements stored in the tree /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[1.1, 2.1, 5.1], 101)?; /// /// assert_eq!(tree.size(), 2); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn size(&self) -> usize { self.size } /// Returns true if the node is a leaf node /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// /// let mut tree_1: KdTree<f64, usize, 3> = KdTree::with_capacity(2)?; /// /// tree_1.add(&[1.0, 2.0, 5.0], 100)?; /// tree_1.add(&[1.1, 2.1, 5.1], 101)?; /// /// assert_eq!(tree_1.is_leaf(), true); /// /// let mut tree_2: KdTree<f64, usize, 3> = KdTree::with_capacity(1)?; /// /// tree_2.add(&[1.0, 2.0, 5.0], 100)?; /// tree_2.add(&[1.1, 2.1, 5.1], 101)?; /// /// assert_eq!(tree_2.is_leaf(), false); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn is_leaf(&self) -> bool { match &self.content { Node::Leaf { .. } => true, Node::Stem { .. } => false, } } /// Queries the tree to find the nearest `num` elements to `point`, using the specified /// distance metric function. /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// use kiddo::distance::squared_euclidean; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[2.0, 3.0, 6.0], 101)?; /// /// let nearest = tree.nearest(&[1.0, 2.0, 5.1], 1, &squared_euclidean)?; /// /// assert_eq!(nearest.len(), 1); /// assert!((nearest[0].0 - 0.01f64).abs() < f64::EPSILON); /// assert_eq!(*nearest[0].1, 100); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn nearest<F>( &self, point: &[A; K], num: usize, distance: &F, ) -> Result<Vec<(A, &T)>, ErrorKind> where F: Fn(&[A; K], &[A; K]) -> A, { self.check_point(point)?; let num = std::cmp::min(num, self.size); if num == 0 { return Ok(vec![]); } let mut pending = BinaryHeap::new(); let mut evaluated = BinaryHeap::<HeapElement<A, &T>>::new(); pending.push(HeapElement { distance: A::zero(), element: self, }); while !pending.is_empty() && (evaluated.len() < num || (-pending.peek().unwrap().distance <= evaluated.peek().unwrap().distance)) { self.nearest_step( point, num, A::infinity(), distance, &mut pending, &mut evaluated, ); } Ok(evaluated .into_sorted_vec() .into_iter() .take(num) .map(Into::into) .collect()) } /// Queries the tree to find the nearest element to `point`, using the specified /// distance metric function. Faster than querying for nearest(point, 1, ...) due /// to not needing to allocate a Vec for the result /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// use kiddo::distance::squared_euclidean; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[2.0, 3.0, 6.0], 101)?; /// /// let nearest = tree.nearest_one(&[1.0, 2.0, 5.1], &squared_euclidean)?; /// /// assert!((nearest.0 - 0.01f64).abs() < f64::EPSILON); /// assert_eq!(*nearest.1, 100); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` // TODO: pending only ever gets to about 7 items max. try doing this // recursively to avoid the alloc/dealloc of the vec pub fn nearest_one<F>(&self, point: &[A; K], distance: &F) -> Result<(A, &T), ErrorKind> where F: Fn(&[A; K], &[A; K]) -> A, { if self.size == 0 { return Err(ErrorKind::Empty); } self.check_point(point)?; let mut pending = Vec::with_capacity(16); let mut best_dist: A = A::infinity(); let mut best_elem: Option<&T> = None; pending.push(HeapElement { distance: A::zero(), element: self, }); while !pending.is_empty() && (best_elem.is_none() || (pending[0].distance > best_dist)) { self.nearest_one_step( point, distance, &mut pending, &mut best_dist, &mut best_elem, ); } Ok((best_dist, best_elem.unwrap())) } fn within_impl<F>( &self, point: &[A; K], radius: A, distance: &F, ) -> Result<BinaryHeap<HeapElement<A, &T>>, ErrorKind> where F: Fn(&[A; K], &[A; K]) -> A, { self.check_point(point)?; let mut pending = BinaryHeap::new(); let mut evaluated = BinaryHeap::<HeapElement<A, &T>>::new(); pending.push(HeapElement { distance: A::zero(), element: self, }); while !pending.is_empty() && (-pending.peek().unwrap().distance <= radius) { self.nearest_step( point, self.size, radius, distance, &mut pending, &mut evaluated, ); } Ok(evaluated) } /// Queries the tree to find all elements within `radius` of `point`, using the specified /// distance metric function. Results are returned sorted nearest-first /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// use kiddo::distance::squared_euclidean; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[2.0, 3.0, 6.0], 101)?; /// tree.add(&[200.0, 300.0, 600.0], 102)?; /// /// let within = tree.within(&[1.0, 2.0, 5.0], 10f64, &squared_euclidean)?; /// /// assert_eq!(within.len(), 2); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn within<F>( &self, point: &[A; K], radius: A, distance: &F, ) -> Result<Vec<(A, &T)>, ErrorKind> where F: Fn(&[A; K], &[A; K]) -> A, { if self.size == 0 { return Ok(vec![]); } self.within_impl(point, radius, distance).map(|evaluated| { evaluated .into_sorted_vec() .into_iter() .map(Into::into) .collect() }) } /// Queries the tree to find all elements within `radius` of `point`, using the specified /// distance metric function. Results are returned in arbitrary order. Faster than within() /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// use kiddo::distance::squared_euclidean; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[2.0, 3.0, 6.0], 101)?; /// tree.add(&[200.0, 300.0, 600.0], 102)?; /// /// let within = tree.within(&[1.0, 2.0, 5.0], 10f64, &squared_euclidean)?; /// /// assert_eq!(within.len(), 2); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn within_unsorted<F>( &self, point: &[A; K], radius: A, distance: &F, ) -> Result<Vec<(A, &T)>, ErrorKind> where F: Fn(&[A; K], &[A; K]) -> A, { if self.size == 0 { return Ok(vec![]); } self.within_impl(point, radius, distance) .map(|evaluated| evaluated.into_vec().into_iter().map(Into::into).collect()) } /// Queries the tree to find the best `n` elements within `radius` of `point`, using the specified /// distance metric function. Results are returned in arbitrary order. 'Best' is determined by /// performing a comparison of the elements using < (ie, std::ord::lt) /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// use kiddo::distance::squared_euclidean; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[2.0, 3.0, 6.0], 1)?; /// tree.add(&[200.0, 300.0, 600.0], 102)?; /// /// let best_n_within = tree.best_n_within(&[1.0, 2.0, 5.0], 10f64, 1, &squared_euclidean)?; /// /// assert_eq!(best_n_within[0], 1); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn best_n_within<F>( &self, point: &[A; K], radius: A, max_qty: usize, distance: &F, ) -> Result<Vec<T>, ErrorKind> where F: Fn(&[A; K], &[A; K]) -> A, T: Copy + Ord, { if self.size == 0 { return Ok(vec![]); } self.check_point(point)?; let mut pending = Vec::with_capacity(max_qty); let mut evaluated = BinaryHeap::<T>::new(); pending.push(HeapElement { distance: A::zero(), element: self, }); while !pending.is_empty() { self.best_n_within_step( point, self.size, max_qty, radius, distance, &mut pending, &mut evaluated, ); } Ok(evaluated.into_vec().into_iter().collect()) } /// Queries the tree to find the best `n` elements within `radius` of `point`, using the specified /// distance metric function. Results are returned in arbitrary order. 'Best' is determined by /// performing a comparison of the elements using < (ie, std::ord::lt). Returns an iterator. /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// use kiddo::distance::squared_euclidean; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[2.0, 3.0, 6.0], 1)?; /// tree.add(&[200.0, 300.0, 600.0], 102)?; /// /// let mut best_n_within_iter = tree.best_n_within_into_iter(&[1.0, 2.0, 5.0], 10f64, 1, &squared_euclidean); /// let first = best_n_within_iter.next().unwrap(); /// /// assert_eq!(first, 1); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn best_n_within_into_iter<F>( &self, point: &[A; K], radius: A, max_qty: usize, distance: &F, ) -> impl Iterator<Item = T> where F: Fn(&[A; K], &[A; K]) -> A, T: Copy + Ord, { // if let Err(err) = self.check_point(point) { // return Err(err); // } // if self.size == 0 { // return std::iter::empty::<T>(); // } let mut pending = Vec::with_capacity(max_qty); let mut evaluated = BinaryHeap::<T>::new(); pending.push(HeapElement { distance: A::zero(), element: self, }); while !pending.is_empty() { self.best_n_within_step( point, self.size, max_qty, radius, distance, &mut pending, &mut evaluated, ); } evaluated.into_iter() } fn best_n_within_step<'b, F>( &self, point: &[A; K], _num: usize, max_qty: usize, max_dist: A, distance: &F, pending: &mut Vec<HeapElement<A, &'b Self>>, evaluated: &mut BinaryHeap<T>, ) where F: Fn(&[A; K], &[A; K]) -> A, T: Copy + Ord, { let curr = &mut &*pending.pop().unwrap().element; <KdTree<A, T, K>>::populate_pending(point, max_dist, distance, pending, curr); match &curr.content { Node::Leaf { points, bucket, .. } => { let points = points.iter(); let bucket = bucket.iter(); let iter = points.zip(bucket).map(|(p, d)| HeapElement { distance: distance(point, p), element: d, }); for element in iter { if element <= max_dist { if evaluated.len() < max_qty { evaluated.push(*element.element); } else { let mut top = evaluated.peek_mut().unwrap(); if element.element < &top { *top = *element.element; } } } } } Node::Stem { .. } => unreachable!(), } } fn nearest_step<'b, F>( &self, point: &[A; K], num: usize, max_dist: A, distance: &F, pending: &mut BinaryHeap<HeapElement<A, &'b Self>>, evaluated: &mut BinaryHeap<HeapElement<A, &'b T>>, ) where F: Fn(&[A; K], &[A; K]) -> A, { let curr = &mut &*pending.pop().unwrap().element; <KdTree<A, T, K>>::populate_pending(point, max_dist, distance, pending, curr); match &curr.content { Node::Leaf { points, bucket, .. } => { let points = points.iter(); let bucket = bucket.iter(); let iter = points.zip(bucket).map(|(p, d)| HeapElement { distance: distance(point, p), element: d, }); for element in iter { if element <= max_dist { if evaluated.len() < num { evaluated.push(element); } else { let mut top = evaluated.peek_mut().unwrap(); if element < *top { *top = element; } } } } } Node::Stem { .. } => unreachable!(), } } fn nearest_one_step<'b, F>( &self, point: &[A; K], distance: &F, pending: &mut Vec<HeapElement<A, &'b Self>>, best_dist: &mut A, best_elem: &mut Option<&'b T>, ) where F: Fn(&[A; K], &[A; K]) -> A, { let curr = &mut &*pending.pop().unwrap().element; let evaluated_dist = *best_dist; <KdTree<A, T, K>>::populate_pending(point, evaluated_dist, distance, pending, curr); match &curr.content { Node::Leaf { points, bucket, .. } => { let points = points.iter(); let bucket = bucket.iter(); let iter = points.zip(bucket).map(|(p, d)| HeapElement { distance: distance(point, p), element: d, }); for element in iter { if best_elem.is_none() || element < *best_dist { *best_elem = Some(element.element); *best_dist = element.distance; } } } Node::Stem { .. } => unreachable!(), } } fn populate_pending<'a, F>( point: &[A; K], max_dist: A, distance: &F, pending: &mut impl Stack<HeapElement<A, &'a Self>>, curr: &mut &'a Self, ) where F: Fn(&[A; K], &[A; K]) -> A, { while let Node::Stem { left, right, .. } = &curr.content { let candidate; if curr.belongs_in_left(point) { candidate = right; *curr = left; } else { candidate = left; *curr = right; }; let candidate_to_space = util::distance_to_space( point, &candidate.min_bounds, &candidate.max_bounds, distance, ); if candidate_to_space <= max_dist { pending.stack_push(HeapElement { distance: candidate_to_space * -A::one(), element: &**candidate, }); } } } /// Returns an iterator over all elements in the tree, sorted nearest-first to the query point. /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// use kiddo::distance::squared_euclidean; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[2.0, 3.0, 6.0], 101)?; /// /// let mut nearest_iter = tree.iter_nearest(&[1.0, 2.0, 5.1], &squared_euclidean)?; /// /// let nearest_first = nearest_iter.next().unwrap(); /// /// assert!((nearest_first.0 - 0.01f64).abs() < f64::EPSILON); /// assert_eq!(*nearest_first.1, 100); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn iter_nearest<'a, 'b, F>( &'b self, point: &'a [A; K], distance: &'a F, ) -> Result<NearestIter<'a, 'b, A, T, F, K>, ErrorKind> where F: Fn(&[A; K], &[A; K]) -> A, { self.check_point(point)?; let mut pending = BinaryHeap::new(); let evaluated = BinaryHeap::<HeapElement<A, &T>>::new(); pending.push(HeapElement { distance: A::zero(), element: self, }); Ok(NearestIter { point, pending, evaluated, distance, }) } /// Add an element to the tree. The first argument specifies the location in kd space /// at which the element is located. The second argument is the data associated with /// that point in space. /// /// # Examples /// /// ```rust /// use kiddo::KdTree; /// /// let mut tree: KdTree<f64, usize, 3> = KdTree::new(); /// /// tree.add(&[1.0, 2.0, 5.0], 100)?; /// tree.add(&[1.1, 2.1, 5.1], 101)?; /// /// assert_eq!(tree.size(), 2); /// # Ok::<(), kiddo::ErrorKind>(()) /// ``` pub fn add(&mut self, point: &[A; K], data: T) -> Result<(), ErrorKind> { self.check_point(point)?; self.add_unchecked(point, data) } fn add_unchecked(&mut self, point: &[A; K], data: T) -> Result<(), ErrorKind> { let res = match &mut self.content { Node::Leaf { .. } => { self.add_to_bucket(point, data); return Ok(()); } Node::Stem { ref mut left, ref mut right, split_dimension, split_value, } => { if point[*split_dimension as usize] < *split_value { // belongs_in_left left.add_unchecked(point, data) } else { right.add_unchecked(point, data) } } }; self.extend(point); self.size += 1; res } fn add_to_bucket(&mut self, point: &[A; K], data: T) { self.extend(point); let cap; match &mut self.content { Node::Leaf { ref mut points, ref mut bucket, capacity, } => { points.push(*point); bucket.push(data); cap = *capacity; } Node::Stem { .. } => unreachable!(), } self.size += 1; if self.size > cap { self.split(); } } pub fn remove(&mut self, point: &[A; K], data: &T) -> Result<usize, ErrorKind> { let mut removed = 0; self.check_point(point)?; match &mut self.content { Node::Leaf { ref mut points, ref mut bucket, .. } => { while let Some(p_index) = points.iter().position(|x| x == point) { if &bucket[p_index] == data { points.remove(p_index); bucket.remove(p_index); removed += 1; self.size -= 1; } } } Node::Stem { ref mut left, ref mut right, .. } => { let right_removed = right.remove(point, data)?; if right_removed > 0 { self.size -= right_removed; removed += right_removed; } let left_removed = left.remove(point, data)?; if left_removed > 0 { self.size -= left_removed; removed += left_removed; } } } Ok(removed) } fn split(&mut self) { match &mut self.content { Node::Leaf { ref mut bucket, ref mut points, capacity, .. } => { let mut split_dimension: Option<usize> = None; let mut max = A::zero(); for dim in 0..K { let diff = self.max_bounds[dim] - self.min_bounds[dim]; if !diff.is_nan() && diff > max { max = diff; split_dimension = Some(dim); } } if let Some(split_dimension) = split_dimension { let min = self.min_bounds[split_dimension]; let max = self.max_bounds[split_dimension]; let split_value = min + (max - min) / A::from(2.0).unwrap(); let mut left = Box::new(KdTree::with_capacity(*capacity).unwrap()); let mut right = Box::new(KdTree::with_capacity(*capacity).unwrap()); while !points.is_empty() { let point = points.swap_remove(0); let data = bucket.swap_remove(0); if point[split_dimension] < split_value { // belongs_in_left left.add_to_bucket(&point, data); } else { right.add_to_bucket(&point, data); } } self.content = Node::Stem { left, right, split_value, split_dimension: split_dimension as u8, } } } Node::Stem { .. } => unreachable!(), } } fn belongs_in_left(&self, point: &[A; K]) -> bool { match &self.content { Node::Stem { ref split_dimension, ref split_value, .. } => point[*split_dimension as usize] < *split_value, Node::Leaf { .. } => unreachable!(), } } fn extend(&mut self, point: &[A; K]) { let min = self.min_bounds.iter_mut(); let max = self.max_bounds.iter_mut(); for ((l, h), v) in min.zip(max).zip(point.iter()) { if v < l { *l = *v } if v > h { *h = *v } } } fn check_point(&self, point: &[A; K]) -> Result<(), ErrorKind> { if point.iter().all(|n| n.is_finite()) { Ok(()) } else { Err(ErrorKind::NonFiniteCoordinate) } } } pub struct NearestIter< 'a, 'b, A: 'a + 'b + Float, T: 'b + PartialEq, F: 'a + Fn(&[A; K], &[A; K]) -> A, const K: usize, > { point: &'a [A; K], pending: BinaryHeap<HeapElement<A, &'b KdTree<A, T, K>>>, evaluated: BinaryHeap<HeapElement<A, &'b T>>, distance: &'a F, } impl<'a, 'b, A: Float + Zero + One, T: 'b, F: 'a, const K: usize> Iterator for NearestIter<'a, 'b, A, T, F, K> where F: Fn(&[A; K], &[A; K]) -> A, T: PartialEq, { type Item = (A, &'b T); fn next(&mut self) -> Option<(A, &'b T)> { use util::distance_to_space; let distance = self.distance; let point = self.point; while !self.pending.is_empty() && (self.evaluated.peek().map_or(A::infinity(), |x| -x.distance) >= -self.pending.peek().unwrap().distance) { let mut curr = &*self.pending.pop().unwrap().element; while let Node::Stem { left, right, .. } = &curr.content { let candidate; if curr.belongs_in_left(point) { candidate = right; curr = left; } else { candidate = left; curr = right; }; self.pending.push(HeapElement { distance: -distance_to_space( point, &candidate.min_bounds, &candidate.max_bounds, distance, ), element: &**candidate, }); } match &curr.content { Node::Leaf { points, bucket, .. } => { let points = points.iter(); let bucket = bucket.iter(); self.evaluated .extend(points.zip(bucket).map(|(p, d)| HeapElement { distance: -distance(point, p), element: d, })); } Node::Stem { .. } => unreachable!(), } } self.evaluated.pop().map(|x| (-x.distance, x.element)) } } impl std::error::Error for ErrorKind { fn description(&self) -> &str { match *self { ErrorKind::NonFiniteCoordinate => "non-finite coordinate", ErrorKind::ZeroCapacity => "zero capacity", ErrorKind::Empty => "invalid operation on empty tree", } } } impl std::fmt::Display for ErrorKind { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "KdTree error: {}", self) } } #[cfg(test)] mod tests { extern crate rand; use super::KdTree; use super::Node; fn random_point() -> ([f64; 2], i32) { rand::random::<([f64; 2], i32)>() } #[test] fn it_has_default_capacity() { let tree: KdTree<f64, i32, 2> = KdTree::new(); match &tree.content { Node::Leaf { capacity, .. } => { assert_eq!(*capacity, 2_usize.pow(4)); } Node::Stem { .. } => unreachable!(), } } #[test] fn it_can_be_cloned() { let mut tree: KdTree<f64, i32, 2> = KdTree::new(); let (pos, data) = random_point(); tree.add(&pos, data).unwrap(); let mut cloned_tree = tree.clone(); cloned_tree.add(&pos, data).unwrap(); assert_eq!(tree.size(), 1); assert_eq!(cloned_tree.size(), 2); } #[test] fn it_holds_on_to_its_capacity_before_splitting() { let mut tree: KdTree<f64, i32, 2> = KdTree::new(); let capacity = 2_usize.pow(4); for _ in 0..capacity { let (pos, data) = random_point(); tree.add(&pos, data).unwrap(); } assert_eq!(tree.size, capacity); assert_eq!(tree.size(), capacity); assert!(tree.is_leaf()); { let (pos, data) = random_point(); tree.add(&pos, data).unwrap(); } assert_eq!(tree.size, capacity + 1); assert_eq!(tree.size(), capacity + 1); assert!(!tree.is_leaf()); } }
true
c04976f466d020514f4b0ddd061bb5e30c0bcc7d
Rust
Swatinem/sentry-contrib-native
/src/before_send.rs
UTF-8
4,128
3
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Implementation details for [`Options::set_before_send`]. use crate::{ffi, Value}; #[cfg(doc)] use crate::{Event, Options}; use once_cell::sync::OnceCell; #[cfg(doc)] use std::process::abort; use std::{mem::ManuallyDrop, os::raw::c_void, sync::Mutex}; /// How global [`BeforeSend`] data is stored. pub type Data = Box<Box<dyn BeforeSend>>; /// Store [`Options::set_before_send`] data to properly deallocate later. pub static BEFORE_SEND: OnceCell<Mutex<Option<Data>>> = OnceCell::new(); /// Trait to help pass data to [`Options::set_before_send`]. /// /// # Examples /// ``` /// # use sentry_contrib_native::{BeforeSend, Options, Value}; /// # use std::sync::atomic::{AtomicUsize, Ordering}; /// # fn main() -> anyhow::Result<()> { /// struct Filter { /// filtered: AtomicUsize, /// }; /// /// impl BeforeSend for Filter { /// fn before_send(&self, value: Value) -> Value { /// self.filtered.fetch_add(1, Ordering::SeqCst); /// // do something with the value and then return it /// value /// } /// } /// /// let mut options = Options::new(); /// options.set_before_send(Filter { /// filtered: AtomicUsize::new(0), /// }); /// let _shutdown = options.init()?; /// # Ok(()) } /// ``` pub trait BeforeSend: 'static + Send + Sync { /// Before send callback. /// /// # Notes /// The caller of this function will catch any unwinding panics and /// [`abort`] if any occured. /// /// # Examples /// ``` /// # use sentry_contrib_native::{BeforeSend, Value}; /// # use std::sync::atomic::{AtomicUsize, Ordering}; /// struct Filter { /// filtered: AtomicUsize, /// }; /// /// impl BeforeSend for Filter { /// fn before_send(&self, value: Value) -> Value { /// self.filtered.fetch_add(1, Ordering::SeqCst); /// // do something with the value and then return it /// value /// } /// } /// ``` fn before_send(&self, value: Value) -> Value; } impl<T: Fn(Value) -> Value + 'static + Send + Sync> BeforeSend for T { fn before_send(&self, value: Value) -> Value { self(value) } } /// Function to pass to [`sys::options_set_before_send`], which in turn calls /// the user defined one. /// /// This function will catch any unwinding panics and [`abort`] if any occured. pub extern "C" fn before_send( event: sys::Value, _hint: *mut c_void, closure: *mut c_void, ) -> sys::Value { let before_send = closure.cast::<Box<dyn BeforeSend>>(); let before_send = ManuallyDrop::new(unsafe { Box::from_raw(before_send) }); ffi::catch(|| { before_send .before_send(unsafe { Value::from_raw(event) }) .into_raw() }) } #[cfg(test)] #[rusty_fork::test_fork(timeout_ms = 60000)] fn before_send_test() -> anyhow::Result<()> { use crate::{Event, Options, Value}; use std::{ cell::RefCell, sync::atomic::{AtomicUsize, Ordering}, }; thread_local! { static COUNTER: RefCell<usize> = RefCell::new(0); } struct Filter { counter: AtomicUsize, } impl BeforeSend for Filter { fn before_send(&self, value: Value) -> Value { self.counter.fetch_add(1, Ordering::SeqCst); value } } impl Drop for Filter { fn drop(&mut self) { COUNTER.with(|counter| *counter.borrow_mut() = *self.counter.get_mut()) } } let mut options = Options::new(); options.set_before_send(Filter { counter: AtomicUsize::new(0), }); let shutdown = options.init()?; Event::new().capture(); Event::new().capture(); Event::new().capture(); shutdown.shutdown(); COUNTER.with(|counter| assert_eq!(3, *counter.borrow())); Ok(()) } #[cfg(test)] #[rusty_fork::test_fork(timeout_ms = 60000)] #[should_panic] fn catch_panic() -> anyhow::Result<()> { use crate::{Event, Options}; let mut options = Options::new(); options.set_before_send(|_| panic!("this is a test")); let _shutdown = options.init()?; Event::new().capture(); Ok(()) }
true
e4dd1b3fbe455949778968b99628ab6597965960
Rust
anthony-c-martin/aoc2017
/src/challenges/challenge_8.rs
UTF-8
3,726
3.59375
4
[]
no_license
use std::collections::HashMap; use std::cmp; pub fn execute(input: &str) { let (max_at_end, max_during_ops) = challenge_a(input); println!("Challenge 8a: {}", max_at_end); println!("Challenge 8b: {}", max_during_ops); } fn challenge_a(input: &str) -> (i32, i32) { let registers = &mut HashMap::new(); let instructions: Vec<Instruction> = input.lines().map(|line| get_instruction(line, registers).unwrap()).collect(); let mut max_during_ops = 0; for instruction in instructions { let condition; { let cmp_register = registers.get(&instruction.comparison_register).unwrap(); condition = match instruction.comparison { Comparison::Equals(val) => cmp_register.value == val, Comparison::NotEquals(val) => cmp_register.value != val, Comparison::LessThan(val) => cmp_register.value < val, Comparison::GreaterThan(val) => cmp_register.value > val, Comparison::LessThanOrEquals(val) => cmp_register.value <= val, Comparison::GreaterThanOrEquals(val) => cmp_register.value >= val, }; } if condition { let register = registers.get_mut(&instruction.register).unwrap(); register.value += instruction.increment; max_during_ops = cmp::max(max_during_ops, register.value); } } let max_at_end = registers.iter() .max_by_key(|&(_, reg)| reg.value) .map(|(_, reg)| reg.value) .unwrap(); (max_at_end, max_during_ops) } fn get_instruction(input: &str, registers: &mut HashMap<String, Register>) -> Result<Instruction, &'static str> { let tokens: Vec<&str> = input.split_whitespace().collect(); if tokens.len() != 7 { return Err("Unexpected instruction"); } let register = tokens[0].to_string(); if !registers.contains_key(&register) { registers.insert(register.clone(), Register { name: tokens[0].to_string(), value: 0 }); } let multiplier = match tokens[1] { "inc" => 1, "dec" => -1, _ => return Err("Unexpected token[1]"), }; let increment = match tokens[2].parse::<i32>() { Ok(val) => multiplier * val, _ => return Err("Unexpected token[2]"), }; match tokens[3] { "if" => { ; }, _ => return Err("Unexpected token[3]"), } let comparison_register = tokens[4].to_string(); if !registers.contains_key(&comparison_register) { registers.insert(comparison_register.clone(), Register { name: tokens[4].to_string(), value: 0 }); } let cmp_val = match tokens[6].parse::<i32>() { Ok(val) => val, _ => return Err("Unexpected token[6]"), }; let comparison = match tokens[5] { "==" => Comparison::Equals(cmp_val), "!=" => Comparison::NotEquals(cmp_val), "<" => Comparison::LessThan(cmp_val), ">" => Comparison::GreaterThan(cmp_val), "<=" => Comparison::LessThanOrEquals(cmp_val), ">=" => Comparison::GreaterThanOrEquals(cmp_val), _ => return Err("Unexpected token[5]"), }; Ok(Instruction { register, increment, comparison, comparison_register, }) } #[derive(Debug)] struct Instruction { register: String, increment: i32, comparison: Comparison, comparison_register: String, } #[derive(Debug)] struct Register { name: String, value: i32, } #[derive(Debug)] enum Comparison { Equals(i32), NotEquals(i32), LessThan(i32), GreaterThan(i32), LessThanOrEquals(i32), GreaterThanOrEquals(i32), }
true
0131a78b967b97fb80896b45d1a05fa5de5d7c14
Rust
desdulianto/exercism-rust
/nth-prime/src/lib.rs
UTF-8
234
3.3125
3
[]
no_license
fn is_prime(n: u32) -> bool { (2..=((n as f64).sqrt().floor() as u32)).all(|i| n % i != 0) } pub fn nth(n: u32) -> u32 { match (2..).filter(|x| is_prime(*x)).nth(n as usize) { Some(x) => x, None => 0, } }
true
f6cf1800048e0b2dd124637273ae7729c1f5deaa
Rust
SaadAhmed-96/Rust-Programmes
/Struct, Methods, Associated Functions/returnable_struct.rs
UTF-8
438
3.515625
4
[]
no_license
#[derive(Debug)] struct Book { name:String, author: String, price: u16, availability: bool, } fn main() { let book_1 = build (let name:String::from("Book A"),let author:String::from("Author A")); println!("{:#?}",book_1); fn build (name:String,author:String) -> Book { Book { name: name, author:author, price:500, availability: true, } } }
true
52f14c526c935da4942709837e0f87550595a68d
Rust
oxalica/nil
/crates/ide/src/ide/highlight_related.rs
UTF-8
6,878
2.8125
3
[ "Apache-2.0", "MIT" ]
permissive
use crate::def::{AstPtr, ResolveResult}; use crate::{DefDatabase, FilePos}; use syntax::ast::{self, AstNode}; use syntax::{best_token_at_offset, TextRange, T}; /// The max distance between returned positions and the original one. Spans too far away are not /// considered "related", to prevent spamming MBs of data to the client. This can happen when /// hovering a "with" attribute in `all-packages.nix`. const MAX_DIST: usize = 1000; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct HlRelated { pub range: TextRange, pub is_definition: bool, } pub(crate) fn highlight_related(db: &dyn DefDatabase, fpos: FilePos) -> Option<Vec<HlRelated>> { let parse = db.parse(fpos.file_id); let source_map = db.source_map(fpos.file_id); let tok = best_token_at_offset(&parse.syntax_node(), fpos.pos)?; let dist_filter = |hlr: &HlRelated| { usize::from(hlr.range.start()).abs_diff(fpos.pos.into()) < MAX_DIST || usize::from(hlr.range.end()).abs_diff(fpos.pos.into()) < MAX_DIST }; // For `with` token, highlight itself and all Attr references. if tok.kind() == T![with] { let with_node = ast::With::cast(tok.parent()?)?; let with_expr = source_map.expr_for_node(AstPtr::new(with_node.syntax()))?; let nameref = db.name_reference(fpos.file_id); let ret = itertools::chain( std::iter::once(HlRelated { range: tok.text_range(), is_definition: true, }), nameref .with_references(with_expr) .unwrap_or(&[]) .iter() .flat_map(|&e| { Some(HlRelated { range: source_map.node_for_expr(e)?.text_range(), is_definition: false, }) }), ) .filter(dist_filter) .collect(); return Some(ret); } // Resolve the definition `Name` for `Attr` and `Ref`. // N.B. We prefer Expr than Name, mainly for highlighting the outer definition of // `inherit`ed Attrs. This is covered by `tests::inherit`. let name = if let Some((ref_node, ref_expr)) = tok.parent().and_then(|ref_node| { let ref_expr = source_map.expr_for_node(AstPtr::new(&ref_node))?; Some((ref_node, ref_expr)) }) { match db.name_resolution(fpos.file_id).get(ref_expr)? { ResolveResult::Definition(name) => *name, ResolveResult::Builtin(_) => return None, // We highlight all effective `with` as definitions and // all other Attr references of the innermost `with`. ResolveResult::WithExprs(with_exprs) => { return Some( with_exprs .iter() .filter_map(|&e| { let ptr = source_map.node_for_expr(e)?; let with_node = ast::With::cast(ptr.to_node(&parse.syntax_node()))?; Some(HlRelated { range: with_node.with_token()?.text_range(), is_definition: true, }) }) // Also include the current token. .chain(Some(HlRelated { range: ref_node.text_range(), is_definition: false, })) .collect(), ); } } } else if let Some(attr_node) = tok.parent().and_then(ast::Attr::cast) { let attr_ptr = AstPtr::new(attr_node.syntax()); source_map.name_for_node(attr_ptr)? } else { return None; }; let ret = itertools::chain( // Definitions. source_map.nodes_for_name(name).map(|ptr| HlRelated { range: ptr.text_range(), is_definition: true, }), // References. db.name_reference(fpos.file_id) .name_references(name) .into_iter() .flatten() .filter_map(|&e| { Some(HlRelated { range: source_map.node_for_expr(e)?.text_range(), is_definition: false, }) }), ) .filter(dist_filter) .collect(); Some(ret) } #[cfg(test)] mod tests { use crate::tests::TestDB; use crate::SourceDatabase; use expect_test::{expect, Expect}; #[track_caller] fn check(fixture: &str, expect: Expect) { let (db, f) = TestDB::from_fixture(fixture).unwrap(); assert_eq!(f.markers().len(), 1); let mut hls = super::highlight_related(&db, f[0]).unwrap_or_default(); hls.sort_by_key(|hl| hl.range.start()); assert!(!hls.is_empty(), "No highlights"); let mut src = db.file_content(f[0].file_id).to_string(); for hl in hls.iter().rev() { let (open, close) = if hl.is_definition { ("<<", ">>") } else { ("<", ">") }; src.insert_str(usize::from(hl.range.end()), close); src.insert_str(usize::from(hl.range.start()), open); } expect.assert_eq(&src); } #[test] fn definition() { check("$0a: a + (a: a)", expect!["<<a>>: <a> + (a: a)"]); check( "let $0a.a = 1; a.b = 2; in a.a", expect!["let <<a>>.a = 1; <<a>>.b = 2; in <a>.a"], ); check( "let b.$0a.a = 1; b.a = { }; a = 1; in b.a", expect!["let b.<<a>>.a = 1; b.<<a>> = { }; a = 1; in b.a"], ); } #[test] fn reference() { check("a: $0a + (a: a)", expect!["<<a>>: <a> + (a: a)"]); check( "let a.a = 1; a.b = 2; in $0a.a", expect!["let <<a>>.a = 1; <<a>>.b = 2; in <a>.a"], ); } #[test] fn inherit() { check( "let $0a = 1; in { inherit a; }", expect!["let <<a>> = 1; in { inherit <a>; }"], ); check( "let a = 1; in { inherit $0a; }", expect!["let <<a>> = 1; in { inherit <a>; }"], ); check( "let $0a = 1; in rec { inherit a; }", expect!["let <<a>> = 1; in rec { inherit <a>; }"], ); check( "let a = 1; in rec { inherit $0a; }", expect!["let <<a>> = 1; in rec { inherit <a>; }"], ); } #[test] fn with() { check( "with 1; a + (with 2; $0a + b (with 3; a))", expect!["<<with>> 1; a + (<<with>> 2; <a> + b (with 3; a))"], ); check( "with 1; a + ($0with 2; a + b (with 3; a))", expect!["with 1; a + (<<with>> 2; <a> + <b> (with 3; <a>))"], ); } }
true
40823da6d5b9d6c6f824de69a8e7cf7234625b7e
Rust
marco-c/gecko-dev-wordified
/third_party/rust/ron/tests/322_escape_idents.rs
UTF-8
892
2.890625
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use serde : : { Deserialize Serialize } ; # [ derive ( Debug Deserialize PartialEq Serialize ) ] # [ serde ( rename_all = " kebab - case " ) ] enum MyEnumWithDashes { ThisIsMyUnitVariant ThisIsMyTupleVariant ( bool i32 ) } # [ derive ( Debug Deserialize PartialEq Serialize ) ] # [ serde ( rename_all = " kebab - case " ) ] struct MyStructWithDashes { my_enum : MyEnumWithDashes # [ serde ( rename = " 2nd " ) ] my_enum2 : MyEnumWithDashes will_be_renamed : u32 } # [ test ] fn roundtrip_ident_with_dash ( ) { let value = MyStructWithDashes { my_enum : MyEnumWithDashes : : ThisIsMyUnitVariant my_enum2 : MyEnumWithDashes : : ThisIsMyTupleVariant ( false - 3 ) will_be_renamed : 32 } ; let serial = ron : : ser : : to_string ( & value ) . unwrap ( ) ; println ! ( " Serialized : { } " serial ) ; let deserial = ron : : de : : from_str ( & serial ) ; assert_eq ! ( Ok ( value ) deserial ) ; }
true
ad548db115333690b40869c500d429bbae555abb
Rust
habitat-sh/habitat
/components/hab/src/command/plan/render.rs
UTF-8
4,951
2.765625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
use serde_json::{self, json, Value as Json}; use std::{fs::{create_dir_all, read_to_string, File}, io::Write, path::Path}; use toml::Value; use crate::{common::{templating::TemplateRenderer, ui::{Status, UIWriter, UI}}, error::Result}; #[allow(clippy::too_many_arguments)] pub fn start(ui: &mut UI, template_path: &Path, default_toml_path: &Path, user_toml_path: Option<&Path>, mock_data_path: Option<&Path>, print: bool, render: bool, render_dir: &Path, quiet: bool) -> Result<()> { // Strip the file name out of our passed template let file_name = Path::new(template_path.file_name().expect("valid template file")); if !quiet { ui.begin(format!("Rendering: {} into: {} as: {}", template_path.display(), render_dir.display(), file_name.display()))?; ui.br()?; } // read our template from file let template = read_to_string(template_path)?; // create a "data" json struct let mut data = json!({}); if !quiet { // import default.toml values, convert to JSON ui.begin(format!("Importing default.toml: {}", &default_toml_path.display()))?; } // we should always have a default.toml, would be nice to "autodiscover" based on package name, // for now assume we're working in the plan dir if --default-toml not passed let default_toml = read_to_string(default_toml_path)?; // merge default into data struct merge(&mut data, toml_to_json(&default_toml)?); // import default.toml values, convert to JSON let user_toml = match user_toml_path { Some(path) => { if !quiet { // print helper message, maybe only print if '--verbose'? how? ui.begin(format!("Importing user.toml: {}", path.display()))?; } read_to_string(path)? } None => String::new(), }; // merge default into data struct merge(&mut data, toml_to_json(&user_toml)?); // read mock data if provided let mock_data = match mock_data_path { Some(path) => { if !quiet { // print helper message, maybe only print if '--verbose'? how? ui.begin(format!("Importing override file: {}", path.display()))?; } read_to_string(path)? } // return an empty json block if '--mock-data' isn't defined. // this allows us to merge an empty JSON block None => "{}".to_string(), }; // merge mock data into data merge(&mut data, serde_json::from_str(&mock_data)?); // create a template renderer let mut renderer = TemplateRenderer::new(); // register our template renderer.register_template_string(&template, &template) .expect("Could not register template content"); // render our JSON override in our template. let rendered_template = renderer.render(&template, &data)?; if print { if !quiet { ui.br()?; ui.warn(format!("###======== Rendered template: {}", &template_path.display()))?; } println!("{}", rendered_template); if !quiet { ui.warn(format!("========### End rendered template: {}", &template_path.display()))?; } } if render { // Render our template file create_with_template(ui, render_dir, file_name, &rendered_template, quiet)?; } if !quiet { ui.br()?; } Ok(()) } fn toml_to_json(cfg: &str) -> Result<Json> { let toml_value = cfg.parse::<Value>()?; let toml_string = serde_json::to_string(&toml_value)?; let json = serde_json::from_str(&format!(r#"{{ "cfg": {} }}"#, &toml_string))?; Ok(json) } // merge two Json structs fn merge(a: &mut Json, b: Json) { if let Json::Object(a_map) = a { if let Json::Object(b_map) = b { for (k, v) in b_map { merge(a_map.entry(k).or_insert(Json::Null), v); } return; } } *a = b; } fn create_with_template(ui: &mut UI, render_dir: &std::path::Path, file_name: &std::path::Path, template: &str, quiet: bool) -> Result<()> { let path = Path::new(&render_dir).join(file_name); if !quiet { ui.status(Status::Creating, format!("file: {}", path.display()))?; } create_dir_all(render_dir)?; // Write file to disk File::create(path).and_then(|mut file| file.write(template.as_bytes()))?; Ok(()) }
true
69f90081d486f185eb86eaf7cc4a3bbab6210458
Rust
HarukiOwO/lndown
/src/search.rs
UTF-8
1,845
2.734375
3
[]
no_license
extern crate prettytable; use prettytable::*; use reqwest::header::USER_AGENT; use scraper::Html; pub async fn search(query: &str) -> Result<String, reqwest::Error> { let res = reqwest::Client::new() .get(format!( "{}{}/1", "https://www.wuxiaworld.co/search/", query )) .header( USER_AGENT, "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0", ) .send() .await?; let body = res.text().await?; let html = Html::parse_document(body.as_str()); let search_selector = scraper::Selector::parse("ul.result-list > li > div.item-info > a.book-name").unwrap(); let mut r: Vec<_> = vec![]; let sel = html.select(&search_selector); //order 0 : LN Name, 1 : Author, 2 : href sel.into_iter().for_each(|x| { r.append(&mut x.text().collect::<Vec<_>>()); r.append(&mut vec![x.value().attr("href").unwrap()]); }); //print out LightNovel names and author names let mut table = Table::new(); table.add_row(row!["", Frbc->"LightNovel", Frbc->"Author"]); for i in (0..r.len()).step_by(3) { //yeah i know there's probably a better way to do this if i == 0 { table.add_row(row![Frbc->i + 1, Frbc->&r[i], Frbc->&r[i + 1]]); } else { table.add_row(row![Frbc->(i / 3) + 1, Frbc->&r[i], Frbc->&r[i + 1]]); } } table.printstd(); println!("Select Novel To Download : "); //get user input let mut input = String::new(); std::io::stdin() .read_line(&mut input) .expect("Error: Unable to read user input"); input.truncate(input.len() - 1); let i = (input.parse::<i32>().unwrap() * 3) - 1; let result = r.get(i as usize).unwrap(); Ok(result.to_string()) }
true
c2a620cc120c106ce282cd68803a77fe16a1eb6b
Rust
portablejim/project-euler
/rust/src/bin/task590.rs
UTF-8
319
2.9375
3
[]
no_license
extern crate num; use num::Integer; use num::bigint::BigInt; use num::integer::gcd; use num::integer::lcm; fn main() { let number1 = 500; let lcm_num1 = (2..(number1+1)).fold(BigInt::from(1), |a,b| { println!("{:?}", a); a.lcm(&BigInt::from(b))}); println!("{}", lcm_num1); println!("{}", lcm(2,3)); }
true
2df08cad89ccaf73d28f6835306de51ddfa128de
Rust
MaxOhn/Bathbot
/bathbot/src/commands/fun/minesweeper.rs
UTF-8
5,352
2.984375
3
[ "ISC" ]
permissive
use std::{ fmt::{Display, Formatter, Result as FmtResult, Write}, sync::Arc, }; use bathbot_macros::{command, SlashCommand}; use bathbot_util::{CowUtils, Matrix, MessageBuilder}; use eyre::Result; use rand::RngCore; use twilight_interactions::command::{CommandModel, CommandOption, CreateCommand, CreateOption}; use crate::{ core::{ commands::{prefix::Args, CommandOrigin}, Context, }, util::{interaction::InteractionCommand, ChannelExt, InteractionCommandExt}, }; #[derive(CommandModel, CreateCommand, SlashCommand)] #[command( name = "minesweeper", desc = "Play a game of minesweeper", help = "Play a game of minesweeper.\n\ In case you don't know how it works: Each number indicates the amount of neighboring bombs." )] #[flags(SKIP_DEFER)] pub struct Minesweeper { #[command(desc = "Choose a difficulty")] difficulty: Difficulty, } #[derive(CommandOption, CreateOption)] enum Difficulty { #[option(name = "easy", value = "easy")] Easy, #[option(name = "medium", value = "medium")] Medium, #[option(name = "hard", value = "hard")] Hard, // #[option(name = "expert", value = "expert")] // Expert, } pub async fn slash_minesweeper(ctx: Arc<Context>, mut command: InteractionCommand) -> Result<()> { let args = Minesweeper::from_interaction(command.input_data())?; minesweeper(ctx, (&mut command).into(), args.difficulty).await } #[command] #[desc("Play a game of minesweeper")] #[help( "Play a game of minesweeper.\n\ The available arguments are:\n\ - `easy`: 6x6 grid\n\ - `medium`: 8x8 grid\n\ - `hard`: 9x11 grid" )] #[usage("[easy / medium / hard]")] #[flags(SKIP_DEFER)] #[group(Games)] async fn prefix_minesweeper(ctx: Arc<Context>, msg: &Message, mut args: Args<'_>) -> Result<()> { let difficulty = match Difficulty::args(&mut args) { Ok(difficulty) => difficulty, Err(content) => { msg.error(&ctx, content).await?; return Ok(()); } }; minesweeper(ctx, msg.into(), difficulty).await } async fn minesweeper( ctx: Arc<Context>, orig: CommandOrigin<'_>, difficulty: Difficulty, ) -> Result<()> { let game = difficulty.create(); let (w, h) = game.dim(); let mut field = String::with_capacity(w * h * 9); for x in 0..w { for y in 0..h { let _ = write!(field, "||:{}:||", game.field[(x, y)]); } field.push('\n'); } field.pop(); let content = format!("Here's a {w}x{h} game with {} mines:\n{field}", game.mines); let builder = MessageBuilder::new().content(content); orig.callback(&ctx, builder).await?; Ok(()) } impl Difficulty { fn args(args: &mut Args<'_>) -> Result<Self, &'static str> { match args .next() .map(|arg| arg.cow_to_ascii_lowercase()) .as_deref() { None | Some("easy") => Ok(Self::Easy), Some("medium") => Ok(Self::Medium), Some("hard") => Ok(Self::Hard), // Some("expert") => Ok(Self::Expert), _ => Err("The argument must be either `easy`, `medium`, or `hard`"), } } fn create(&self) -> Game { match self { Self::Easy => Game::new(6, 6, 6), Self::Medium => Game::new(8, 8, 12), Self::Hard => Game::new(11, 9, 20), // Self::Expert => Game::new(13, 13, 40), } } } struct Game { pub field: Matrix<Cell>, pub mines: u8, } impl Game { fn new(height: usize, width: usize, mines: u8) -> Self { let mut field = Matrix::new(width, height); let mut rng = rand::thread_rng(); let size = width * height; let mut new_mines = mines; // Place mines while new_mines > 0 { let r = rng.next_u32() as usize % size; let x = r % width; let y = r / width; if field[(x, y)] == Cell::None { field[(x, y)] = Cell::Mine; new_mines -= 1; } } // Place numbers for x in 0..width { for y in 0..height { if field[(x, y)] == Cell::None { let mines = field.count_neighbors(x, y, Cell::Mine); field[(x, y)] = Cell::Num(mines); } } } Self { field, mines } } fn dim(&self) -> (usize, usize) { (self.field.width(), self.field.height()) } } #[derive(Clone, Copy, Eq, PartialEq)] enum Cell { Num(u8), Mine, None, } impl Display for Cell { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match self { Self::Num(0) => f.write_str("zero"), Self::Num(1) => f.write_str("one"), Self::Num(2) => f.write_str("two"), Self::Num(3) => f.write_str("three"), Self::Num(4) => f.write_str("four"), Self::Num(5) => f.write_str("five"), Self::Num(6) => f.write_str("six"), Self::Num(7) => f.write_str("seven"), Self::Num(8) => f.write_str("eight"), Self::Mine => f.write_str("bomb"), Self::None | Self::Num(_) => unreachable!(), } } } impl Default for Cell { fn default() -> Self { Self::None } }
true
11a905830d6be3e3f6bb2ffcbe5d68376d065959
Rust
sts10/Alice
/src/main.rs
UTF-8
4,323
3.28125
3
[ "LPPL-1.3c" ]
permissive
// main.rs // Copyright 2020~2021 Lu Neder // // This work may be distributed and/or modified under the // conditions of the LaTeX Project Public License, either version 1.3 // of this license or (at your option) any later version. // The latest version of this license is in // http://www.latex-project.org/lppl.txt // and version 1.3 or later is part of all distributions of LaTeX // version 2005/12/01 or later. // // This work has the LPPL maintenance status `maintained'. // // The Current Maintainer of this work is Lu Neder. // // This work consists of the files main.rs, README.md and the included original.txt example. //Alice requires an original.txt file on the directory you're running it from. //Alice will read the file and then type it (a line followed by an enter, then the next line). //This way you can send the file contnent on a chat, for example, each line on a message. //You can also tell Alice to wait some time between a line and the other. //The first line will be written 10 seconds after you run Alice and tell the time between a line and the other, //this way you have time to select the place where you want to input your text. //"Alice" was just the 1st name I found on Google lol use std::env; use text_io::scan; use std::fs; use std::str; use std::{thread, time}; use simulate; use simulate::Key; use chrono::prelude::*; fn main() { let ver: String = "3.0.0".to_string(); //sets ver vaiable to current Alice version // Get command line input and save it as an args variable let args: String = env::args().collect(); // Checks if the mode selected in command line was help and runs it or not if args.contains("help") { alice_help(ver); // Help mode } else { // Asks how many seconds between lines and save it as a t variable println!("How many seconds between lines?"); let t: i32; scan!("{}", t); // Prints the t variable println!("{} seconds between lines", t); // Open and divide original.txt by lines let file = "original.txt"; let open = fs::read_to_string(file) .expect("Something went wrong reading the file"); let mut divided: Vec<&str> = open.lines().collect(); // Checks selected mode in command line and runs it if args.contains("loop") {alice_loop(t, divided);} // Loop mode else {alice(t, divided)}; // Regular mode }; } // Help mode, prints help and the version ver fn alice_help(ver: String) { println!("Alice {} Help", ver); println!("--help: Help mode: show this message"); println!("--loop: Loop mode: restart the file from beginning after it's over"); println!("No args: Normal mode: stop once file ends"); } // Loop mode fn alice_loop(t: i32, divided: Vec<&str>) { println!("loop ({} seconds between lines)", t); // Waits 10 seconds before running let tensec = time::Duration::from_secs(10); thread::sleep(tensec); // Loops Alice loop { let mut divided2 = divided.clone(); // Clones the divided variable because the program won't compile otherwise alice(t, divided2); // run Alice regular mode, inside the loop } } //Regular mode fn alice(t: i32, divided: Vec<&str>) { // If the args contains loop, does not wait 10 seconds since alice_loop() alreadi did that. If it's regular mode, waits 10 seconds let args: String = env::args().collect(); if args.contains("loop") {println!("LOOP")} else { println!("alice ({} seconds between lines)", t); let tensec = time::Duration::from_secs(10); thread::sleep(tensec); } // Converts t into u64 let tttt = t as u64; // Repeats with each line of the file for i in divided { let halfsec = time::Duration::from_millis(500); // Set halfsec variable to 500 ms simulate::type_str(i).unwrap(); // types the line thread::sleep(halfsec); // Waits halfsec (500 ms) simulate::send(Key::Enter).unwrap(); // Press enter let now = Local::now(); println!("{} - {:#?}", i, now); // prints in terminal the linee that was just typed and the time it was sent let z = time::Duration::from_secs(tttt); thread::sleep(z); // Waits the time that the user input at the start of the program } }
true
7b909747ee101a25371b3450b53e312d37c3ee51
Rust
happysalada/poem
/poem/src/web/websocket/message.rs
UTF-8
8,613
3.515625
4
[ "MIT", "Apache-2.0" ]
permissive
/// Status code used to indicate why an endpoint is closing the WebSocket /// connection. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum CloseCode { /// Indicates a normal closure, meaning that the purpose for /// which the connection was established has been fulfilled. Normal, /// Indicates that an endpoint is "going away", such as a server /// going down or a browser having navigated away from a page. Away, /// Indicates that an endpoint is terminating the connection due /// to a protocol error. Protocol, /// Indicates that an endpoint is terminating the connection /// because it has received a type of data it cannot accept (e.g., an /// endpoint that understands only text data MAY send this if it /// receives a binary message). Unsupported, /// Indicates that no status code was included in a closing frame. Status, /// Indicates an abnormal closure. Abnormal, /// Indicates that an endpoint is terminating the connection /// because it has received data within a message that was not /// consistent with the type of the message (e.g., non-UTF-8 \[RFC3629\] /// data within a text message). Invalid, /// Indicates that an endpoint is terminating the connection /// because it has received a message that violates its policy. This /// is a generic status code that can be returned when there is no /// other more suitable status code (e.g., Unsupported or Size) or if there /// is a need to hide specific details about the policy. Policy, /// Indicates that an endpoint is terminating the connection /// because it has received a message that is too big for it to /// process. Size, /// Indicates that an endpoint (client) is terminating the /// connection because it has expected the server to negotiate one or /// more extension, but the server didn't return them in the response /// message of the WebSocket handshake. The list of extensions that /// are needed should be given as the reason for closing. /// Note that this status code is not used by the server, because it /// can fail the WebSocket handshake instead. Extension, /// Indicates that a server is terminating the connection because /// it encountered an unexpected condition that prevented it from /// fulfilling the request. Error, /// Indicates that the server is restarting. A client may choose to /// reconnect, and if it does, it should use a randomized delay of 5-30 /// seconds between attempts. Restart, /// Indicates that the server is overloaded and the client should either /// connect to a different IP (when multiple targets exist), or /// reconnect to the same IP when a user has performed an action. Again, /// Code reserved for the future. Reserved(u16), } impl From<u16> for CloseCode { fn from(code: u16) -> Self { use CloseCode::*; match code { 1000 => Normal, 1001 => Away, 1002 => Protocol, 1003 => Unsupported, 1005 => Status, 1006 => Abnormal, 1007 => Invalid, 1008 => Policy, 1009 => Size, 1010 => Extension, 1011 => Error, 1012 => Restart, 1013 => Again, _ => Reserved(code), } } } impl From<CloseCode> for u16 { fn from(code: CloseCode) -> Self { use CloseCode::*; match code { Normal => 1000, Away => 1001, Protocol => 1002, Unsupported => 1003, Status => 1005, Abnormal => 1006, Invalid => 1007, Policy => 1008, Size => 1009, Extension => 1010, Error => 1011, Restart => 1012, Again => 1013, Reserved(code) => code, } } } /// An enum representing the various forms of a WebSocket message. #[derive(Debug, Clone, Eq, PartialEq)] pub enum Message { /// A text WebSocket message Text(String), /// A binary WebSocket message Binary(Vec<u8>), /// A ping message with the specified payload /// /// The payload here must have a length less than 125 bytes Ping(Vec<u8>), /// A pong message with the specified payload /// /// The payload here must have a length less than 125 bytes Pong(Vec<u8>), /// A close message with the optional close frame. Close(Option<(CloseCode, String)>), } impl Message { /// Construct a new text message. pub fn text(text: impl Into<String>) -> Self { Self::Text(text.into()) } /// Construct a new binary message. pub fn binary(data: impl Into<Vec<u8>>) -> Self { Self::Binary(data.into()) } /// Construct a new ping message. pub fn ping(data: impl Into<Vec<u8>>) -> Self { Self::Ping(data.into()) } /// Construct a new pong message. pub fn pong(data: impl Into<Vec<u8>>) -> Self { Self::Pong(data.into()) } /// Construct the default close message. pub fn close() -> Self { Self::Close(None) } /// Construct a close message with a code and reason. pub fn close_with(code: impl Into<CloseCode>, reason: impl Into<String>) -> Self { Self::Close(Some((code.into(), reason.into()))) } /// Returns true if this message is a Text message. #[inline] pub fn is_text(&self) -> bool { matches!(self, Message::Text(_)) } /// Returns true if this message is a Binary message. #[inline] pub fn is_binary(&self) -> bool { matches!(self, Message::Binary(_)) } /// Returns true if this message is a Ping message. pub fn is_ping(&self) -> bool { matches!(self, Message::Ping(_)) } /// Returns true if this message is a Pong message. pub fn is_pong(&self) -> bool { matches!(self, Message::Pong(_)) } /// Returns true if this message a is a Close message. pub fn is_close(&self) -> bool { matches!(self, Message::Close(_)) } /// Destructure this message into binary data. pub fn into_bytes(self) -> Vec<u8> { match self { Message::Text(data) => data.into_bytes(), Message::Binary(data) => data, Message::Ping(data) => data, Message::Pong(data) => data, Message::Close(_) => Default::default(), } } /// Return the bytes of this message, if the message can contain data. pub fn as_bytes(&self) -> &[u8] { match self { Message::Text(data) => data.as_bytes(), Message::Binary(data) => data, Message::Ping(data) => data, Message::Pong(data) => data, Message::Close(_) => &[], } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_message() { assert_eq!(Message::text("abc"), Message::Text("abc".to_string())); assert_eq!( Message::binary(vec![1, 2, 3]), Message::Binary(vec![1, 2, 3]) ); assert_eq!(Message::ping(vec![1, 2, 3]), Message::Ping(vec![1, 2, 3])); assert_eq!(Message::pong(vec![1, 2, 3]), Message::Pong(vec![1, 2, 3])); assert_eq!(Message::close(), Message::Close(None)); assert_eq!( Message::close_with(CloseCode::Again, "again"), Message::Close(Some((CloseCode::Again, "again".to_string()))) ); assert!(Message::text("abc").is_text()); assert!(Message::binary("abc").is_binary()); assert!(Message::ping(vec![1, 2, 3]).is_ping()); assert!(Message::pong(vec![1, 2, 3]).is_pong()); assert!(Message::close().is_close()); assert_eq!( Message::text("abc").into_bytes(), "abc".to_string().into_bytes() ); assert_eq!(Message::binary(vec![1, 2, 3]).into_bytes(), vec![1, 2, 3]); assert_eq!(Message::ping(vec![1, 2, 3]).into_bytes(), vec![1, 2, 3]); assert_eq!(Message::pong(vec![1, 2, 3]).into_bytes(), vec![1, 2, 3]); assert_eq!(Message::close().into_bytes(), Vec::<u8>::new()); assert_eq!(Message::text("abc").as_bytes(), "abc".as_bytes()); assert_eq!(Message::binary(vec![1, 2, 3]).as_bytes(), &[1, 2, 3]); assert_eq!(Message::ping(vec![1, 2, 3]).as_bytes(), &[1, 2, 3]); assert_eq!(Message::pong(vec![1, 2, 3]).as_bytes(), &[1, 2, 3]); assert_eq!(Message::close().as_bytes(), &[] as &[u8]); } }
true
95496aeb0738c66464c02aed5f8ebe09b73c8c7f
Rust
lex148/leftwm
/src/utils/helpers.rs
UTF-8
2,792
3.28125
3
[ "MIT" ]
permissive
//! Generic intersection, finding, reordering, and Vec extraction use std::cmp::Ordering; pub fn intersect<T>(v1: &[T], v2: &[T]) -> bool where T: PartialEq, { for a in v1 { for b in v2 { if a == b { return true; } } } false } pub fn vec_extract<T, F>(list: &mut Vec<T>, test: F) -> Vec<T> where F: Fn(&T) -> bool, T: Clone, { let len = list.len(); let mut removed = vec![]; let mut del = 0; { let v = &mut **list; for i in 0..len { if test(&v[i]) { removed.push(v[i].clone()); del += 1; } else if del > 0 { v.swap(i - del, i); } } } list.truncate(len - del); removed } pub fn cycle_vec<T>(list: &mut Vec<T>, shift: i32) -> Option<()> where T: Clone, { let v = &mut **list; let change = shift.abs() as usize; if v.len() < change { return None; } match shift.cmp(&0) { Ordering::Less => v.rotate_left(change), Ordering::Greater => v.rotate_right(change), Ordering::Equal => {} } Some(()) } //shifts a object left or right in an Vec by a given amount pub fn reorder_vec<T, F>(list: &mut Vec<T>, test: F, shift: i32) -> Option<()> where F: Fn(&T) -> bool, T: Clone, { let len = list.len() as i32; if len < 2 { return None; } let index = list.iter().position(|x| test(x))?; let item = list.get(index)?.clone(); let mut new_index = index as i32 + shift; list.remove(index); let v = &mut **list; if new_index < 0 { new_index += len; v.rotate_right(1); } else if new_index >= len { new_index -= len; v.rotate_left(1); } list.insert(new_index as usize, item); Some(()) } pub fn relative_find<T, F>(list: &[T], test: F, shift: i32, should_loop: bool) -> Option<&T> where F: Fn(&T) -> bool, T: Clone, { let index = list.iter().position(|x| test(x))?; let len = list.len() as i32; if len == 1 { return list.get(index as usize); } let mut find_index = index as i32 + shift; if find_index < 0 && should_loop { find_index += len; } else if find_index >= len && should_loop { find_index -= len; } else if find_index < 0 || find_index >= len { return None; } list.get(find_index as usize) } #[cfg(test)] pub(crate) mod test { pub async fn temp_path() -> std::io::Result<std::path::PathBuf> { tokio::task::spawn_blocking(|| tempfile::Builder::new().tempfile_in("target")) .await .expect("Blocking task joined")? .into_temp_path() .keep() .map_err(Into::into) } }
true
6f4ba56a3683dbd7a7293d20e76abffabdb01edf
Rust
jafow/awl
/src/server/connection.rs
UTF-8
837
3
3
[ "MIT" ]
permissive
use std::net::{SocketAddr, IpAddr}; #[derive(Debug)] pub struct Client { pub private: SocketAddr, pub public: SocketAddr, } impl Client { pub fn serialize_found_peer(&self) { // returns u8 array of destination peer's public IP } } pub struct Pool { pub connections: Vec<Client>, } impl Pool { pub fn client_in_pool(&self, target_ip: &IpAddr) -> Option<usize> { for (i, ref client) in self.connections.iter().enumerate() { if client.private.ip() == *target_ip { return Some(i); } } None } pub fn find_client(&mut self, target_ip: &IpAddr) -> Option<Client> { match self.client_in_pool(&target_ip) { Some(pos) => return Some(self.connections.swap_remove(pos)), _ => return None, } } }
true
c08c0eeb7c031824b335631b3cbf731ce59cd2c4
Rust
FliegendeWurst/fend
/core/src/date/day.rs
UTF-8
853
3.40625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::fmt; #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) struct Day(u8); impl Day { pub(crate) fn value(self) -> u8 { self.0 } pub(crate) fn new(day: u8) -> Self { assert!(day != 0 && day < 32, "day value {} is out of range", day); Self(day) } } impl fmt::Debug for Day { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl fmt::Display for Day { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic] fn day_0() { Day::new(0); } #[test] #[should_panic] fn day_32() { Day::new(32); } #[test] fn day_to_string() { assert_eq!(Day::new(1).to_string(), "1"); } }
true
61535df59a14a0117cb35945d1f786c507d00aad
Rust
revcx/revc
/src/bin/io/demuxer/mod.rs
UTF-8
1,330
2.625
3
[ "MIT" ]
permissive
mod nalu; mod y4m; mod yuv; use std::fs::File; use std::io; use std::io::Read; use std::path::Path; use self::nalu::NaluDemuxer; use self::y4m::Y4mDemuxer; use crate::io::demuxer::yuv::YuvDemuxer; use revc::api::*; #[derive(Debug, Clone, Copy)] pub struct VideoInfo { pub width: usize, pub height: usize, pub bit_depth: usize, pub chroma_sampling: ChromaSampling, pub time_base: Rational, } impl Default for VideoInfo { fn default() -> Self { VideoInfo { width: 640, height: 480, bit_depth: 8, chroma_sampling: ChromaSampling::Cs420, time_base: Rational { num: 30, den: 1 }, } } } pub trait Demuxer { fn read(&mut self) -> io::Result<Data>; fn info(&self) -> Option<VideoInfo>; } pub fn new(filename: &str, info: Option<VideoInfo>) -> io::Result<Box<dyn Demuxer>> { if let Some(ext) = Path::new(filename).extension() { if ext == "y4m" { Ok(Y4mDemuxer::new(filename)?) } else if ext == "yuv" { Ok(YuvDemuxer::new(filename, info)?) } else { // .evc Ok(NaluDemuxer::new(filename)?) } } else { Err(io::Error::new( io::ErrorKind::InvalidInput, "Filename doesn't have extension", )) } }
true
f109e34ae9e0d5d7e75489919debbaf5b4a01577
Rust
DemonusPC/ray-tracing-demo
/src/material.rs
UTF-8
4,797
2.890625
3
[]
no_license
use std::rc::Rc; use crate::ray::Ray; use crate::texture::{SolidColor, Texture}; use crate::vec3::Vec3; use crate::{ hit::HitRecord, texture::{CheckerTexture, PerlinTexture}, }; use crate::{random_double, texture::ImageTexture}; pub trait Material { fn scatter( &self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool; fn emitted(&self, u: f64, v: f64, p: &Vec3) -> Vec3; } pub struct Lambertian { albedo: Rc<dyn Texture>, } impl Lambertian { pub fn new(color: Vec3) -> Lambertian { Lambertian { albedo: Rc::new(SolidColor::new(color)), } } pub fn from_checker(texture: CheckerTexture) -> Lambertian { Lambertian { albedo: Rc::new(texture), } } pub fn from_perlin(texture: PerlinTexture) -> Lambertian { Lambertian { albedo: Rc::new(texture), } } pub fn from_image(texture: ImageTexture) -> Lambertian { Lambertian { albedo: Rc::new(texture), } } } impl Material for Lambertian { fn scatter( &self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { let scatter_direction = rec.normal() + Vec3::random_unit_vector(); *scattered = Ray::new(&rec.p(), &scatter_direction, ray_in.time()); *attenuation = self.albedo.value(rec.u(), rec.v(), &rec.p()); true } fn emitted(&self, u: f64, v: f64, p: &Vec3) -> Vec3 { Vec3::empty() } } pub struct Metal { albedo: Vec3, fuzz: f64, } impl Metal { pub fn new(color: Vec3, fuzz: f64) -> Metal { let f = if fuzz < 1.0 { fuzz } else { 1.0 }; Metal { albedo: color, fuzz: f, } } } impl Material for Metal { fn scatter( &self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { let reflected: Vec3 = Vec3::reflect(&Vec3::unit_vector(ray_in.direction()), &rec.normal()); *scattered = Ray::new( &rec.p(), &(reflected + Vec3::random_in_unit_sphere() * self.fuzz), ray_in.time(), ); *attenuation = Vec3::new(self.albedo.x(), self.albedo.y(), self.albedo.z()); let result = Vec3::dot(&scattered.direction(), &rec.normal()) > 0.0; result } fn emitted(&self, u: f64, v: f64, p: &Vec3) -> Vec3 { Vec3::empty() } } pub fn schlick(cosine: f64, ref_idx: f64) -> f64 { let r0 = (1.0 - ref_idx) / (1.0 + ref_idx); let r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - cosine).powi(5) } pub struct Dielectric { ref_idx: f64, } impl Dielectric { pub fn new(ri: f64) -> Dielectric { Dielectric { ref_idx: ri } } } impl Material for Dielectric { fn scatter( &self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { *attenuation = Vec3::new(1.0, 1.0, 1.0); let etai_over_etat = if rec.front_face() { 1.0 / self.ref_idx } else { self.ref_idx }; let unit_direction = Vec3::unit_vector(ray_in.direction()); let cos_theta = Vec3::dot(&-unit_direction, &rec.normal()).min(1.0); let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); if etai_over_etat * sin_theta > 1.0 { let reflected = Vec3::reflect(&unit_direction, &rec.normal()); *scattered = Ray::new(&rec.p(), &reflected, ray_in.time()); return true; } let reflect_prob = schlick(cos_theta, etai_over_etat); if random_double() < reflect_prob { let reflected = Vec3::reflect(&unit_direction, &rec.normal()); *scattered = Ray::new(&rec.p(), &reflected, ray_in.time()); return true; } let refracted = Vec3::refract(&unit_direction, &rec.normal(), etai_over_etat); *scattered = Ray::new(&rec.p(), &refracted, ray_in.time()); true } fn emitted(&self, u: f64, v: f64, p: &Vec3) -> Vec3 { Vec3::empty() } } pub struct DiffuseLight { emit: Rc<dyn Texture>, } impl DiffuseLight { pub fn new(color: Vec3) -> DiffuseLight { DiffuseLight { emit: Rc::new(SolidColor::new(color)), } } } impl Material for DiffuseLight { fn scatter( &self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { false } fn emitted(&self, u: f64, v: f64, p: &Vec3) -> Vec3 { self.emit.value(u, v, p) } }
true
d3cf6bc002284f9d1bce559ceb401e4d7c687b0f
Rust
gcfbn/learning_rust
/utils/examples/use_default_logging/main.rs
UTF-8
722
2.703125
3
[]
no_license
/// You can run this program with the following command e.g.: /// /// RUST_LOG=error,use_default_logging=warn cargo run --example use_default_logging --features default_logging /// mod cmd_args; use cmd_args::CmdArgs; use log::warn; use thiserror::Error; use utils::{ApplicationRunner, DefaultAppLoggerCreator}; #[derive(Debug, Error)] #[error("Application error !")] struct AppError; struct App; fn main() { App.main(); } impl ApplicationRunner for App { type AppLoggerCreator = DefaultAppLoggerCreator; type CmdArgs = CmdArgs; type Error = AppError; fn run(&self, _cmd_args: CmdArgs) -> Result<(), Self::Error> { warn!("this method will raise an error"); Err(AppError) } }
true
5ccd8986fb1f79154fb62f3774b59445ce320b94
Rust
yuki-uthman/matrix_rust
/src/matrix/with_mpsc2.rs
UTF-8
4,115
3.375
3
[]
no_license
use std::ops::Range; use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; use std::thread; fn is_it_half(a: u64, b: u64) -> bool { (a as f64 / b as f64) * 10.0 % 10.0 == 5.0 } pub fn split_number(target: u64, thread: u64) -> Vec<std::ops::Range<u64>> { let mut ranges: Vec<std::ops::Range<u64>> = Vec::new(); let mut x = 0; if is_it_half(target, thread) { x = target / thread } else { x = (target as f64 / thread as f64).round() as u64; } for i in 0..thread { if i == thread - 1 && x * (i + 1) != target { ranges.push(x * i..target); } else { ranges.push(x * i..x * (i + 1)); } } ranges } fn multiply_with_range(range: Range<u64>, a: &Vec<Vec<u64>>, b: &Vec<Vec<u64>>) -> Vec<Vec<u64>> { let col_size = a[0].len(); let row_size = a.len(); let mut new_block = vec![]; for thread_index in range { // each block for thread // do sth here let mut new_row = vec![]; for row_index in 0..row_size { let mut element = 0; for index in 0..col_size { element += a[thread_index as usize][index] * b[index][row_index] } new_row.push(element); } new_block.push(new_row); } new_block } fn multiply_matrix(thread: u64, a: &Vec<Vec<u64>>, b: &Vec<Vec<u64>>) -> Vec<Vec<u64>> { let ranges = split_number(*&a.len() as u64, thread); let (tx, rx) = mpsc::channel(); let mut children = Vec::new(); let mut id = 0; for range in ranges { let thread_tx = tx.clone(); let a = a.clone(); let b = b.clone(); let child = thread::spawn(move || { let new_block = multiply_with_range(range, &a, &b); // println!("sending {:?}", new_block); thread_tx.send((id, new_block)).unwrap(); }); children.push(child); id += 1; } let mut received = vec![]; for _ in 0..thread { let recv = rx.recv().unwrap(); received.push(recv); } received.sort_by_key(|tuple| tuple.0); let mut result = vec![]; for tuple in received { result.extend(tuple.1); } for child in children { child.join().expect("oops! the child thread panicked"); } result } pub fn calculate(thread: u64, size: usize) -> Vec<Vec<u64>> { let a = super::generate_matrix_u64(size); let b = a.clone(); multiply_matrix(thread, &a, &b) } #[test] fn test_multipy_matrix() { let a = super::generate_matrix_u64(2); let b = super::generate_matrix_u64(2); let expected = vec![vec![7, 10], vec![15, 22]]; assert_eq!(expected, multiply_matrix(1, &a, &b)); let a = super::generate_matrix_u64(3); let b = super::generate_matrix_u64(3); let expected = vec![vec![30, 36, 42], vec![66, 81, 96], vec![102, 126, 150]]; assert_eq!(expected, multiply_matrix(1, &a, &b)); assert_eq!(expected, multiply_matrix(3, &a, &b)); let a = super::generate_matrix_u64(4); let b = super::generate_matrix_u64(4); let expected = vec![ vec![90, 100, 110, 120], vec![202, 228, 254, 280], vec![314, 356, 398, 440], vec![426, 484, 542, 600], ]; assert_eq!(expected, multiply_matrix(1, &a, &b)); assert_eq!(expected, multiply_matrix(2, &a, &b)); assert_eq!(expected, multiply_matrix(4, &a, &b)); } #[test] fn test_calculate() { let expected = vec![vec![7, 10], vec![15, 22]]; assert_eq!(expected, calculate(1, 2)); assert_eq!(expected, calculate(2, 2)); let expected = vec![vec![30, 36, 42], vec![66, 81, 96], vec![102, 126, 150]]; assert_eq!(expected, calculate(1, 3)); assert_eq!(expected, calculate(3, 3)); let expected = vec![ vec![90, 100, 110, 120], vec![202, 228, 254, 280], vec![314, 356, 398, 440], vec![426, 484, 542, 600], ]; assert_eq!(expected, calculate(1, 4)); assert_eq!(expected, calculate(2, 4)); assert_eq!(expected, calculate(3, 4)); assert_eq!(expected, calculate(4, 4)); }
true
6811b7b4c52e9400dbd6393742ff3956132fcb85
Rust
zaeleus/noodles
/noodles-fasta/src/fai/record/field.rs
UTF-8
338
2.890625
3
[ "MIT" ]
permissive
/// A FASTA index record field. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Field { /// The name. Name, /// The total length of the sequence. Length, /// The offset from the start. Offset, /// The number of bases in a line. LineBases, /// The number of characters in a line. LineWidth, }
true
d2820b2181ae67ee87534a92b79c6af54b82b7dd
Rust
AlexRiosJ/huffcomp
/src/huffman_tree/mod.rs
UTF-8
2,889
3.421875
3
[]
no_license
use serde::{Deserialize, Serialize}; use std::collections::{BinaryHeap, HashMap}; pub mod node; use node::Node; use node::NodeType::{Character, Joint}; #[derive(Serialize, Deserialize)] pub struct HuffmanTree { root: Node, } impl HuffmanTree { pub fn new(freq_map: &HashMap<u32, u32>) -> HuffmanTree { let mut queue = BinaryHeap::new(); for (ch, freq) in freq_map { let new_node = Node::new(Character(*ch as u32), *freq); queue.push(new_node); } let mut left_node: Node; let mut right_node: Node; let mut joint_node: Node; while queue.len() >= 2 { left_node = queue.pop().unwrap(); right_node = queue.pop().unwrap(); joint_node = Node::new(Joint, left_node.frequency + right_node.frequency); joint_node.left = Some(Box::new(left_node)); joint_node.right = Some(Box::new(right_node)); queue.push(joint_node); } HuffmanTree { root: queue.pop().unwrap(), } } pub fn _print(&self) { println!("-------------Printing Tree--------------"); self._print_recursive(&self.root, 0); println!("----------------------------------------"); } fn _print_recursive(&self, node: &Node, spaces: u32) { let mut temp = String::from(""); for _ in 0..spaces { temp.push_str("| "); } println!("{}{}", temp, node); if let (Some(left), Some(right)) = (&node.left, &node.right) { self._print_recursive(&*left, spaces + 1); self._print_recursive(&*right, spaces + 1); } } pub fn get_root(&self) -> &Node { &self.root } } pub fn fill_code_table(code_table: &mut HashMap<u32, String>, tree: &HuffmanTree) { fill_code_table_recursive(code_table, &tree.get_root(), String::from("")).unwrap(); } fn fill_code_table_recursive<'a>( code_table: &'a mut HashMap<u32, String>, node: &Node, mask: String, ) -> Result<(), &'static str> { if let None = &node.left { let character: u32; if let Character(c) = &node.value { character = *c; } else { return Err("Something went wrong with the table creation"); } code_table.insert(character, mask); return Ok(()); } Ok( if let (Some(left), Some(right)) = (&node.left, &node.right) { fill_code_table_recursive(code_table, &*left, format!("{}0", mask))?; fill_code_table_recursive(code_table, &*right, format!("{}1", mask))?; }, ) } pub fn char_freq(contents: &String) -> HashMap<u32, u32> { let mut freq_map: HashMap<u32, u32> = HashMap::new(); for c in contents.chars() { let count = freq_map.entry(c as u32).or_insert(0); *count += 1; } freq_map }
true
8b2f0fa8c7eb346f94a59f9fd01907bb194265ee
Rust
Lucretiel/cascade
/src/lib.rs
UTF-8
4,716
3.984375
4
[ "MIT" ]
permissive
/// A macro for chaining together statements that act on an initial expression. /// # Usage /// Cascading allows you to run multiple statements on a struct generated by an expression without having /// to repeatedly type it out. This can be very convinient for modifying multiple properties simultaneously, /// or running a long series of individual methods on a struct. /// /// When writing a cascade, the first line specifies the expression that will be operated upon. /// All following lines modify the struct created by the expression in some way. /// The most common operator is the `..` member operator, which is borrowed from Dart's syntax. /// It's a convinient shorthand for accessing a member or method of the struct. For example: /// ``` /// use cascade::cascade; /// /// let old_vector = vec!(1, 2, 3); /// let new_vector = cascade! { /// old_vector; /// ..push(4); /// ..push(5); /// ..push(6); /// }; /// ``` /// /// Remember, you can't move the struct, because it gets returned at the end of the cascade. In other words, /// you can't run a method on a struct with the `..` operator if the method takes `self` or /// `mut self`. But `&self` or `&mut self` works fine. /// /// If you want to put statements within the macro, you can use the `|` operator: /// ``` /// use cascade::cascade; /// use std::collections::HashMap; /// /// let hash_map = cascade! { /// HashMap::new(); /// ..insert("foo", "bar"); /// | println!("Look! You can put statements in a cascade!"); /// | for i in 0..3 { /// println!("You can put loops in here too! Make sure to put a semicolon at the end!"); /// }; /// }; /// ``` /// /// If you need to reference the expression inside a cascade, you can name it and then use it: /// ``` /// use cascade::cascade; /// /// let vector = cascade! { /// v: Vec::new(); /// ..push(1); /// | println!("The vector now has {} element(s).", v.len()); /// ..push(2); /// }; /// ``` /// This will print `The vector now has 1 element(s).` /// /// Once again, trying to move this value will throw an error. /// /// Finally, you can also use the member operator (`..`) to set or change members of the cascaded struct: /// ``` /// use cascade::cascade; /// struct A { /// pub b: u32, /// pub c: u32 /// } /// /// let a = cascade! { /// A { b: 0, c: 0 }; /// ..b = 5; /// ..c += 1; /// }; /// ``` /// /// More examples of the cascade macro can be found in the examples folder on the Github repository. /// /// # Common Mistakes /// Sometimes, you might get a weird error while using this macro. Most likely it will be some /// variation of `no rules expected the token '@'`. Since these errors are notoriously hard to debug, /// here are some common mistakes one might make that will result in this error being thrown: /// 1. **Not putting a semicolon at the end of a line.** Every single cascade statement must end /// with a semicolon. Yes, even loops! This is because the parser needs to know when the line ends and the /// next line begins, and the semicolon is used as the delimiter. /// 2. **Not putting a operator at the beginning of a line.** Even if you are just writing a statement, /// you need to put the `|` operator at the beginning. Once again, this is due to the way Rust parses macros. /// It also means that each line of the cascade macro is consistent, with an `<operator> <statement>;` syntax. #[macro_export] macro_rules! cascade { ($i:ident : $e: expr; $($tail: tt)*) => { { let mut $i = $e; cascade!(@line $i, $($tail)*); $i }; }; ($e: expr; $($tail: tt)*) => { { let mut __tmp = $e; cascade!(@line __tmp, $($tail)*); __tmp }; }; (@line $i:ident, | $s: stmt; $($tail: tt)*) => { $s; cascade!(@line $i, $($tail)*); }; (@line $i: ident, .. $v: ident = $e: expr; $($tail: tt)*) => { $i.$v = $e; cascade!(@line $i, $($tail)*); }; (@line $i:ident, .. $v:ident += $e:expr; $($tail:tt)*) => { $i.$v += $e; cascade!(@line $i, $($tail)*); }; (@line $i:ident, .. $v:ident -= $e:expr; $($tail:tt)*) => { $i.$v -= $e; cascade!(@line $i, $($tail)*); }; (@line $i:ident, .. $v:ident *= $e:expr; $($tail:tt)*) => { $i.$v *= $e; cascade!(@line $i, $($tail)*); }; (@line $i:ident, .. $($q: ident ($($e: expr),*)).+; $($tail: tt)*) => { $i.$($q($($e),*)).+; cascade!(@line $i, $($tail)*); }; (@line $i:ident, .. $($q: ident ($($e: expr),*)).+?; $($tail: tt)*) => { $i.$($q($($e),*)).+?; cascade!(@line $i, $($tail)*); }; (@line $i:ident,) => {}; () => {} }
true
cbba3e1dc9ee2e523834a49b4bde54f1b1b5ec67
Rust
oreganoli/bfc-rs
/src/parser/cto.rs
UTF-8
4,431
3.21875
3
[ "MIT", "WTFPL" ]
permissive
#[cfg(test)] mod tests; use super::BrainfuckInstr; /// Optimizes a list of Brainfuck instructions to be less repetitive. pub fn optimize(code: &mut Vec<BrainfuckInstr>) { optimize_arithmetic(code); // dbg!(&code); /* this helped us while fixing a buggy interaction between the arithmetic and print passes the reason was we didn't push the last instruction to the instruction vector if it wasn't arithmetic 🤷 see lines 119-122 */ optimize_printing(code); } fn optimize_printing(code: &mut Vec<BrainfuckInstr>) -> () { use BrainfuckInstr::{PointerInc, PutByte, Print}; let mut last_op = match code.get(0) { Some(op) => op.clone(), None => return // no instructions to optimize }; let mut print_lvl = 0u16; let mut opt = Vec::new(); for op in code.iter() { match op { PutByte => { if print_lvl == 0 { print_lvl += 1; } else { match last_op { PointerInc => print_lvl += 1, _ => { opt.push(PutByte); print_lvl = 1 } } } }, PointerInc => { match last_op { PutByte => (), _ => { opt.push(PointerInc); print_lvl = 0; } } } other => { match print_lvl { 0 => { opt.push(other.clone()); print_lvl = 0; }, 1 => { opt.push(PutByte); opt.push(other.clone()); print_lvl = 0; }, n => { opt.push(Print(n)); opt.push(other.clone()); print_lvl = 0; } } } } last_op = op.clone(); } match print_lvl { 0 => (), 1 => { opt.push(PutByte); }, n => { opt.push(Print(n)); } } *code = opt; } /// Arithmetic optimization pass. fn optimize_arithmetic(code: &mut Vec<BrainfuckInstr>) { use BrainfuckInstr::*; // new, optimized output: let mut opt = Vec::new(); /* Yes, we're cheating to keep the same function signature. We're going to just replace `code` with the new vector. We could optimize things in place, but I tried, believe me, I did. */ // How many times the last instruction has been repeated. let mut repeats: u16 = 0; // Instruction last seen. let mut last_op = match code.get(0) { Some(op) => op.clone(), None => return // no instructions to optimize }; let last = code.len() - 1; for (index, op) in code.iter().enumerate() { if *op == last_op { repeats += 1; } if *op != last_op || index == last { if repeats > 1 { match last_op { DataDec | DataInc | PointerDec | PointerInc => { opt.push(squash_arithmetic(&last_op, repeats)); repeats = 1; }, _ => { repeats = 1; } } } else { opt.push(last_op.clone()); repeats = 1; } } last_op = op.clone(); } match last_op { DataDec | DataInc | PointerDec | PointerInc => (), _ => opt.push(last_op) }; *code = opt; } /// "Compress" standard Brainfuck arithmetic operations repeated `x` times into our own virtual ones. fn squash_arithmetic(op: &BrainfuckInstr, x: u16) -> BrainfuckInstr { use BrainfuckInstr::*; use std::cmp::min; let max_u16 = std::u16::MAX; match op { PointerDec => PointerSub(min(max_u16, x)), PointerInc => PointerAdd(min(max_u16, x)), DataDec => DataSub(min(255, x) as u8), DataInc => DataAdd(min(255, x) as u8), _ => { panic!("Tried to convert the non-arithmetic instruction {:?} into a virtual arithmetic instruction!", op) } } }
true
dbeb71161fb64531413c9a40e868ae4f30b2dc50
Rust
xantrac/status_checker
/src/lib/monitor_actor.rs
UTF-8
1,709
2.515625
3
[]
no_license
use actix::prelude::*; use std::time::Duration; const STATUS_UPDATE_INTERVAL: Duration = Duration::from_secs(5); pub struct MonitorActor { listeners: Vec<Addr<super::websocket_actor::Websocket>>, } impl Actor for MonitorActor { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { ctx.run_interval(STATUS_UPDATE_INTERVAL, |act, _ctx| { println!("Polling status..."); let listeners = act.listeners.clone(); Arbiter::spawn(async { let status = super::clients::github_status().await; for listener in listeners { listener.do_send(super::websocket_actor::StatusEvent { status: (status).to_string(), }); } }); }); } } pub struct WsRegistration { pub address: Addr<super::websocket_actor::Websocket>, } pub struct StatusUpdate { pub status: String, } impl Message for WsRegistration { type Result = (); } impl Message for StatusUpdate { type Result = (); } impl Handler<WsRegistration> for MonitorActor { type Result = (); fn handle(&mut self, msg: WsRegistration, _: &mut Context<Self>) { self.listeners.push(msg.address); } } impl Handler<StatusUpdate> for MonitorActor { type Result = (); fn handle(&mut self, msg: StatusUpdate, _: &mut Context<Self>) { for listener in &self.listeners { listener.do_send(super::websocket_actor::StatusEvent { status: (&msg.status).to_string(), }); } } } impl MonitorActor { pub fn new() -> Self { Self { listeners: vec![] } } }
true
2c5400c49bd08872a50d3ca51c2cc1f67ca04855
Rust
ijijn/rust-more-asserts
/src/lib.rs
UTF-8
14,066
3.9375
4
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
//! Small library providing some macros helpful for asserting. The API is very //! similar to the API provided by the stdlib's own `assert_eq!`, `assert_ne!`, //! `debug_assert_eq!`, or `debug_assert_ne!`. //! //! | Name | Enabled | Equivalent to | //! | -------------------- | ----------------------------- | -------------------------------------------- | //! | `assert_le!` | Always | `assert!(a <= b)` | //! | `assert_lt!` | Always | `assert!(a < b)` | //! | `assert_ge!` | Always | `assert!(a >= b)` | //! | `assert_gt!` | Always | `assert!(a > b)` | //! | `debug_assert_le!` | `if cfg!(debug_assertions)` | `debug_assert!(a <= b)` | //! | `debug_assert_lt!` | `if cfg!(debug_assertions)` | `debug_assert!(a < b)` | //! | `debug_assert_ge!` | `if cfg!(debug_assertions)` | `debug_assert!(a >= b)` | //! | `debug_assert_gt!` | `if cfg!(debug_assertions)` | `debug_assert!(a > b)` | //! | `debug_unreachable!` | `if cfg!(debug_assertions)` | `unreachable!` when debug_assertions are on. | //! //! When one of the assertions fails, it prints out a message like the following: //! //! ```text //! thread 'main' panicked at 'assertion failed: `left < right` //! left: `4`, //! right: `3`', src/main.rs:47:5 //! note: Run with `RUST_BACKTRACE=1` for a backtrace. //! ``` //! //! # Example //! //! ```rust //! #[macro_use] //! extern crate more_asserts; //! //! #[derive(Debug, PartialEq, PartialOrd)] //! enum Example { Foo, Bar } //! //! fn main() { //! assert_le!(3, 4); //! assert_ge!(10, 10, //! "You can pass a message too (just like `assert_eq!`)"); //! debug_assert_lt!(1.3, 4.5, //! "Format syntax is supported ({}).", "also like `assert_eq!`"); //! //! assert_gt!(Example::Bar, Example::Foo, //! "It works on anything that implements PartialOrd, PartialEq, and Debug!"); //! } //! ``` #![deny(missing_docs)] /// Panics if the first expression is not strictly less than the second. /// Requires that the values be comparable with `<`. /// /// On failure, panics and prints the values out in a manner similar to /// prelude's `assert_eq!`. /// /// Optionally may take an additional message to display on failure, which /// is formatted using standard format syntax. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// assert_lt!(3, 4); /// assert_lt!(3, 4, "With a message"); /// assert_lt!(3, 4, "With a formatted message: {}", "oh no"); /// } /// ``` #[macro_export] macro_rules! assert_lt { ($left:expr, $right:expr) => ({ let (left, right) = (&($left), &($right)); assert!(left < right, "assertion failed: `(left < right)`\n left: `{:?}`,\n right: `{:?}`", left, right); }); ($left:expr, $right:expr, ) => ({ assert_lt!($left, $right); }); ($left:expr, $right:expr, $($msg_args:tt)+) => ({ let (left, right) = (&($left), &($right)); assert!(left < right, "assertion failed: `(left < right)`\n left: `{:?}`,\n right: `{:?}`: {}", left, right, format_args!($($msg_args)+)); }) } /// Panics if the first expression is not strictly greater than the second. /// Requires that the values be comparable with `>`. /// /// On failure, panics and prints the values out in a manner similar to /// prelude's `assert_eq!`. /// /// Optionally may take an additional message to display on failure, which /// is formatted using standard format syntax. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// assert_gt!(5, 3); /// assert_gt!(5, 3, "With a message"); /// assert_gt!(5, 3, "With a formatted message: {}", "oh no"); /// } /// ``` #[macro_export] macro_rules! assert_gt { ($left:expr, $right:expr) => ({ let (left, right) = (&($left), &($right)); assert!(left > right, "assertion failed: `(left > right)`\n left: `{:?}`,\n right: `{:?}`", left, right); }); ($left:expr, $right:expr, ) => ({ assert_gt!($left, $right); }); ($left:expr, $right:expr, $($msg_args:tt)+) => ({ let (left, right) = (&($left), &($right)); assert!(left > right, "assertion failed: `(left > right)`\n left: `{:?}`,\n right: `{:?}`: {}", left, right, format_args!($($msg_args)+)); }) } /// Panics if the first expression is not less than or equal to the second. /// Requires that the values be comparable with `<=`. /// /// On failure, panics and prints the values out in a manner similar to /// prelude's `assert_eq!`. /// /// Optionally may take an additional message to display on failure, which /// is formatted using standard format syntax. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// assert_le!(4, 4); /// assert_le!(4, 5); /// assert_le!(4, 5, "With a message"); /// assert_le!(4, 4, "With a formatted message: {}", "oh no"); /// } /// ``` #[macro_export] macro_rules! assert_le { ($left:expr, $right:expr) => ({ let (left, right) = (&($left), &($right)); assert!(left <= right, "assertion failed: `(left <= right)`\n left: `{:?}`,\n right: `{:?}`", left, right); }); ($left:expr, $right:expr, ) => ({ assert_le!($left, $right); }); ($left:expr, $right:expr, $($msg_args:tt)+) => ({ let (left, right) = (&($left), &($right)); assert!(left <= right, "assertion failed: `(left <= right)`\n left: `{:?}`,\n right: `{:?}`: {}", left, right, format_args!($($msg_args)+)); }) } /// Panics if the first expression is not greater than or equal to the second. /// Requires that the values be comparable with `>=`. /// /// On failure, panics and prints the values out in a manner similar to /// prelude's `assert_eq!`. /// /// Optionally may take an additional message to display on failure, which /// is formatted using standard format syntax. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// assert_ge!(4, 4); /// assert_ge!(4, 3); /// assert_ge!(4, 3, "With a message"); /// assert_ge!(4, 4, "With a formatted message: {}", "oh no"); /// } /// ``` #[macro_export] macro_rules! assert_ge { ($left:expr, $right:expr) => ({ let (left, right) = (&($left), &($right)); assert!(left >= right, "assertion failed: `(left >= right)`\n left: `{:?}`,\n right: `{:?}`", left, right); }); ($left:expr, $right:expr, ) => ({ assert_ge!($left, $right); }); ($left:expr, $right:expr, $($msg_args:tt)+) => ({ let (left, right) = (&($left), &($right)); assert!(left >= right, "assertion failed: `(left >= right)`\n left: `{:?}`,\n right: `{:?}`: {}", left, right, format_args!($($msg_args)+)); }) } /// Same as `assert_lt!` in debug builds or release builds where the /// `-C debug-assertions` was provided to the compiler. For all other builds, /// vanishes without a trace. /// /// Optionally may take an additional message to display on failure, which /// is formatted using standard format syntax. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// // These are compiled to nothing if debug_assertions are off! /// debug_assert_lt!(3, 4); /// debug_assert_lt!(3, 4, "With a message"); /// debug_assert_lt!(3, 4, "With a formatted message: {}", "oh no"); /// } /// ``` #[macro_export] macro_rules! debug_assert_lt { ($($arg:tt)+) => { if cfg!(debug_assertions) { assert_lt!($($arg)+); } } } /// Same as `assert_gt!` in debug builds or release builds where the /// `-C debug-assertions` was provided to the compiler. For all other builds, /// vanishes without a trace. /// /// Optionally may take an additional message to display on failure, which /// is formatted using standard format syntax. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// // These are compiled to nothing if debug_assertions are off! /// debug_assert_gt!(5, 3); /// debug_assert_gt!(5, 3, "With a message"); /// debug_assert_gt!(5, 3, "With a formatted message: {}", "oh no"); /// } /// ``` #[macro_export] macro_rules! debug_assert_gt { ($($arg:tt)+) => { if cfg!(debug_assertions) { assert_gt!($($arg)+); } } } /// Same as `assert_le!` in debug builds or release builds where the /// `-C debug-assertions` was provided to the compiler. For all other builds, /// vanishes without a trace. /// /// Optionally may take an additional message to display on failure, which /// is formatted using standard format syntax. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// // These are compiled to nothing if debug_assertions are off! /// debug_assert_le!(4, 4); /// debug_assert_le!(4, 5); /// debug_assert_le!(4, 5, "With a message"); /// debug_assert_le!(4, 4, "With a formatted message: {}", "oh no"); /// } /// ``` #[macro_export] macro_rules! debug_assert_le { ($($arg:tt)+) => { if cfg!(debug_assertions) { assert_le!($($arg)+); } } } /// Same as `assert_ge!` in debug builds or release builds where the /// `-C debug-assertions` was provided to the compiler. For all other builds, /// vanishes without a trace. /// /// Optionally may take an additional message to display on failure, which /// is formatted using standard format syntax. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// // These are compiled to nothing if debug_assertions are off! /// debug_assert_ge!(4, 4); /// debug_assert_ge!(4, 3); /// debug_assert_ge!(4, 3, "With a message"); /// debug_assert_ge!(4, 4, "With a formatted message: {}", "oh no"); /// } /// ``` #[macro_export] macro_rules! debug_assert_ge { ($($arg:tt)+) => { if cfg!(debug_assertions) { assert_ge!($($arg)+); } } } /// Panics if reached. This is a variant of the standard library's `unreachable!` /// macro that is controlled by `cfg!(debug_assertions)`. /// /// Same as prelude's `unreachable!` in debug builds or release builds where the /// `-C debug-assertions` was provided to the compiler. For all other builds, /// vanishes without a trace. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate more_asserts; /// /// fn main() { /// // You probably wouldn't actually use this here /// let mut value = 0.5; /// if value < 0.0 { /// debug_unreachable!("Value out of range {}", value); /// value = 0.0; /// } /// } /// ``` #[macro_export] macro_rules! debug_unreachable { ($($arg:tt)*) => { if cfg!(debug_assertions) { unreachable!($($arg)*); } } } #[cfg(test)] mod tests { use std::panic::catch_unwind; #[derive(PartialOrd, PartialEq, Debug)] enum DummyType { Foo, Bar, Baz } #[test] fn test_assert_lt() { assert_lt!(3, 4); assert_lt!(4.0, 4.5); assert_lt!("a string", "b string"); assert_lt!(DummyType::Foo, DummyType::Bar, "Message with {}", "cool formatting"); let a = &DummyType::Foo; let b = &DummyType::Baz; assert_lt!(a, b); assert!(catch_unwind(|| assert_lt!(5, 3)).is_err()); assert!(catch_unwind(|| assert_lt!(5, 5)).is_err()); assert!(catch_unwind(|| assert_lt!(DummyType::Bar, DummyType::Foo)).is_err()); } #[test] fn test_assert_gt() { assert_gt!(4, 3); assert_gt!(4.5, 4.0); assert_gt!("b string", "a string"); assert_gt!(DummyType::Bar, DummyType::Foo, "Message with {}", "cool formatting"); let a = &DummyType::Foo; let b = &DummyType::Baz; assert_gt!(b, a); assert!(catch_unwind(|| assert_gt!(3, 5)).is_err()); assert!(catch_unwind(|| assert_gt!(5, 5)).is_err()); assert!(catch_unwind(|| assert_gt!(DummyType::Foo, DummyType::Bar)).is_err()); } #[test] fn test_assert_le() { assert_le!(3, 4); assert_le!(4, 4); assert_le!(4.0, 4.5); assert_le!("a string", "a string"); assert_le!("a string", "b string"); assert_le!(DummyType::Foo, DummyType::Bar, "Message"); assert_le!(DummyType::Foo, DummyType::Foo, "Message with {}", "cool formatting"); let a = &DummyType::Foo; let b = &DummyType::Baz; assert_le!(a, a); assert_le!(a, b); assert!(catch_unwind(|| assert_le!(5, 3)).is_err()); assert!(catch_unwind(|| assert_le!(DummyType::Bar, DummyType::Foo)).is_err()); } #[test] fn test_assert_ge() { assert_ge!(4, 3); assert_ge!(4, 4); assert_ge!(4.5, 4.0); assert_ge!(5.0, 5.0); assert_ge!("a string", "a string"); assert_ge!("b string", "a string"); assert_ge!(DummyType::Bar, DummyType::Bar, "Example"); assert_ge!(DummyType::Bar, DummyType::Foo, "Message with {}", "cool formatting"); let a = &DummyType::Foo; let b = &DummyType::Baz; assert_ge!(a, a); assert_ge!(b, a); assert!(catch_unwind(|| assert_ge!(3, 5)).is_err()); assert!(catch_unwind(|| assert_ge!(DummyType::Foo, DummyType::Bar)).is_err()); } // @@TODO: how to test the debug macros? }
true