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
51457d63f7b6e78e9cdf23aaecd2516628cd37a6
Rust
sshashank124/graphite
/src/core/interpolate.rs
UTF-8
1,207
2.8125
3
[]
no_license
use std::ops::{Add, Mul}; use super::*; #[derive(Clone, Copy, Debug)] #[cfg_attr(feature="serde-derive", derive(Deserialize, Serialize))] pub struct LinearScale; #[derive(Clone, Copy, Debug)] #[cfg_attr(feature="serde-derive", derive(Deserialize, Serialize))] pub struct PowerScale; #[derive(Clone, Copy, Debug)] #[cfg_attr(feature="serde-derive", derive(Deserialize, Serialize))] pub struct SmoothScale; pub trait Interp<A> { fn interp(a: A2<A>, t: F) -> A; } impl<A> Interp<A> for LinearScale where A2<A>: Mul<F2, Output = A2<A>>, A: Copy + Zero + Add<Output = A> { #[inline(always)] fn interp(a: A2<A>, t: F) -> A { A2::dot(a, A2(1. - t, t)) } } impl<A> Interp<A> for SmoothScale where A: Copy + Zero + Add<Output = A> + Mul<F, Output = A> { #[inline(always)] fn interp(a: A2<A>, t: F) -> A { LinearScale::interp(a, t.sq() * (3. - 2. * t)) } } pub trait Balance { fn balance(a: F2) -> F; fn balance2(a: F, b: F) -> F { Self::balance(A2(a, b)) } } impl Balance for LinearScale { #[inline(always)] fn balance(a: F2) -> F { a[0] / a.sum() } } impl Balance for PowerScale { #[inline(always)] fn balance(a: F2) -> F { LinearScale::balance(a.map(F::sq)) } }
true
05d47fd77920488cd285a1801cf488ef785ac305
Rust
Patryk27/avr-tester
/avr-tester/src/components/component_handle.rs
UTF-8
819
3.09375
3
[ "MIT" ]
permissive
use super::*; use std::{cell::RefCell, rc::Rc}; pub struct ComponentHandle { state: Rc<RefCell<ComponentState>>, } impl ComponentHandle { pub(crate) fn new(state: Rc<RefCell<ComponentState>>) -> Self { Self { state } } /// Pauses component until [`Self::resume()`] is called. pub fn pause(&self) { *self.state.borrow_mut() = ComponentState::Paused; } /// Resumes component paused through [`Self::pause()`]. pub fn resume(&self) { *self.state.borrow_mut() = ComponentState::Working; } /// Removes component, preventing it from running again. pub fn remove(self) { *self.state.borrow_mut() = ComponentState::Removed; } /// Returns component's state. pub fn state(&self) -> ComponentState { *self.state.borrow() } }
true
c21f615422567336a30b30007ee077da0bf8095e
Rust
alexandrejanin/rust-chess
/src/game.rs
UTF-8
6,629
3.34375
3
[]
no_license
use cuivre::{ graphics::sprites::{Sprite, SpriteSheet}, maths::Vector3f, transform::Transform, }; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Team { White, Black, } impl Team { fn piece(self, id: i32, x: usize, y: usize) -> Piece { Piece { team: self, id, x, y: self.get_row(y), alive: true, } } fn get_row(self, row: usize) -> usize { match self { Team::White => row, Team::Black => 7 - row, } } } #[derive(Debug, PartialEq, Eq)] enum MoveType { MoveOnly, CaptureOnly, MoveAndCapture, } /// Represents a move that could be executed by a piece, /// but has to be checked for validity before being used. #[derive(Debug)] pub struct MoveAttempt { source_x: usize, source_y: usize, target_x: i32, target_y: i32, move_type: MoveType, } /// Represents a valid move that can be executed by a piece. #[derive(Debug)] pub struct Move { source_x: usize, source_y: usize, target_x: usize, target_y: usize, } impl Move { pub fn target_pos(&self) -> (usize, usize) { (self.target_x, self.target_y) } } #[derive(Debug)] pub struct Piece { team: Team, id: i32, x: usize, y: usize, alive: bool, } impl Piece { pub fn sprite<'s>(&self, sheet: &'s SpriteSheet) -> Sprite<'s> { // Sprite row let y = match self.team { Team::White => 0, Team::Black => 1, }; sheet.sprite(self.id, y) } pub fn transform(&self) -> Transform { Transform::from_position(Vector3f::new(self.x as f32 + 0.5, self.y as f32 + 0.5, 1.0)) } // Creates a move attempt, relative to the current position. fn move_attempt(&self, x: i32, y: i32, move_type: MoveType) -> MoveAttempt { MoveAttempt { source_x: self.x, source_y: self.y, target_x: self.x as i32 + x, target_y: self.y as i32 + y, move_type, } } fn moves(&self, manager: &PiecesManager) -> Vec<Move> { // A list of possible moves that need to be validated. let mut move_tries = Vec::new(); let dir = match self.team { Team::White => 1, Team::Black => -1, }; match self.id { // Pawn 0 => { // Move forward move_tries.push(self.move_attempt(0, dir, MoveType::MoveOnly)); // Move 2 tiles forward if self.y == self.team.get_row(1) { move_tries.push(self.move_attempt(0, 2 * dir, MoveType::MoveOnly)); } // Diagonal capture for &x in &[self.x as i32 + 1, self.x as i32 - 1] { move_tries.push(self.move_attempt(x, dir, MoveType::CaptureOnly)) } } _ => {} } move_tries .iter() .filter_map(|ref move_attempt| { // Check bounds if move_attempt.target_x < 0 || move_attempt.target_x >= 8 || move_attempt.target_y < 0 || move_attempt.target_y >= 8 { return None; } let target_x = move_attempt.target_x as usize; let target_y = move_attempt.target_y as usize; // Check for pieces on the target tile if let Some(other_piece) = manager.piece_by_pos(target_x, target_y) { if other_piece.team == self.team { return None; } else if move_attempt.move_type == MoveType::MoveOnly { return None; } } else if move_attempt.move_type == MoveType::CaptureOnly { return None; } Some(Move { target_x, target_y, source_x: move_attempt.source_x, source_y: move_attempt.source_y, }) }) .collect() } } pub type PieceIndex = usize; pub struct PiecesManager { pieces: Vec<Piece>, selected_piece_index: Option<PieceIndex>, } impl PiecesManager { pub fn new() -> Self { let mut pieces = Vec::new(); for team in &[Team::White, Team::Black] { //Pawns for i in 0..8 { pieces.push(team.piece(0, i, 1)) } //Knights pieces.push(team.piece(1, 1, 0)); pieces.push(team.piece(1, 6, 0)); //Bishops pieces.push(team.piece(2, 2, 0)); pieces.push(team.piece(2, 5, 0)); //Rooks pieces.push(team.piece(3, 0, 0)); pieces.push(team.piece(3, 7, 0)); //Queen pieces.push(team.piece(4, 3, 0)); //King pieces.push(team.piece(5, 4, 0)); } Self { pieces, selected_piece_index: None, } } pub fn pieces(&self) -> Vec<&Piece> { self.pieces.iter().filter(|piece| piece.alive).collect() } fn piece(&self, index: PieceIndex) -> &Piece { self.pieces .get(index) .unwrap_or_else(|| panic!("No piece found for index {}", index)) } pub fn piece_by_pos(&self, x: usize, y: usize) -> Option<&Piece> { self.piece_index_by_pos(x, y).map(|index| self.piece(index)) } fn piece_index_by_pos(&self, x: usize, y: usize) -> Option<PieceIndex> { for (index, piece) in self.pieces.iter().enumerate() { if piece.alive && piece.x == x && piece.y == y { return Some(index); } } None } pub fn selected_moves(&self) -> Vec<Move> { match &self.selected_piece_index { None => Vec::new(), Some(piece) => self.piece(*piece).moves(self), } } pub fn on_click(&mut self, x: usize, y: usize) { if x >= 8 || y >= 8 { self.selected_piece_index = None; } else { if let Some(selected_move) = self .selected_moves() .iter() .find(|mov| mov.target_pos() == (x, y)) { //TODO: Move piece } else { self.selected_piece_index = self.piece_index_by_pos(x, y) } } } }
true
05869e032c9e245d64a8b130d03e3bd7e7f5209a
Rust
1148118271/redis_rs
/src/redis_instance.rs
UTF-8
1,870
3
3
[]
no_license
use crate::tcp::Client; use tokio::io; use std::rc::Rc; mod constant { pub const CRLF: &'static str = "\r\n"; pub const LIST_SYMBOL: &'static str = "*"; pub const STR_SYMBOL: &'static str = "$"; } pub struct RedisInstance(Client); pub type Instance = RedisInstance; impl RedisInstance { pub fn init(c: Client) -> Instance { RedisInstance(c) } pub async fn login(&self, pass: &str) -> io::Result<()> { self.assembly_and_send(&["AUTH", pass]).await?; Ok(()) } pub async fn assembly_and_send(&self, data: &[&str]) -> io::Result<Vec<u8>> { let mut params = String::from(constant::LIST_SYMBOL); params += &data.len().to_string(); params += constant::CRLF; for x in data { params += constant::STR_SYMBOL; params += &(*x.len().to_string()); params += constant::CRLF; params += *x; params += constant::CRLF; } println!("Client -> {}", &params); self.0.write(params.as_bytes()).await?; let mut v = vec![0; 2048]; self.0.read(&mut v).await?; let rc = Rc::new(v); let str = unsafe { String::from_utf8_unchecked(Rc::clone(&rc).to_vec()) }; println!("Server -> {}", str); Ok(Rc::clone(&rc).to_vec()) } // // 43 / 45 // pub async fn push_str(&self, k: &str, v: &str) -> io::Result<State> { // let vec = self.assembly_and_send(&["SET", k, v]).await?; // Ok(validation(&vec)) // } // // // pub async fn push_list(&self, k: &str, v: &[&str]) -> io::Result<State> { // let mut arr = vec![]; // arr.push("lpush"); // arr.push(k); // arr.extend_from_slice(v); // let vec = self.assembly_and_send(&arr).await?; // Ok(validation(&vec)) // } }
true
2ea243294bdaeeb5383be3225066a1de2fb6df86
Rust
reiya-hanai/aoj-book-in-rust
/alds1_7_c_tree_walk/src/main.rs
UTF-8
4,809
2.8125
3
[]
no_license
#![allow(unused_macros)] // ---------------------------------------------------------------------------------------------------- // input macro by @tanakh https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 // ---------------------------------------------------------------------------------------------------- macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes .by_ref() .map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; } macro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; } macro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>() }; ($next:expr, chars) => { read_value!($next, String).chars().collect::<Vec<char>>() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect("Parse error") }; } // ---------------------------------------------------------------------------------------------------- // IO util // ---------------------------------------------------------------------------------------------------- #[allow(dead_code)] fn print_vec<T: ToString>(v: &Vec<T>, sep: &str) { println!( "{}", v.iter() .map(|t| t.to_string()) .collect::<Vec<_>>() .join(sep) ); } // ---------------------------------------------------------------------------------------------------- // main code // ---------------------------------------------------------------------------------------------------- #[derive(Debug)] struct BinaryTree { size: usize, parent: Vec<Option<usize>>, left: Vec<Option<usize>>, right: Vec<Option<usize>>, } impl BinaryTree { fn new(n: usize) -> Self { BinaryTree { size: n, parent: vec![None; n], left: vec![None; n], right: vec![None; n], } } fn get_root(&self) -> usize { let roots = self .parent .iter() .enumerate() .filter(|(_, v)| v.is_none()) .collect::<Vec<_>>(); debug_assert!(roots.len() == 1); roots[0].0 } fn reconstruct(&mut self, preorder: &mut Vec<usize>, inorder: &mut Vec<usize>, parent: Option<usize>) { assert_eq!(preorder.len(), inorder.len()); if preorder.len() == 0 { return } let subroot = preorder[0]; self.parent[subroot] = parent; let idx = inorder.iter().position(|x| *x==subroot).unwrap(); let mut pre_left = preorder.split_off(1); let mut pre_right = pre_left.split_off(idx); if pre_left.len() > 0 { self.left[subroot] = Some(pre_left[0]); } if pre_right.len() > 0 { self.right[subroot] = Some(pre_right[0]); } let mut in_left = inorder; let mut in_right = in_left.split_off(idx); let mut in_right = in_right.split_off(1); self.reconstruct(&mut pre_left, &mut in_left, Some(subroot)); self.reconstruct(&mut pre_right, &mut in_right, Some(subroot)); } fn walk_postorder(&self, node_id: usize, result: &mut Vec<usize>) { if let Some(left) = self.left[node_id] { self.walk_postorder(left as usize, result); } if let Some(right) = self.right[node_id] { self.walk_postorder(right as usize, result); } result.push(node_id + 1); } } fn solve(n: usize, preorder: &mut Vec<usize>, inorder: &mut Vec<usize>) { let mut tree = BinaryTree::new(n); tree.reconstruct(preorder, inorder, None); let root = tree.get_root(); let mut result = Vec::new(); tree.walk_postorder(root, &mut result); print_vec(&result, " "); } fn main() { input! { n: usize, preorder: [usize1; n], inorder: [usize1; n], } let mut preorder = preorder; let mut inorder = inorder; solve(n, &mut preorder, &mut inorder); }
true
22696c136a405a519c00687596b519f41b58eb5d
Rust
ejfamanas/rust-training
/data_structures/enumerations/src/main.rs
UTF-8
562
3.546875
4
[]
no_license
enum Color { Red, Green, Blue, RgbColor(u8, u8, u8), // WOW this is cool CmykColor{cyan:u8, magenta: u8, yellow: u8, black:u8} } fn enums() { let color:Color = Color::RgbColor(0,0,0); match color { Color::Red => println!("r"), Color::Green => println!("g"), Color::Blue => println!("b"), Color::RgbColor(0,0,0) | Color::CmykColor {cyan:0, magenta: 0, yellow: 0, black: 0} => println!("black"), _ => println!("another color") } } fn main() { println!("Hello, world!"); enums(); }
true
f075476c7d887ead494a90dd17d08195e982c2b7
Rust
whoiscc/auto
/src/re.rs
UTF-8
4,420
2.953125
3
[]
no_license
use crate::nfa::{NFAutoBlueprint, NFAutoBuilder}; use std::hash::Hash; use std::mem; enum RePriv<T> { Plain(T), ZeroOrMore(Box<RePriv<T>>), Concat(Box<RePriv<T>>, Box<RePriv<T>>), Either(Box<RePriv<T>>, Box<RePriv<T>>), Wildcard, } pub struct Re<T>(RePriv<T>); impl<T> RePriv<T> where T: Eq + Hash + Clone, { pub fn compile(self) -> NFAutoBlueprint<u64, T> { let mut builder = NFAutoBuilder::start(0).accept(1); let mut counter = 2; self.recursive_compile(&mut builder, &mut counter, 0, 1); builder.finalize() } fn recursive_compile( self, builder: &mut NFAutoBuilder<u64, T>, counter: &mut u64, left: u64, right: u64, ) { match self { RePriv::Plain(trans) => { update_builder(builder, |b| b.connect(left, trans, right)); } RePriv::ZeroOrMore(inner) => { let (inner_left, inner_right) = (*counter, *counter + 1); *counter += 2; update_builder(builder, |b| { b.connect_void(left, inner_left) .connect_void(inner_right, right) .connect_void(inner_right, inner_left) .connect_void(left, right) }); inner.recursive_compile(builder, counter, inner_left, inner_right); } RePriv::Concat(first, second) => { let middle = *counter; *counter += 1; first.recursive_compile(builder, counter, left, middle); second.recursive_compile(builder, counter, middle, right); } RePriv::Either(first, second) => { let (first_left, first_right, second_left, second_right) = (*counter, *counter + 1, *counter + 2, *counter + 3); *counter += 4; update_builder(builder, |b| { b.connect_void(left, first_left) .connect_void(left, second_left) .connect_void(first_right, right) .connect_void(second_right, right) }); first.recursive_compile(builder, counter, first_left, first_right); second.recursive_compile(builder, counter, second_left, second_right); } RePriv::Wildcard => { update_builder(builder, |b| b.connect_wildcard(left, right)); } } } } fn update_builder<T, F>(builder_mut: &mut NFAutoBuilder<u64, T>, updater: F) where T: Hash + Eq, F: FnOnce(NFAutoBuilder<u64, T>) -> NFAutoBuilder<u64, T>, { let mut updated = updater(mem::replace(builder_mut, Default::default())); mem::swap(builder_mut, &mut updated); } impl<T> Re<T> { pub fn plain(trans: T) -> Self { Self(RePriv::Plain(trans)) } pub fn zero_or_more(inner: Self) -> Self { Self(RePriv::ZeroOrMore(Box::new(inner.0))) } pub fn concat(first: Self, second: Self) -> Self { Self(RePriv::Concat(Box::new(first.0), Box::new(second.0))) } pub fn either(first: Self, second: Self) -> Self { Self(RePriv::Either(Box::new(first.0), Box::new(second.0))) } pub fn wildcard() -> Self { Self(RePriv::Wildcard) } } impl<T> Re<T> where T: Eq + Hash + Clone, { pub fn compile(self) -> NFAutoBlueprint<u64, T> { self.0.compile() } } #[cfg(test)] mod tests { use super::*; #[test] fn compile_and_match() { // (a|b)*c let bp = Re::concat( Re::zero_or_more(Re::either(Re::plain('a'), Re::plain('b'))), Re::plain('c'), ) .compile(); let mut nfa = bp.create(); for c in "ababbabc".chars() { assert!(!nfa.is_accepted()); nfa.trigger(&c); assert!(!nfa.is_dead()); } assert!(nfa.is_accepted()); nfa.trigger(&'d'); assert!(nfa.is_dead()); } #[test] fn auto_trait_test() { use crate::auto::Auto; let bp = Re::concat( Re::zero_or_more(Re::either(Re::plain('a'), Re::plain('b'))), Re::plain('c'), ) .compile(); assert!(bp.create().test("ababbabc".chars())); assert!(!bp.create().test("ababbabd".chars())); } }
true
22f249ab7c52262c72df14a42f4989083d7fe807
Rust
growingspaghetti/my-thread-coroutine-nonblockingio-scrapbox
/rs-tokio/src/bin/main8.rs
UTF-8
797
2.96875
3
[]
no_license
// https://docs.rs/tokio/0.2.11/tokio/time/fn.timeout.html // https://docs.rs/tokio/0.2.11/src/tokio/time/delay.rs.html#81-99 impl Future for Delay fn type_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } #[tokio::main] async fn main() { // tokio::time::delay::Delay println!("{}", type_of(tokio::time::delay_for(std::time::Duration::from_secs(1)))); // let future = tokio::time::delay_for(std::time::Duration::from_secs(1)) is fine though let future = async { tokio::time::delay_for(std::time::Duration::from_secs(1)).await; // I mean lengthy calc block }; if let Err(e) = tokio::time::timeout(std::time::Duration::from_millis(500), future).await { // Elapsed(()) println!("did not receive value within 500 ms. {:?}", e); } }
true
17f0f5942ec69d2fb2f6fc2be78dbc0250a78935
Rust
chromium/chromium
/third_party/rust/syn/v1/crate/src/parse_quote.rs
UTF-8
5,167
3.453125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0", "GPL-1.0-or-later", "LGPL-2.0-or-later", "BSD-3-Clause" ]
permissive
/// Quasi-quotation macro that accepts input like the [`quote!`] macro but uses /// type inference to figure out a return type for those tokens. /// /// [`quote!`]: https://docs.rs/quote/1.0/quote/index.html /// /// The return type can be any syntax tree node that implements the [`Parse`] /// trait. /// /// [`Parse`]: crate::parse::Parse /// /// ``` /// use quote::quote; /// use syn::{parse_quote, Stmt}; /// /// fn main() { /// let name = quote!(v); /// let ty = quote!(u8); /// /// let stmt: Stmt = parse_quote! { /// let #name: #ty = Default::default(); /// }; /// /// println!("{:#?}", stmt); /// } /// ``` /// /// *This macro is available only if Syn is built with the `"parsing"` feature, /// although interpolation of syntax tree nodes into the quoted tokens is only /// supported if Syn is built with the `"printing"` feature as well.* /// /// # Example /// /// The following helper function adds a bound `T: HeapSize` to every type /// parameter `T` in the input generics. /// /// ``` /// use syn::{parse_quote, Generics, GenericParam}; /// /// // Add a bound `T: HeapSize` to every type parameter T. /// fn add_trait_bounds(mut generics: Generics) -> Generics { /// for param in &mut generics.params { /// if let GenericParam::Type(type_param) = param { /// type_param.bounds.push(parse_quote!(HeapSize)); /// } /// } /// generics /// } /// ``` /// /// # Special cases /// /// This macro can parse the following additional types as a special case even /// though they do not implement the `Parse` trait. /// /// - [`Attribute`] — parses one attribute, allowing either outer like `#[...]` /// or inner like `#![...]` /// - [`Punctuated<T, P>`] — parses zero or more `T` separated by punctuation /// `P` with optional trailing punctuation /// - [`Vec<Stmt>`] — parses the same as `Block::parse_within` /// /// [`Vec<Stmt>`]: Block::parse_within /// /// # Panics /// /// Panics if the tokens fail to parse as the expected syntax tree type. The /// caller is responsible for ensuring that the input tokens are syntactically /// valid. #[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "printing"))))] #[macro_export] macro_rules! parse_quote { ($($tt:tt)*) => { $crate::parse_quote::parse($crate::__private::quote::quote!($($tt)*)) }; } /// This macro is [`parse_quote!`] + [`quote_spanned!`][quote::quote_spanned]. /// /// Please refer to each of their documentation. /// /// # Example /// /// ``` /// use quote::{quote, quote_spanned}; /// use syn::spanned::Spanned; /// use syn::{parse_quote_spanned, ReturnType, Signature}; /// /// // Changes `fn()` to `fn() -> Pin<Box<dyn Future<Output = ()>>>`, /// // and `fn() -> T` to `fn() -> Pin<Box<dyn Future<Output = T>>>`, /// // without introducing any call_site() spans. /// fn make_ret_pinned_future(sig: &mut Signature) { /// let ret = match &sig.output { /// ReturnType::Default => quote_spanned!(sig.paren_token.span=> ()), /// ReturnType::Type(_, ret) => quote!(#ret), /// }; /// sig.output = parse_quote_spanned! {ret.span()=> /// -> ::std::pin::Pin<::std::boxed::Box<dyn ::std::future::Future<Output = #ret>>> /// }; /// } /// ``` #[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "printing"))))] #[macro_export] macro_rules! parse_quote_spanned { ($span:expr=> $($tt:tt)*) => { $crate::parse_quote::parse($crate::__private::quote::quote_spanned!($span=> $($tt)*)) }; } //////////////////////////////////////////////////////////////////////////////// // Can parse any type that implements Parse. use crate::parse::{Parse, ParseStream, Parser, Result}; use proc_macro2::TokenStream; // Not public API. #[doc(hidden)] pub fn parse<T: ParseQuote>(token_stream: TokenStream) -> T { let parser = T::parse; match parser.parse2(token_stream) { Ok(t) => t, Err(err) => panic!("{}", err), } } // Not public API. #[doc(hidden)] pub trait ParseQuote: Sized { fn parse(input: ParseStream) -> Result<Self>; } impl<T: Parse> ParseQuote for T { fn parse(input: ParseStream) -> Result<Self> { <T as Parse>::parse(input) } } //////////////////////////////////////////////////////////////////////////////// // Any other types that we want `parse_quote!` to be able to parse. use crate::punctuated::Punctuated; #[cfg(any(feature = "full", feature = "derive"))] use crate::{attr, Attribute}; #[cfg(feature = "full")] use crate::{Block, Stmt}; #[cfg(any(feature = "full", feature = "derive"))] impl ParseQuote for Attribute { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Token![#]) && input.peek2(Token![!]) { attr::parsing::single_parse_inner(input) } else { attr::parsing::single_parse_outer(input) } } } impl<T: Parse, P: Parse> ParseQuote for Punctuated<T, P> { fn parse(input: ParseStream) -> Result<Self> { Self::parse_terminated(input) } } #[cfg(feature = "full")] impl ParseQuote for Vec<Stmt> { fn parse(input: ParseStream) -> Result<Self> { Block::parse_within(input) } }
true
691ec85a077529041df6295e21dc21828bade04f
Rust
danbugs/danlogs
/Rust/The Rust Programming Language - Tutorials/chapter15/rc-refcell/src/main.rs
UTF-8
592
2.875
3
[]
no_license
#![allow(dead_code)] use std::rc::{Rc, Weak}; use std::cell::RefCell; #[derive(Debug)] struct Node { val: i32, points_to: Option<Weak<RefCell<Node>>>, } fn main() { let n2 = Rc::new(RefCell::new(Node { val: 2, points_to: None })); let n1 = Rc::new(RefCell::new(Node { val: 1, points_to: Some(Rc::downgrade(&n2)) })); n2.borrow_mut().points_to = Some(Rc::downgrade(&n1)); dbg!(Rc::weak_count(&n1)); dbg!(Rc::weak_count(&n2)); // std::mem::drop(n1); dbg!(Rc::weak_count(&n2)); dbg!(&n2); dbg!(n2.borrow().points_to.as_ref().unwrap().upgrade()); }
true
4738cde2ba8f02ea86128c01fa4805676660c58f
Rust
r-novel/webrtc-1
/dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.rs
UTF-8
3,191
2.65625
3
[ "MIT" ]
permissive
use super::*; use crate::crypto::crypto_gcm::*; use crate::prf::*; //use std::sync::Arc; //use tokio::sync::Mutex; //use async_trait::async_trait; #[derive(Clone)] pub struct CipherSuiteTLSEcdheEcdsaWithAes128GcmSha256 { gcm: Option<CryptoGcm>, //Arc<Mutex<Option<CryptoGcm>>>, } impl CipherSuiteTLSEcdheEcdsaWithAes128GcmSha256 { const PRF_MAC_LEN: usize = 0; const PRF_KEY_LEN: usize = 16; const PRF_IV_LEN: usize = 4; } impl Default for CipherSuiteTLSEcdheEcdsaWithAes128GcmSha256 { fn default() -> Self { CipherSuiteTLSEcdheEcdsaWithAes128GcmSha256 { gcm: None, //Arc::new(Mutex::new(None)), } } } //#[async_trait] impl CipherSuite for CipherSuiteTLSEcdheEcdsaWithAes128GcmSha256 { fn to_string(&self) -> String { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256".to_owned() } fn id(&self) -> CipherSuiteID { CipherSuiteID::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 } fn certificate_type(&self) -> ClientCertificateType { ClientCertificateType::ECDSASign } fn hash_func(&self) -> CipherSuiteHash { CipherSuiteHash::SHA256 } fn is_psk(&self) -> bool { false } /*async*/ fn is_initialized(&self) -> bool { //let gcm = self.gcm.lock().await; self.gcm.is_some() } /*async*/ fn init( &mut self, master_secret: &[u8], client_random: &[u8], server_random: &[u8], is_client: bool, ) -> Result<(), Error> { let keys = prf_encryption_keys( master_secret, client_random, server_random, CipherSuiteTLSEcdheEcdsaWithAes128GcmSha256::PRF_MAC_LEN, CipherSuiteTLSEcdheEcdsaWithAes128GcmSha256::PRF_KEY_LEN, CipherSuiteTLSEcdheEcdsaWithAes128GcmSha256::PRF_IV_LEN, self.hash_func(), )?; //let mut gcm = self.gcm.lock().await; if is_client { self.gcm = Some(CryptoGcm::new( &keys.client_write_key, &keys.client_write_iv, &keys.server_write_key, &keys.server_write_iv, )); } else { self.gcm = Some(CryptoGcm::new( &keys.server_write_key, &keys.server_write_iv, &keys.client_write_key, &keys.client_write_iv, )); } Ok(()) } /*async*/ fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result<Vec<u8>, Error> { //let mut gcm = self.gcm.lock().await; if let Some(cg) = &self.gcm { cg.encrypt(pkt_rlh, raw) } else { Err(Error::new( "CipherSuite has not been initialized, unable to encrypt".to_owned(), )) } } /*async*/ fn decrypt(&self, input: &[u8]) -> Result<Vec<u8>, Error> { //let mut gcm = self.gcm.lock().await; if let Some(cg) = &self.gcm { cg.decrypt(input) } else { Err(Error::new( "CipherSuite has not been initialized, unable to decrypt".to_owned(), )) } } }
true
b7df2f370b1553c7f8e4bce73a9ec44336304a33
Rust
ytyaru/Rust.While.20190601134837
/src/main.rs
UTF-8
181
2.6875
3
[ "CC0-1.0" ]
permissive
/* * Rustでwhile。 * CreatedAt: 2019-06-01 */ fn main() { let mut count = 0; while count < 10 { println!("while count {}", count); count += 1; } }
true
8c12bf42a8b7ccaa3224ce9f8b9f359395534629
Rust
innerop/wireguard-p2p
/src/exchange/args.rs
UTF-8
1,765
2.78125
3
[]
no_license
use clap::App; use clap::Arg; pub struct CmdExchangeArgs { pub netns: Option<String>, pub ifname: Option<String>, pub verbose: bool, pub dht_port: u16, pub bootstrap_addrs: String, } impl CmdExchangeArgs { pub fn parse() -> CmdExchangeArgs { let m = App::new("wg-exchange") .version("0.1.990") .about("Exchange WireGuard public keys") .arg(Arg::with_name("verbose") .short("v") .long("verbose") .help("Be more verbose")) .arg(Arg::with_name("dht_port") .short("D") .long("dht") .default_value("4222") .help("Client port for OpenDHT")) .arg(Arg::with_name("dht_supernode") .short("B") .long("bootstrap") .help("Bootstrap using this OpenDHT supernode") .default_value("bootstrap.ring.cx:4222")) .arg(Arg::with_name("netns") .help("Linux network namespace of the WireGuard interface [default: none]") .short("N") .long("netns") .takes_value(true)) .arg(Arg::with_name("ifname") .help("Network interface to manage") .short("i") .long("iface") .takes_value(true)) .get_matches(); CmdExchangeArgs { verbose: m.is_present("verbose"), ifname: m.value_of("ifname").map(|s| s.to_string()), netns: m.value_of("netns").map(|s| s.to_string()), dht_port: value_t!(m, "dht_port", u16).unwrap(), bootstrap_addrs: value_t!(m, "dht_supernode", String).unwrap(), } } }
true
43e9470ad9375efd4f8ae4505149fb5b42e7e52d
Rust
ngynkvn/rustide
/src/layout.rs
UTF-8
6,486
3
3
[]
no_license
use std::collections::HashMap; use cassowary::strength::*; use cassowary::WeightedRelation::*; use cassowary::{Constraint, Solver, Variable}; use eframe::egui::Ui; use eframe::egui::{self, Direction, Pos2}; #[derive(Debug)] pub struct Rect { x: f32, y: f32, w: f32, h: f32, } impl Rect { /// Returns the x-coordinate for the left side of the rectangle. fn left(&self) -> f32 { self.x } /// Returns the x-coordinate for the right side of the rectangle. fn right(&self) -> f32 { self.x + self.w } /// Returns the y-coordinate for the top side of the rectangle. fn top(&self) -> f32 { self.y } /// Returns the y-coordinate for the bottom side of the rectangle. fn bottom(&self) -> f32 { self.y + self.h } } impl From<(u32, u32, u32, u32)> for Rect { fn from((x, y, w, h): (u32, u32, u32, u32)) -> Self { Rect { x: x as f32, y: y as f32, w: w as f32, h: h as f32, } } } impl From<egui::Rect> for Rect { fn from(rect: egui::Rect) -> Self { let egui::Rect { min: Pos2 { x, y }, max: Pos2 { x: w, y: h }, } = rect; Rect { x: x as f32, y: y as f32, w: w as f32, h: h as f32, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum LayoutConstraint { Percentage(u16), Ratio(u32, u32), Length(u16), Max(u16), Min(u16), } macro_rules! var_struct { ($name: ident, { $($e: ident),* }) => { struct $name { $($e: cassowary::Variable,)* }; impl Default for $name { fn default() -> Self { Self { $($e: cassowary::Variable::new(),)* } } }; }; } macro_rules! var_map { ($($e:expr, $l:literal),*) => { { let mut hm: HashMap<cassowary::Variable, String> = std::collections::HashMap::new(); $(hm.insert($e, $l.into());)* hm } }; } //https://github.com/fdehau/tui-rs/blob/4e76bfa2ca8eb51719d611bb8d3d4094ab8ba398/src/layout.rs pub struct Layout { direction: Direction, constraints: Vec<LayoutConstraint>, } impl Layout { fn default() -> Self { Self { direction: Direction::LeftToRight, constraints: Vec::new(), } } fn constraints<C: Into<Vec<LayoutConstraint>>>(mut self, constraints: C) -> Self { self.constraints = constraints.into(); self } fn solve(area: Rect, layout: &Layout) -> Vec<Rect> { dbg!(area); dbg!(&layout.constraints); let mut solver = Solver::new(); let mut variables: HashMap<Variable, (usize, usize)> = HashMap::new(); // solver.add_constraints(&layout.constraints); vec![Rect::from((0, 0, 5, 5))] } /// Chunks provide the portion of space they should take from the layout /// i.e. [1, 4] should map to: /// /// `chunk[0]` having 1/5 space, and /// `chunk[1]` having 4/5 space. pub fn horizontal(ctx: &egui::Context, area: Rect, chunks: &[f32]) -> Self { let mut solver = Solver::new(); var_struct!(LeftRightBounds, {left, right}); let area_bounds = LeftRightBounds::default(); solver .add_constraints(&[ area_bounds.left | EQ(REQUIRED) | area.left(), area_bounds.right | EQ(REQUIRED) | area.right(), ]) .unwrap(); let total: f32 = chunks.iter().sum(); let mut curr = 0.0; let bounds = chunks.iter().map(|numerator| LeftRightBounds::default()); for (i, numerator) in chunks.iter().enumerate() { let bounds = LeftRightBounds::default(); let partial_area = (*numerator) / total; println!("{} {} {}", i, numerator, partial_area * area.w); #[rustfmt::skip] solver.add_constraints(&[ bounds.right - bounds.left |EQ(STRONG)| partial_area * area.w, bounds.left |GE(REQUIRED)| curr * area.w, bounds.right |GE(REQUIRED)| bounds.left, ]).unwrap(); curr += partial_area; } Self { direction: Direction::LeftToRight, constraints: vec![], // constraints: chunks.into(), } } } #[cfg(test)] mod test { use std::collections::HashMap; use cassowary::strength::REQUIRED; use cassowary::strength::WEAK; use cassowary::Solver; use cassowary::Variable; use cassowary::WeightedRelation::*; use super::Layout; use super::Rect; #[test] fn side_by_side() { let mut solver = Solver::new(); let area = Rect::from((0, 0, 20, 20)); let box1 = Rect::from((0, 0, 10, 10)); let box2 = Rect::from((0, 0, 10, 10)); struct Element { left: Variable, right: Variable, } let area = Element { left: Variable::new(), right: Variable::new(), }; let box1 = Element { left: Variable::new(), right: Variable::new(), }; let box2 = Element { left: Variable::new(), right: Variable::new(), }; let map = var_map! { area.left, "area.left", area.right, "area.right", box2.right, "box2.right", box2.left, "box2.left", box1.right, "box1.right", box1.left, "box1.left" }; #[rustfmt::skip] solver.add_constraints(&[ area.right |EQ(REQUIRED)| 20.0, area.left |EQ(REQUIRED)| 0.0, box1.left |EQ(REQUIRED)| 0.0, box2.right |EQ(REQUIRED)| area.right, box2.left |GE(REQUIRED)| box1.right, box2.left |GE(REQUIRED)| box1.right, box1.right - box1.left |EQ(WEAK)| 10.0, box2.right - box2.left |EQ(WEAK)| 10.0 ]).unwrap(); eprintln!("?"); assert_eq!(solver.get_value(area.left), 0.0); assert_eq!(solver.get_value(area.right), 20.0); assert_eq!(solver.get_value(box1.left), 0.0); assert_eq!(solver.get_value(box1.right), 10.0); assert_eq!(solver.get_value(box2.left), 10.0); assert_eq!(solver.get_value(box2.right), 20.0); } }
true
1c4c58c5d9d220a98db149d79890e7756eaa1b2a
Rust
dragon1061/MoonZoon
/crates/hsluv/src/lib.rs
UTF-8
1,644
2.84375
3
[ "MIT" ]
permissive
use hsluv::hsluv_to_rgb; #[cfg(feature = "hsluv_macro")] pub use hsluv_macro::hsluv; /// https://www.hsluv.org/ #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] pub struct HSLuv { h: f64, s: f64, l: f64, a: f64, } impl HSLuv { pub fn hsl(h: impl Into<f64>, s: impl Into<f64>, l: impl Into<f64>) -> Self { Self::hsla(h, s, l, 100) } pub fn hsla( h: impl Into<f64>, s: impl Into<f64>, l: impl Into<f64>, a: impl Into<f64>, ) -> Self { Self { h: h.into().clamp(0., 360.), s: s.into().clamp(0., 100.), l: l.into().clamp(0., 100.), a: a.into().clamp(0., 100.), } } pub const fn new_unchecked(h: f64, s: f64, l: f64, a: f64) -> Self { HSLuv { h, s, l, a } } pub fn to_rgb(&self) -> (f64, f64, f64) { hsluv_to_rgb((self.h, self.s, self.l)) } // -- setters -- pub fn set_h(mut self, h: impl Into<f64>) -> Self { self.h = h.into().clamp(0., 360.); self } pub fn set_s(mut self, s: impl Into<f64>) -> Self { self.s = s.into().clamp(0., 100.); self } pub fn set_l(mut self, l: impl Into<f64>) -> Self { self.l = l.into().clamp(0., 100.); self } pub fn set_a(mut self, a: impl Into<f64>) -> Self { self.a = a.into().clamp(0., 100.); self } // -- getters -- pub fn h(&self) -> f64 { self.h } pub fn s(&self) -> f64 { self.s } pub fn l(&self) -> f64 { self.l } pub fn a(&self) -> f64 { self.a } }
true
ab616139d9c809427b57fd045d2825c054059797
Rust
esmevane/zemeroth
/hate/src/scene/action/sleep.rs
UTF-8
513
2.84375
3
[ "Apache-2.0", "MIT" ]
permissive
use time::Time; use scene::Action; #[derive(Debug)] pub struct Sleep { duration: Time, time: Time, } impl Sleep { pub fn new(duration: Time) -> Self { Self { duration: duration, time: Time(0.0), } } } impl Action for Sleep { fn duration(&self) -> Time { self.duration } fn is_finished(&self) -> bool { self.time.0 / self.duration.0 > 1.0 } fn update(&mut self, dtime: Time) { self.time.0 += dtime.0; } }
true
ed155998c0f4141203562e2e9a47ec60b5396618
Rust
sbnair/dices
/game_server/src/ws.rs
UTF-8
4,135
2.65625
3
[]
no_license
use std::{collections::HashMap, error::Error, io::Error as IoError, net::SocketAddr, sync::Arc}; use futures::SinkExt; use tokio::stream::StreamExt; use tokio::{ prelude::*, sync::mpsc::{unbounded_channel, UnboundedSender}, sync::Mutex, }; use async_tungstenite::tungstenite::protocol::Message; use lazy_static::lazy_static; use tokio::net::{TcpListener, TcpStream}; use tokio::select; use tokio::task; use common::{MessageFromClient, MessageFromServer}; use mongodb::{ bson::{doc, Bson}, options::ClientOptions, options::FindOptions, Client, }; type Tx = UnboundedSender<Message>; type PeerMap = Arc<Mutex<HashMap<String, Tx>>>; fn parse_message(ws_message: Message) -> Result<MessageFromClient, ()> { if let Message::Text(message_str) = ws_message { match serde_json::from_str::<MessageFromClient>(&message_str) { Ok(message_from_client) => return Ok(message_from_client), Err(_) => return Err(()), }; } else { return Err(()); } } async fn verify_user(username: &str, password: &str) -> Result<bool, Box<dyn Error>> { // Connect to the database let mut client_options = ClientOptions::parse("mongodb://localhost:27017") .await .unwrap(); let client = Client::with_options(client_options).unwrap(); let db = client.database("game"); // Query the documents in the collection with a filter and an option. let document_option = db .collection("users") .find_one(doc! {"username": username}, None) .await?; if let Some(document) = document_option { if let Some(user_password) = document.get("password").and_then(Bson::as_str) { return Ok(password == user_password); } } Ok(false) } async fn handle_connection(peer_map: PeerMap, raw_stream: TcpStream, addr: SocketAddr) { println!("Incoming TCP connection from: {}", addr); let mut ws_stream = async_tungstenite::tokio::accept_async(raw_stream) .await .unwrap(); println!("WebSocket connection established: {}", addr); // Login user let mut user: String = String::from("unknown"); let mut login_result: bool = false; while login_result == false { let login_message = parse_message(ws_stream.next().await.unwrap().unwrap()).unwrap(); if let MessageFromClient::Login { username, password } = login_message { println!( "Received login request from {} with password {}", &username, &password ); if verify_user(&username, &password).await.unwrap() { login_result = true; user = username; } } else { panic!(); } let login_response_msg = MessageFromServer::LoginResponse(login_result); ws_stream .send(Message::Text( serde_json::to_string(&login_response_msg).unwrap(), )) .await .unwrap(); } let (tx, mut rx) = unbounded_channel(); peer_map.lock().await.insert(user.clone(), tx); loop { let a = rx.next(); let b = ws_stream.next(); select! { m = a => { if let Some(m) = m { ws_stream.send(m).await.unwrap(); } } m = b => { let client_message: MessageFromClient = parse_message(m.unwrap().unwrap()).unwrap(); } } } peer_map.lock().await.remove(&user); } pub async fn listen(addr: String) -> Result<(), Box<dyn Error>> { let state = PeerMap::new(Mutex::new(HashMap::new())); // Create the event loop and TCP listener we'll accept connections on. let try_socket = TcpListener::bind(&addr).await; let mut listener = try_socket.expect("Failed to bind"); println!("Listening on: {}", addr); // Let's spawn the handling of each connection in a separate task. while let Ok((stream, addr)) = listener.accept().await { task::spawn(handle_connection(state.clone(), stream, addr)); } Ok(()) }
true
1cf5ee97c72a5b46fbd9812656cf75676c9672c6
Rust
JRMurr/rust-back
/rback/src/game_input_frame.rs
UTF-8
1,016
3.171875
3
[ "MIT" ]
permissive
use crate::{FrameSize, GameInput}; use std::fmt::Debug; #[derive(Debug, Clone, PartialEq)] // TODO: i think only prediction could have both of these be none // so might be better if i make a special type for prediction // so normal game input does not have to deal with unwraps pub struct GameInputFrame<T: GameInput> { pub frame: Option<FrameSize>, pub input: Option<T>, } impl<T: GameInput> GameInputFrame<T> { pub fn new(input: T, frame: FrameSize) -> Self { Self { frame: Some(frame), input: Some(input), } } pub fn empty_input() -> Self { Self { frame: None, input: None, } } pub fn erase_input(&mut self) { self.input = None } } // Mostly used for tests to make frames easily impl<T: GameInput> From<(T, FrameSize)> for GameInputFrame<T> { fn from(inner: (T, FrameSize)) -> Self { Self { input: Some(inner.0), frame: Some(inner.1), } } }
true
7475cf74ccb75cb1dc364a497f17f7284262b95c
Rust
liufoyang/rust_demo
/demobin/src/main.rs
UTF-8
3,867
3.53125
4
[]
no_license
use flycoin::fly_coin; fn main() { println!("Hello, world!"); let mut s = "aaaa"; s = "bbb"; let mut b = s.to_string(); b.push_str("cccc"); base_date_type(); own_ship(); base_own_and_reference(); mut_own_and_reference(); //fly_coin } fn base_date_type() { let demo_str = 'a'; let demo_int:u32 = 1024; let demo_float = 10.0; let demo_boolean = true; println!("base type for char {}, int {}, float {}, boolean {}", demo_str,demo_int, demo_float, demo_boolean ); // let default 不变的,下面语句错误 //demoInt = 120; // 数组的定义方法 let demo_array = [1,2,3,4,5]; println!("base array {}", demo_array[0]); // 可变的变量需要加mut声明 let mut demo_mut_Str:String = String::from("hello"); demo_mut_Str.push_str(", world"); demo_mut_Str.push_str(", from rust"); println!("mut varibality {}", demo_mut_Str); } fn own_ship() { let default_own:String = String::from("own"); let default_ownInt:i32 = 32; println!("the own is own_move {}", default_own); // 所有者转移到新的,老的会失效 let own_move = default_own; let own_move_int:i32 = default_ownInt; println!("the own is own_move {}", own_move); println!("the own is own_move_int {}", own_move_int); //println!("own have move {}", default_own); // 再使用原来的变量,就回报错,这里不能通过编译 // 基础类型,放在stack,没有own的转移,直接stack的copy println!("own have move {}", default_ownInt); // own直接转移到函数内,最终范围结束被清理 let pass_own:String = String::from("pass Own"); take_own_ship(pass_own); // 这里再使用,报错 // println!("own have move {}", pass_own); // 基本类型,存放在stack, own不传递,只复制值 not_take_own_ship(own_move_int); println!("the own is own not pass {}", own_move_int); } fn take_own_ship(own_pass:String) { println!("own have move in fun {}", own_pass); } fn not_take_own_ship(own_pass:i32) { println!("own have move in fun {}", own_pass); } fn base_own_and_reference() { // 变量第一个持有,就是这变量的ownship let default_own:String = String::from("dafualOwn"); // let mut reference: &String = &default_own; { // we only can use when own_ship 在范围块内 let own_scop:String = String::from("own_scop"); reference = &own_scop; println!("in scop use {}", reference); } // reference 借来的引用, 因为owner范围块结束,这里使用会报错 borrowed value does not live long enough // println!("out scop use {}", reference); } fn mut_own_and_reference() { // 变量第一个持有,就是这变量的ownship let mut default_own:String = String::from("dafualOwn"); // let mut reference1: &String = &mut default_own; // 借用只能借给一个,不能同时使用 //let mut reference2: &String = &mut default_own; //println!("in scop use {}", reference2); { // we only can use when own_ship 在范围块内 let own_scop: String = String::from("own_scop"); reference1 = &own_scop; println!("in scop use {}", reference1); // 这里 借用可以, 因为refenc1已结结束借用了。 let reference2 = &mut default_own; println!("in scop use one borrow {}", reference2); // 把可变的变量借给第二个可变引用,则会报错,同时只能借给一个可变引用 //reference1 = &mut default_own; //println!("in scop use {} {}", reference1, reference2); } // 这里报错,因为reference1借的变量已结结束范围,被清理 borrow later used here //println!("in scop use {} {}", reference1, reference1); }
true
01ed008f7bd4616f9589bc431a0842041ca60034
Rust
kitsuneninetails/rust-tutorials
/src/bin/tutorial10-threads.rs
UTF-8
985
3.109375
3
[]
no_license
use std::io::{stdin, stdout, Write}; use std::sync::mpsc::{channel, Sender, Receiver}; use std::thread::spawn; fn enter_val(chan: Sender<String>, rchan: Receiver<bool>) { loop { print!("In>"); stdout().flush().unwrap(); let mut instr = String::new(); stdin().read_line(&mut instr).unwrap(); chan.send(instr.trim().to_string()).unwrap(); if rchan.recv().unwrap() { break; } } } fn print_out_val(chan: Receiver<String>, rchan: Sender<bool>) { loop { let printstr = chan.recv().unwrap(); if printstr == "exit!" { rchan.send(true).unwrap(); break; } println!("Out> {}", printstr.trim()); stdout().flush().unwrap(); rchan.send(false).unwrap(); } } fn main() { let (s, r) = channel(); let (s2, r2) = channel(); let h = spawn(move || { print_out_val(r, s2); }); enter_val(s, r2); h.join().unwrap(); }
true
7589a46cede7ede7006780a62c3ecc8234c5571a
Rust
WiebeCnossen/rust-kata
/src/kata21/tests.rs
UTF-8
2,605
3.015625
3
[]
no_license
use std::fmt::Debug; use super::list::List; pub fn test_empty<T: PartialEq, L: List<T>>() { let list = L::empty(); assert_eq!(0, list.collect().len()); } pub fn test_one<T: PartialEq + Clone + Debug, L: List<T>>(v0: T) { let b0 = v0.clone(); let list = L::empty().add(v0); let v = list.collect(); assert_eq!(1, v.len()); assert_eq!(b0, *v[0]); } pub fn test_two<T: PartialEq + Clone + Debug, L: List<T>>(v0: T, v1: T) { let b0 = v0.clone(); let b1 = v1.clone(); let list = L::empty().add(v0).add(v1); let v = list.collect(); assert_eq!(2, v.len()); assert_eq!(b0, *v[0]); assert_eq!(b1, *v[1]); } pub fn test_found<T: PartialEq + Clone, L: List<T>>(v0: T, v1: T) { let b0 = v0.clone(); let list = L::empty().add(v0).add(v1); assert!(list.find(&b0).is_some()); } pub fn test_not_found<T: PartialEq + Clone, L: List<T>>(v0: T, v1: T, x0: T) { let list = L::empty().add(v0).add(v1); assert!(list.find(&x0).is_none()); } pub fn test_remove_first<T: PartialEq + Clone + Debug, L: List<T>>(v0: T, v1: T) { let b0 = v0.clone(); let b1 = v1.clone(); let list = L::empty().add(v0).add(v1); let found = list.find(&b0); assert!(found.is_some()); let list = list.remove(found.unwrap()); let v = list.collect(); assert_eq!(1, v.len()); assert_eq!(b1, *v[0]); } pub fn test_remove_second<T: PartialEq + Clone + Debug, L: List<T>>(v0: T, v1: T) { let b0 = v0.clone(); let b1 = v1.clone(); let list = L::empty().add(v0).add(v1); let found = list.find(&b1); assert!(found.is_some()); let list = list.remove(found.unwrap()); let v = list.collect(); assert_eq!(1, v.len()); assert_eq!(b0, *v[0]); } pub fn test_remove_third<T: PartialEq + Clone + Debug, L: List<T>>(v0: T, v1: T, v2: T) { let b0 = v0.clone(); let b1 = v1.clone(); let b2 = v2.clone(); let list = L::empty().add(v0).add(v1).add(v2); let found = list.find(&b2); assert!(found.is_some()); let list = list.remove(found.unwrap()); let v = list.collect(); assert_eq!(2, v.len()); assert_eq!(b0, *v[0]); assert_eq!(b1, *v[1]); } pub fn test_remove_head<T: PartialEq + Clone + Debug, L: List<T>>(v0: T, v1: T, v2: T) { let b0 = v0.clone(); let b1 = v1.clone(); let b2 = v2.clone(); let list = L::empty().add(v0).add(v1).add(v2); let found = list.find(&b0); assert!(found.is_some()); let list = list.remove(found.unwrap()); let v = list.collect(); assert_eq!(2, v.len()); assert_eq!(b1, *v[0]); assert_eq!(b2, *v[1]); }
true
fc614a333a768af911aa34184c9c4a638680e1fb
Rust
marc47marc47/leetcode-cn
/132minCut/min_cut/src/lib.rs
UTF-8
1,618
2.9375
3
[]
no_license
/* * @Description: 132 min_cut * @Version: 2.0 * @Author: kingeasternsun * @Date: 2021-03-08 11:18:50 * @LastEditors: kingeasternsun * @LastEditTime: 2021-03-08 11:38:36 * @FilePath: \132minCut\min_cut\src\lib.rs */ pub struct Solution; impl Solution { pub fn min_cut(s: String) -> i32 { if s.len() <= 1 { return 0; } let mut isPali = vec![vec![false; s.len()]; s.len()]; let bs = s.into_bytes(); //预先计算任意区间是否是回文字符串 let mut judge = |mut x: usize, mut y: usize| { while y < bs.len() && bs[x] == bs[y] { isPali[x][y] = true; if x == 0 { break; }; x -= 1; y += 1; } }; (0..bs.len()).for_each(|x| { judge(x, x); judge(x, x + 1); }); //dp计算 let mut dp = vec![0 as i32; bs.len()]; for end in 1..bs.len() { dp[end] = bs.len() as i32 - 1; for beg in 0..end + 1 { if isPali[beg][end] { if beg == 0 { dp[end] = 0 } else if dp[beg - 1] + 1 < dp[end] { dp[end] = dp[beg - 1] + 1 } } } } dp[dp.len() - 1] } } #[cfg(test)] mod tests { use crate::Solution; #[test] fn it_works() { assert_eq!(Solution::min_cut(String::from("aab")),1); assert_eq!(Solution::min_cut(String::from("aba")),0); } }
true
412965b7dfaf27f17e7ad62bb4ebed5def3529ae
Rust
chrisrhayden/drift
/src/bin/driftcli.rs
UTF-8
1,988
2.84375
3
[]
no_license
extern crate clap; use std::error::Error; use std::os::unix::net::UnixStream; use std::io::prelude::*; use clap::{App, Arg}; fn main() { if let Err(err) = run() { eprintln!("Error {}", err); } } fn run() -> Result<(), Box<dyn Error>> { let evt_str = get_args(); let mut stream = UnixStream::connect("/tmp/drift_socket")?; stream .write_all(evt_str.as_bytes()) .expect("failed to send string"); Ok(()) } fn get_args() -> String { let matches = App::new("driftcli") .arg( Arg::with_name("play song") .long("play") .short("p") .value_name("FILE") .takes_value(true) .help("play a song"), ).arg( Arg::with_name("stop song") .long("stop") .short("s") .help("stop the current song, Note: cant restart after"), ).arg( Arg::with_name("pause song") .long("pause") .short("P") .help("pause a song"), ).arg( Arg::with_name("toggle pause") .long("toggle") .short("t") .help("toggle pause of a song"), ).arg( Arg::with_name("kill daemon") .long("kill") .short("k") .help("kill the daemon"), ).get_matches(); // TODO: reformat to match if matches.is_present("play song") { // we know it exists so unwrap should be fine format!("play {}", matches.value_of("play song").unwrap()) } else if matches.is_present("stop song") { String::from("stop") } else if matches.is_present("toggle pause") { String::from("toggle") } else if matches.is_present("pause") { String::from("pause") } else if matches.is_present("kill daemon") { String::from("kill") } else { String::from("none") } }
true
b3f3379292dfc4d15eb54f842a5e9b52f29c4910
Rust
nguyenminhhieu12041996/casper-node
/types/src/named_key.rs
UTF-8
1,310
2.71875
3
[ "Apache-2.0" ]
permissive
// TODO - remove once schemars stops causing warning. #![allow(clippy::field_reassign_with_default)] use alloc::{string::String, vec::Vec}; #[cfg(feature = "std")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::bytesrepr::{self, FromBytes, ToBytes}; /// A named key. #[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Default, Debug)] #[cfg_attr(feature = "std", derive(JsonSchema))] #[serde(deny_unknown_fields)] pub struct NamedKey { /// The name of the entry. pub name: String, /// The value of the entry: a casper `Key` type. pub key: String, } impl ToBytes for NamedKey { fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> { let mut buffer = bytesrepr::allocate_buffer(self)?; buffer.extend(self.name.to_bytes()?); buffer.extend(self.key.to_bytes()?); Ok(buffer) } fn serialized_length(&self) -> usize { self.name.serialized_length() + self.key.serialized_length() } } impl FromBytes for NamedKey { fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> { let (name, remainder) = String::from_bytes(bytes)?; let (key, remainder) = String::from_bytes(remainder)?; let named_key = NamedKey { name, key }; Ok((named_key, remainder)) } }
true
cfdccab12a77bad79b76a47349e9d1f709dbbf28
Rust
vivint-smarthome/color-backtrace
/src/failure.rs
UTF-8
1,843
2.703125
3
[ "MIT", "Apache-2.0" ]
permissive
//! Temporary hack to allow printing of `failure::Backtrace` objects. use crate::default_output_stream; struct FakeBacktrace { internal: FakeInternalBacktrace, } struct FakeInternalBacktrace { backtrace: Option<MaybeResolved>, } struct MaybeResolved { _resolved: std::sync::Mutex<bool>, backtrace: std::cell::UnsafeCell<backtrace::Backtrace>, } /// Unsafely extract a reference to the internal `backtrace::Backtrace` from a /// `failure::Backtrace`. /// /// # Unsafe Usage /// /// Casts a `failure::Backtrace` to an internal reimplementation of it's struct layout as of /// failure `0.1.5` and then accesses its UnsafeCell to get a reference to its internal /// Backtrace. pub unsafe fn backdoortrace(_opaque: &failure::Backtrace) -> Option<&backtrace::Backtrace> { let _ = format!("{}", _opaque); // forces resolution let no_longer_opaque: &FakeBacktrace = { &*(_opaque as *const failure::Backtrace as *const FakeBacktrace) }; // unsafe if let Some(bt) = &no_longer_opaque.internal.backtrace { let bt = { &*bt.backtrace.get() }; // unsafe return Some(bt); } None } #[deprecated( since = "0.4", note = "Use `BacktracePrinter::print_failure_trace` instead." )] pub unsafe fn print_backtrace( trace: &failure::Backtrace, printer: &crate::BacktracePrinter, ) -> crate::IOResult { printer.print_failure_trace(trace, &mut default_output_stream()) } #[cfg(test)] mod tests { use super::*; #[test] fn with_envvar() { std::env::set_var("RUST_BACKTRACE", "full"); let e = failure::format_err!("arbitrary error :)"); let printer = crate::BacktracePrinter::new(); unsafe { printer .print_failure_trace(e.backtrace(), &mut default_output_stream()) .unwrap(); } } }
true
68f0c2ca1ecb1db9aa7c6fc2f6efe336f0170532
Rust
GuyL99/metropolis
/src/elements.rs
UTF-8
4,613
3.09375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use crate::color::*; use crate::canvas::*; pub trait PageElement { fn draw(self,canvas:&mut Canvas); #[allow(non_snake_case)] fn onClick(self,canvas:&Canvas)->bool; #[allow(non_snake_case)] fn onHover(self,canvas:&Canvas)->bool; } #[derive(Copy,Clone)] pub enum Styles{ Normal, RoundEdges, Triangular, Elliptic, } #[derive(Clone,Copy)] pub struct Button{ color:Color, x:u16, y:u16, width:u16, height:u16, border_width:u8, style:Styles, text:&'static str, } impl PageElement for Button { fn draw(self,canvas:&mut Canvas){ canvas.textSize(12); canvas.text(self.x+self.border_width as u16+6,self.y+self.border_width as u16+(self.height/2)+1,self.text); match self.style{ Styles::Normal=>{ /*canvas.fill(self.color-20); canvas.rect(self.x,self.y,self.width,self.height);*/ canvas.fill(self.color); canvas.rect(self.x+self.border_width as u16,self.y+self.border_width as u16,self.width-(self.border_width*2) as u16,self.height-(self.border_width*2) as u16); }, Styles::RoundEdges=>{ canvas.line(self.x+2,self.y,self.x+self.width-4,self.y); canvas.bezierCurveVertex((self.x+self.width-4) as i64,self.y as i64,(self.x+self.width-2) as i64,(self.y+2) as i64,(self.x+self.width-4) as i64,self.y as i64,(self.x+self.width-2) as i64,(self.y+2) as i64); canvas.line(self.x+self.width-2,self.y+2,self.x+self.width-2,self.y+self.height-4); canvas.bezierCurveVertex((self.x+self.width-2) as i64,(self.y+self.height-4) as i64,(self.x+self.width-4) as i64,(self.y+self.height-2) as i64,(self.x+self.width-2) as i64,(self.y+self.height-4) as i64,(self.x+self.width-4) as i64,(self.y+self.height-2) as i64); canvas.line(self.x+self.width-4,self.y+self.height-2,self.x+2,self.y+self.height-2); canvas.bezierCurveVertex((self.x+2) as i64,(self.y+self.height-2) as i64,(self.x) as i64,(self.y+self.height-4) as i64,(self.x+2) as i64,(self.y+self.height-2) as i64,(self.x) as i64,(self.y+self.height-4) as i64); canvas.line(self.x,self.y+self.height-4,self.x,self.y+2); canvas.bezierCurveVertex((self.x) as i64,(self.y+2) as i64,(self.x+2) as i64,self.y as i64,(self.x) as i64,(self.y+2) as i64,(self.x+2) as i64,self.y as i64); }, _=>{}, } } #[allow(non_snake_case)] fn onClick(self,canvas:&Canvas)->bool{ if canvas.mouseClick()==MouseButton::Left && (canvas.mouseX()>self.x && canvas.mouseX()<self.x+self.width) &&(canvas.mouseY()>self.y && canvas.mouseY()<self.y+self.height){ return true; } false } #[allow(non_snake_case)] fn onHover(self,canvas:&Canvas)->bool{ if canvas.mouseClick()!=MouseButton::Left && (canvas.mouseX()>self.x && canvas.mouseX()<self.x+self.width) &&(canvas.mouseY()>self.y && canvas.mouseY()<self.y+self.height){ return true; } false } } impl Button{ pub fn new(x:u16,y:u16,text:&'static str)->Button{ Button{color:Color::from(190), x,y,width:40,height:20,border_width:2,style:Styles::Normal,text,} } pub fn location(&mut self,x:u16,y:u16)->Self{ self.x = x; self.y = y; *self } pub fn get_location(self)->(u16,u16){ (self.x,self.y) } pub fn get_x(self)->u16{ self.x } pub fn get_y(self)->u16{ self.y } pub fn color(&mut self,color:Color)->Self{ self.color = color; *self } pub fn size(&mut self,width:u16,height:u16)->Self{ self.width = width; self.height= height; *self } pub fn get_size(self)->(u16,u16){ (self.width,self.height) } pub fn get_width(self)->u16{ self.width } pub fn get_height(self)->u16{ self.height } pub fn width(&mut self,width:u16)->Self{ self.width = width; *self } pub fn height(&mut self,height:u16)->Self{ self.height = height; *self } pub fn border_width(&mut self,width:u8)->Self{ self.border_width = width; *self } pub fn get_border_width(self)->u8{ self.border_width } pub fn button_text(&mut self,text:&'static str)->Self{ self.text = text; *self } pub fn get_color(self)->Color{ self.color } pub fn style(&mut self,style:Styles)->Self{ self.style = style; *self } }
true
67be9903487f4e8ef07f9c01f63666522d30a7e6
Rust
talebisinan/RustBook
/tuple_array.rs
UTF-8
422
3.09375
3
[]
no_license
fn main() { let tup: (i32, f64, u8) = (500, 5.4, 3); let (x, y, z) = tup; // println!("tup:{:#?}, x:{}, y:{}, z:{}", tup, x, y, z); // println!("tuple => 0:{}, 1:{}, 2:{}", tup.0, tup.1, tup.2); let foo = ["bar", "Baz"]; let a: [i32; 5] = [1, 2, 3, 4, 5]; let omg = [42; 10]; // 10 times 42! println!("{:#?}", foo); println!("{:#?} , a[0]:{}", a, a[0]); println!("{:?}", omg); }
true
97ba44460647e53cf9f02da5136303796f1f4dfc
Rust
AndikaRizary/juneau_wasm
/packages/juneau/src/parsing/jasm/test/assign.rs
UTF-8
637
2.546875
3
[]
no_license
use juneau_core::{assert_eq_debug, assert_eq_object}; use crate::core::Id; use crate::semantic::Variable; use crate::semantic::jasm::JasmType::*; use crate::semantic::jasm::render::render_jasm; use crate::parsing::jasm::parse_jasm_statement; use super::new_context; #[test] fn parse_jasm_assign() { let source = "a = 4;"; let mut context = new_context(&[Variable::new(Id::from(63), &"a".into(), &I64)]); let jasm = parse_jasm_statement(&mut context, source); assert_eq_debug!(jasm, r#"Assign(Var(Variable { id: 63, name: "a", typ: I64 }), Constant(I64(4)))"#); assert_eq_object!(render_jasm(&jasm), r#"a = 4;"#); }
true
e50670deaa0806cfd09fc9395f52967ea423cbd6
Rust
kerinin/hammer
/src/evicting_store/ghosted_list.rs
UTF-8
4,126
3.203125
3
[]
no_license
use std::cmp; use std::hash; use std::clone; use std::collections::{HashMap}; use evicting_store::entry::Entry; use evicting_store::list::{List, Node, NodeLocation}; struct CachedNode<'a, T: 'a, V: 'a> { prev: Option<&'a mut CachedNode<'a, T, V>>, next: Option<&'a mut CachedNode<'a, T, V>>, //entry: Entry<T, V> + 'a, } impl<'a, T, V> Node<'a> for CachedNode<'a, T, V> { fn prev(&self) -> Option<&'a mut CachedNode<'a, T, V>> { self.prev } fn set_prev(&mut self, v: Option<&'a mut CachedNode<'a, T, V>>) { self.prev = v; } fn next(&self) -> Option<&'a mut CachedNode<'a, T, V>> { self.next } fn set_next(&mut self, v: Option<&'a mut CachedNode<'a, T, V>>) { self.next = v; } fn location(&self) -> NodeLocation { match (self.prev, self.next) { (None, None) => NodeLocation::NotInList, (None, Some(..)) => NodeLocation::Back, (Some(..), None) => NodeLocation::Front, (Some(..), Some(..)) => NodeLocation::Middle, } } } struct GhostNode<'a> { prev: Option<&'a mut GhostNode<'a>>, next: Option<&'a mut GhostNode<'a>>, } impl<'a> Node<'a> for GhostNode<'a> { fn prev(&self) -> Option<&'a mut GhostNode<'a>> { self.prev } fn set_prev(&mut self, v: Option<&'a mut GhostNode<'a>>) { self.prev = v; } fn next(&self) -> Option<&'a mut GhostNode<'a>> { self.next } fn set_next(&mut self, v: Option<&'a mut GhostNode<'a>>) { self.next = v; } fn location(&self) -> NodeLocation { match (self.prev, self.next) { (None, None) => NodeLocation::NotInList, (None, Some(..)) => NodeLocation::Back, (Some(..), None) => NodeLocation::Front, (Some(..), Some(..)) => NodeLocation::Middle, } } } enum Position<'a, T: 'a, V: 'a> { Top(CachedNode<'a, T, V>), Bottom(GhostNode<'a>), } struct GhostedList<'a, T: 'a + cmp::Eq + hash::Hash, V: 'a> { pub top: List<'a, CachedNode<'a, T, V>>, top_index: HashMap<T, CachedNode<'a, T, V>>, pub bottom: List<'a, GhostNode<'a>>, bottom_index: HashMap<T, GhostNode<'a>>, } impl<'a, T: hash::Hash + cmp::Eq + clone::Clone, V> GhostedList<'a, T, V> { fn get(&self, token: T) -> Option<Position<'a, T, V>> { match self.top_index.get(&token.clone()) { Some(node) => { //return Some(Position::Top(*node)); }, None => {}, } match self.bottom_index.get(&token) { Some(node) => { //return Some(Position::Bottom(*node)); return None; }, Nonde => { return None; }, } } /* * Shifts an entry from the LRU position in the top list to the MRU position * in the bottom list, and returns the newly emptied entry from the top */ fn replace(&mut self, target: &GhostNode) -> &CachedNode<'a, T, V> { // NOTE: Need to use target... // NOTE: Make sure this updates indices // NOTE: What if these are None? match self.top.back { None => { // We shouldn't ever end up here - this function should // only ever be called when the top has data. panic!("Attempted to shift data from an empty list") }, Some(top_lru) => { // Clear out pointers //self.top.remove(top_lru); //self.bottom.remove(target); // Remove from lookups //self.top_index.remove(self.top.data); // ??? //self.bottom_index.remove(self.bottom.data); // ??? // Shift data //target.data = top_lru.data; // ??? // Add to list //self.bottom.push_front(target); // Add to lookup //self.bottom_index.insert(self.bottom.data, self.bottom); // ??? return top_lru; }, } } }
true
f56c7c73477249b4aaa22ce79bb9c5afeee301d6
Rust
m-lima/advent-of-code-2020
/src/bin/072/main.rs
UTF-8
2,186
3.171875
3
[]
no_license
use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; const INPUT: &str = include_str!("input.txt"); struct Rules { color_to_index: HashMap<String, usize>, allowed_bags: Vec<Vec<(usize, usize)>>, } impl Rules { fn new(known_bags: Vec<String>) -> Self { let color_to_index: HashMap<String, usize> = known_bags .iter() .enumerate() .map(|(index, value)| (value.clone(), index)) .collect(); Self { color_to_index, allowed_bags: Vec::with_capacity(known_bags.len()), } } } fn fold_into_dataset(mut rules: Rules, line: &str) -> Rules { lazy_static! { static ref PATTERN: Regex = Regex::new(r"([0-9]+) (\w+ \w+) bags?").unwrap(); } let captures = PATTERN.captures_iter(line); let allowed = captures .filter_map(|capture| { capture .get(1) .and_then(|count| count.as_str().parse::<usize>().ok()) .and_then(|count| { capture .get(2) .map(|color| (count, String::from(color.as_str()))) }) }) .map(|(count, color)| (count, *rules.color_to_index.get(&color).unwrap())) .collect::<Vec<_>>(); rules.allowed_bags.push(allowed); rules } fn bag_count(bag: usize, rules: &Rules) -> usize { rules.allowed_bags[bag] .iter() .map(|allowed_bag| allowed_bag.0 + allowed_bag.0 * bag_count(allowed_bag.1, rules)) .sum() } fn main() { let rules = { let known_bags = INPUT .split('\n') .filter(|line| !line.is_empty()) .map(|line| { let mut name = line.split_whitespace().take(2); format!("{} {}", name.next().unwrap(), name.next().unwrap()) }) .collect(); INPUT .split('\n') .filter(|line| !line.is_empty()) .fold(Rules::new(known_bags), fold_into_dataset) }; let count = bag_count(*rules.color_to_index.get("shiny gold").unwrap(), &rules); println!("{}", count); }
true
029daaa904b4fc5ab6246878762d1714da8b95fd
Rust
sanpii/lxc-rs
/src/attach.rs
UTF-8
1,092
2.53125
3
[ "MIT" ]
permissive
/** LXC attach function type. */ pub use lxc_sys::lxc_attach_exec_t as ExecFn; /** LXC attach options for `lxc::Container::attach()`. */ pub use lxc_sys::lxc_attach_options_t as Options; bitflags::bitflags! { /** LXC environment policy. */ pub struct EnvPolicy: i32 { /** Retain the environment */ const KEEP_ENV = lxc_sys::lxc_attach_env_policy_t_LXC_ATTACH_KEEP_ENV as i32; /** Clear the environment */ const CLEAR_ENV = lxc_sys::lxc_attach_env_policy_t_LXC_ATTACH_CLEAR_ENV as i32; } } /** * Run a command in the container. * * Returns exit code program on success. */ pub fn run_command(payload: &mut std::os::raw::c_void) -> Result<i32, ()> { let result = unsafe { lxc_sys::lxc_attach_run_command(payload) }; if result == -1 { Err(()) } else { Ok(result) } } /** * Run a shell command in the container. * * `_payload` parameter is not used. * * Returns exit code of shell. */ pub fn run_shell(_payload: &mut std::os::raw::c_void) -> i32 { unsafe { lxc_sys::lxc_attach_run_shell(_payload) } }
true
8b4705c316410288056f8fdfd72323b554b2040e
Rust
mapkts/byteseeker
/tests/seeker.rs
UTF-8
24,569
2.84375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
use byteseeker::*; use std::io::Cursor; use std::iter; const DEFAULT_CHUNK_SIZE: usize = 1024; #[test] fn test_invalid_seeking_bytes() { let bytes: Vec<u8> = vec![0, 1, 2]; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek(&[]) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::UnsupportedLength => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![0, 1, 2]; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::with_capacity(&mut cursor, 3); let seeking_bytes = [0; 4]; match seeker.seek(&seeking_bytes) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::UnsupportedLength => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_cs0() { let bytes: Vec<u8> = vec![]; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } match seeker.seek(b"\r\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_back_cs0() { let bytes: Vec<u8> = vec![]; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek_back(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![]; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek_back(b"\r\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_cs1() { let bytes: Vec<u8> = vec![b'0']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'0']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek(b"\r\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n").unwrap(), 0); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => { assert!(false) } }, } let bytes: Vec<u8> = vec![b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek(b"\n\r") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_back_cs1() { let bytes: Vec<u8> = vec![b'0']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek_back(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'0']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek_back(b"\r\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n").unwrap(), 0); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => { assert!(false) } }, } let bytes: Vec<u8> = vec![b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek_back(b"\n\r") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_cs2() { let bytes: Vec<u8> = vec![b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n").unwrap(), 1); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n").unwrap(), 0); assert_eq!(seeker.seek(b"\n").unwrap(), 1); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n\n").unwrap(), 0); match seeker.seek(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_back_cs2() { let bytes: Vec<u8> = vec![b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n").unwrap(), 1); match seeker.seek_back(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek_back(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n").unwrap(), 1); assert_eq!(seeker.seek_back(b"\n").unwrap(), 0); match seeker.seek_back(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n\n").unwrap(), 0); match seeker.seek_back(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_cs3() { let bytes: Vec<u8> = vec![b'0', b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n").unwrap(), 2); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'0', b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => { assert!(false) } }, } let bytes: Vec<u8> = vec![b'\n', b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n").unwrap(), 0); assert_eq!(seeker.seek(b"\n").unwrap(), 2); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'\n', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n").unwrap(), 0); assert_eq!(seeker.seek(b"\n").unwrap(), 1); assert_eq!(seeker.seek(b"\n").unwrap(), 2); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'\n', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n\n").unwrap(), 0); match seeker.seek(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_back_cs3() { let bytes: Vec<u8> = vec![b'0', b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n").unwrap(), 2); match seeker.seek_back(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'0', b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek_back(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => { assert!(false) } }, } let bytes: Vec<u8> = vec![b'\n', b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n").unwrap(), 2); assert_eq!(seeker.seek_back(b"\n").unwrap(), 0); match seeker.seek_back(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'0', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); match seeker.seek_back(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'\n', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n").unwrap(), 2); assert_eq!(seeker.seek_back(b"\n").unwrap(), 1); assert_eq!(seeker.seek_back(b"\n").unwrap(), 0); match seeker.seek_back(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = vec![b'\n', b'\n', b'\n']; let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n\n").unwrap(), 1); match seeker.seek_back(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_csn() { let bytes: Vec<u8> = iter::repeat(0) .take(DEFAULT_CHUNK_SIZE - 1) .chain(iter::repeat(b'\n').take(2)) .chain(iter::repeat(0).take(DEFAULT_CHUNK_SIZE)) .chain(iter::repeat(b'\n').take(2)) .collect(); let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n").unwrap(), DEFAULT_CHUNK_SIZE - 1); assert_eq!(seeker.seek(b"\n").unwrap(), DEFAULT_CHUNK_SIZE); assert_eq!(seeker.seek(b"\n").unwrap(), DEFAULT_CHUNK_SIZE * 2 + 1); assert_eq!(seeker.seek(b"\n").unwrap(), DEFAULT_CHUNK_SIZE * 2 + 2); match seeker.seek(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = iter::repeat(0) .take(DEFAULT_CHUNK_SIZE - 1) .chain(iter::repeat(b'\n').take(2)) .chain(iter::repeat(0).take(DEFAULT_CHUNK_SIZE)) .chain(iter::repeat(b'\n').take(2)) .collect(); let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek(b"\n\n").unwrap(), DEFAULT_CHUNK_SIZE - 1); assert_eq!(seeker.seek(b"\n\n").unwrap(), DEFAULT_CHUNK_SIZE * 2 + 1); match seeker.seek(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_back_csn() { let bytes: Vec<u8> = iter::repeat(0) .take(DEFAULT_CHUNK_SIZE - 1) .chain(iter::repeat(b'\n').take(2)) .chain(iter::repeat(0).take(DEFAULT_CHUNK_SIZE)) .chain(iter::repeat(b'\n').take(2)) .collect(); let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_back(b"\n").unwrap(), DEFAULT_CHUNK_SIZE * 2 + 2); assert_eq!(seeker.seek_back(b"\n").unwrap(), DEFAULT_CHUNK_SIZE * 2 + 1); assert_eq!(seeker.seek_back(b"\n").unwrap(), DEFAULT_CHUNK_SIZE); assert_eq!(seeker.seek_back(b"\n").unwrap(), DEFAULT_CHUNK_SIZE - 1); match seeker.seek_back(b"\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let bytes: Vec<u8> = iter::repeat(0) .take(DEFAULT_CHUNK_SIZE - 1) .chain(iter::repeat(b'\n').take(2)) .chain(iter::repeat(0).take(DEFAULT_CHUNK_SIZE)) .chain(iter::repeat(b'\n').take(2)) .collect(); let mut cursor = Cursor::new(bytes); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!( seeker.seek_back(b"\n\n").unwrap(), DEFAULT_CHUNK_SIZE * 2 + 1 ); assert_eq!(seeker.seek_back(b"\n\n").unwrap(), DEFAULT_CHUNK_SIZE - 1); match seeker.seek_back(b"\n\n") { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_nth() { let bytes: Vec<u8> = iter::repeat(0) .take(DEFAULT_CHUNK_SIZE - 1) .chain(iter::repeat(b'\n').take(2)) .chain(iter::repeat(0).take(DEFAULT_CHUNK_SIZE - 1)) .chain(iter::repeat(b'\n').take(2)) .chain(iter::repeat(0).take(100)) .chain(iter::repeat(b'\n').take(2)) .collect(); let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_nth(b"\n", 1).unwrap(), DEFAULT_CHUNK_SIZE - 1); assert_eq!(seeker.seek_nth(b"\n", 1).unwrap(), DEFAULT_CHUNK_SIZE); assert_eq!(seeker.seek_nth(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE); assert_eq!( seeker.seek_nth(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 1 ); assert_eq!( seeker.seek_nth(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 2 ); assert_eq!( seeker.seek_nth(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 3 ); match seeker.seek_nth(b"\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_nth(b"\n", 2).unwrap(), DEFAULT_CHUNK_SIZE); assert_eq!( seeker.seek_nth(b"\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 1 ); assert_eq!( seeker.seek_nth(b"\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 3 ); match seeker.seek_nth(b"\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_nth(b"\n", 1).unwrap(), DEFAULT_CHUNK_SIZE - 1); assert_eq!(seeker.seek_nth(b"\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE); assert_eq!( seeker.seek_nth(b"\n", 3).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 3 ); match seeker.seek_nth(b"\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_nth(b"\n\n", 1).unwrap(), DEFAULT_CHUNK_SIZE - 1); assert_eq!(seeker.seek_nth(b"\n\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE); assert_eq!( seeker.seek_nth(b"\n\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 2 ); match seeker.seek_nth(b"\n\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_nth(b"\n\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE); match seeker.seek_nth(b"\n\n", 2) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!(seeker.seek_nth(b"\n\n", 1).unwrap(), DEFAULT_CHUNK_SIZE - 1); assert_eq!( seeker.seek_nth(b"\n\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 2 ); match seeker.seek_nth(b"\n\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } } #[test] fn test_seek_nth_back() { let bytes: Vec<u8> = iter::repeat(0) .take(DEFAULT_CHUNK_SIZE - 1) .chain(iter::repeat(b'\n').take(2)) .chain(iter::repeat(0).take(DEFAULT_CHUNK_SIZE - 1)) .chain(iter::repeat(b'\n').take(2)) .chain(iter::repeat(0).take(100)) .chain(iter::repeat(b'\n').take(2)) .collect(); let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!( seeker.seek_nth_back(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 3 ); assert_eq!( seeker.seek_nth_back(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 2 ); assert_eq!( seeker.seek_nth_back(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 1 ); assert_eq!( seeker.seek_nth_back(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE ); assert_eq!(seeker.seek_nth_back(b"\n", 1).unwrap(), DEFAULT_CHUNK_SIZE); assert_eq!( seeker.seek_nth_back(b"\n", 1).unwrap(), DEFAULT_CHUNK_SIZE - 1 ); match seeker.seek_nth_back(b"\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!( seeker.seek_nth_back(b"\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 2 ); assert_eq!( seeker.seek_nth_back(b"\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE ); assert_eq!( seeker.seek_nth_back(b"\n", 2).unwrap(), DEFAULT_CHUNK_SIZE - 1 ); match seeker.seek_nth_back(b"\n", 2) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!( seeker.seek_nth_back(b"\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 3 ); assert_eq!( seeker.seek_nth_back(b"\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 1 ); assert_eq!( seeker.seek_nth_back(b"\n", 3).unwrap(), DEFAULT_CHUNK_SIZE - 1 ); match seeker.seek_nth_back(b"\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!( seeker.seek_nth_back(b"\n\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 2 ); assert_eq!( seeker.seek_nth_back(b"\n\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE ); assert_eq!( seeker.seek_nth_back(b"\n\n", 1).unwrap(), DEFAULT_CHUNK_SIZE - 1 ); match seeker.seek_nth_back(b"\n\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!( seeker.seek_nth_back(b"\n\n", 2).unwrap(), 2 * DEFAULT_CHUNK_SIZE ); match seeker.seek_nth_back(b"\n\n", 2) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } let mut cursor = Cursor::new(bytes.clone()); let mut seeker = ByteSeeker::new(&mut cursor); assert_eq!( seeker.seek_nth_back(b"\n\n", 1).unwrap(), 2 * DEFAULT_CHUNK_SIZE + 100 + 2 ); assert_eq!( seeker.seek_nth_back(b"\n\n", 2).unwrap(), DEFAULT_CHUNK_SIZE - 1 ); match seeker.seek_nth_back(b"\n\n", 1) { Ok(_) => assert!(false), Err(e) => match *e.kind() { ErrorKind::ByteNotFound => assert!(true), _ => assert!(false), }, } }
true
7c4054d53b0e199c333192dbd15f3d90997acae3
Rust
aptend/leetcode-rua
/Rust/src/n1071_greatest_common_divisor_of_strings.rs
UTF-8
488
3.390625
3
[]
no_license
pub fn gcd_of_strings(str1: String, str2: String) -> String { if str1.clone() + &str2 != str2.clone() + &str1 { "".to_owned() } else { let mut a = str1.len(); let mut b = str2.len(); while b > 0 { let tmp = a % b; a = b; b = tmp; } str1[..a].into() } } #[test] fn test_1071() { assert_eq!( "AB".to_owned(), gcd_of_strings("ABABAB".to_owned(), "ABAB".to_owned()) ); }
true
86bb66a0d49c78f1f49366c5f32d86528d2701ea
Rust
rust-crdt/rust-crdt
/test/vclock.rs
UTF-8
5,027
3.109375
3
[ "Apache-2.0" ]
permissive
use crdts::*; use std::cmp::Ordering; quickcheck! { fn prop_into_iter_produces_same_vclock(clock: VClock<u8>) -> bool { clock == clock.clone().into_iter().collect() } fn prop_dots_are_commutative_in_from_iter(dots: Vec<Dot<u8>>) -> bool { // TODO: is there a better way to check comutativity of dots? let reverse: VClock<u8> = dots.clone() .into_iter() .rev() .collect(); let forward: VClock<u8> = dots .into_iter() .collect(); reverse == forward } fn prop_idempotent_dots_in_from_iter(dots: Vec<Dot<u8>>) -> bool { let single: VClock<u8> = dots.clone() .into_iter() .collect(); let double: VClock<u8> = dots.clone() .into_iter() .chain(dots.into_iter()) .collect(); single == double } fn prop_glb_self_is_nop(clock: VClock<u8>) -> bool { let mut clock_glb = clock.clone(); clock_glb.glb(&clock); clock_glb == clock } fn prop_glb_commutes(a: VClock<u8>, b: VClock<u8>) -> bool { let mut a_glb = a.clone(); a_glb.glb(&b); let mut b_glb = b; b_glb.glb(&a); a_glb == b_glb } fn prop_reset_remove_with_empty_is_nop(clock: VClock<u8>) -> bool { let mut subbed = clock.clone(); subbed.reset_remove(&VClock::new()); subbed == clock } fn prop_reset_remove_self_is_empty(clock: VClock<u8>) -> bool { let mut subbed = clock.clone(); subbed.reset_remove(&clock); subbed == VClock::new() } fn prop_reset_remove_is_empty_implies_equal_or_greator(a: VClock<u8>, b: VClock<u8>) -> bool { let mut a = a; a.reset_remove(&b); if a.is_empty() { matches!(a.partial_cmp(&b), Some(Ordering::Less) | Some(Ordering::Equal)) } else { matches!(a.partial_cmp(&b), None | Some(Ordering::Greater)) } } } #[test] fn test_reset_remove() { let mut a: VClock<u8> = vec![Dot::new(1, 4), Dot::new(2, 3), Dot::new(5, 9)] .into_iter() .collect(); let b: VClock<u8> = vec![Dot::new(1, 5), Dot::new(2, 3), Dot::new(5, 8)] .into_iter() .collect(); let expected: VClock<u8> = vec![Dot::new(5, 9)].into_iter().collect(); a.reset_remove(&b); assert_eq!(a, expected); } #[test] fn test_merge() { let mut a: VClock<u8> = vec![Dot::new(1, 1), Dot::new(4, 4)].into_iter().collect(); let b: VClock<u8> = vec![Dot::new(3, 3), Dot::new(4, 3)].into_iter().collect(); a.merge(b); let expected: VClock<u8> = vec![Dot::new(1, 1), Dot::new(3, 3), Dot::new(4, 4)] .into_iter() .collect(); assert_eq!(a, expected); } #[test] fn test_merge_less_left() { let (mut a, mut b) = (VClock::new(), VClock::new()); a.apply(Dot::new(5, 5)); b.apply(Dot::new(6, 6)); b.apply(Dot::new(7, 7)); a.merge(b); assert_eq!(a.get(&5), 5); assert_eq!(a.get(&6), 6); assert_eq!(a.get(&7), 7); } #[test] fn test_merge_less_right() { let (mut a, mut b) = (VClock::new(), VClock::new()); a.apply(Dot::new(6, 6)); a.apply(Dot::new(7, 7)); b.apply(Dot::new(5, 5)); a.merge(b); assert_eq!(a.get(&5), 5); assert_eq!(a.get(&6), 6); assert_eq!(a.get(&7), 7); } #[test] fn test_merge_same_id() { let (mut a, mut b) = (VClock::new(), VClock::new()); a.apply(Dot::new(1, 1)); a.apply(Dot::new(2, 1)); b.apply(Dot::new(1, 1)); b.apply(Dot::new(3, 1)); a.merge(b); assert_eq!(a.get(&1), 1); assert_eq!(a.get(&2), 1); assert_eq!(a.get(&3), 1); } #[test] #[allow(clippy::neg_cmp_op_on_partial_ord)] fn test_vclock_ordering() { assert_eq!(VClock::<i8>::new(), VClock::new()); let (mut a, mut b) = (VClock::new(), VClock::new()); a.apply(Dot::new("A".to_string(), 1)); a.apply(Dot::new("A".to_string(), 2)); a.apply(Dot::new("A".to_string(), 0)); b.apply(Dot::new("A".to_string(), 1)); // a {A:2} // b {A:1} // expect: a dominates assert!(a > b); assert!(b < a); assert!(a != b); b.apply(Dot::new("A".to_string(), 3)); // a {A:2} // b {A:3} // expect: b dominates assert!(b > a); assert!(a < b); assert!(a != b); a.apply(Dot::new("B".to_string(), 1)); // a {A:2, B:1} // b {A:3} // expect: concurrent assert!(a != b); assert!(!(a > b)); assert!(!(b > a)); a.apply(Dot::new("A".to_string(), 3)); // a {A:3, B:1} // b {A:3} // expect: a dominates assert!(a > b); assert!(b < a); assert!(a != b); b.apply(Dot::new("B".to_string(), 2)); // a {A:3, B:1} // b {A:3, B:2} // expect: b dominates assert!(b > a); assert!(a < b); assert!(a != b); a.apply(Dot::new("B".to_string(), 2)); // a {A:3, B:2} // b {A:3, B:2} // expect: equal assert!(!(b > a)); assert!(!(a > b)); assert_eq!(a, b); }
true
0e848fbb77223b5c77812bf1e2a90cca50d07d0f
Rust
ajaysusarla/rfc822dtparser
/rfc822dtparser/src/parser.rs
UTF-8
272
2.828125
3
[]
no_license
// // Copyright 2017 (c) Partha Susarla // use std::str; #[derive(Clone)] pub struct InputStr<'i> { chars: str::Chars<'i>, } impl<'i> InputStr<'i> { pub fn new(inputstr: &'i str) -> Self { let s = inputstr.trim(); InputStr { chars: s.chars() } } }
true
4ee358d0b33c785f04344520b9cefa14de90b3de
Rust
mklein994/weather-rs
/src/lib.rs
UTF-8
1,256
2.546875
3
[]
no_license
#[macro_use] extern crate clap; extern crate darksky; extern crate reqwest; extern crate serde_json; pub mod app; use app::{Config, OutputStyle}; use darksky::models::Forecast; use darksky::DarkskyReqwestRequester; use reqwest::Client; use std::error::Error; pub fn run(matches: &clap::ArgMatches) -> Result<(), Box<Error>> { let config = Config::parse_args(&matches)?; let weather = get_weather(&config)?; print_weather(&weather, &config.output_style)?; Ok(()) } fn get_weather(c: &Config) -> Result<Forecast, darksky::Error> { let client = Client::new(); if c.historical_time.is_some() { client.get_forecast_time_machine( &c.api_key, c.latitude, c.longitude, c.historical_time.unwrap(), |o| o, ) } else { client.get_forecast(&c.api_key, c.latitude, c.longitude) } } fn print_weather(weather: &Forecast, format: &OutputStyle) -> Result<(), serde_json::Error> { match format { OutputStyle::Parsed => println!("{:#?}", weather), OutputStyle::Json => println!("{}", serde_json::to_string(&weather)?), OutputStyle::PrettyJson => println!("{}", serde_json::to_string_pretty(&weather)?), }; Ok(()) }
true
fdfee3d26bf3eeba42f3bb169fc28b66a4ff1eb7
Rust
Tarabyte/rust-101
/threads_messaging/src/main.rs
UTF-8
1,816
3.421875
3
[ "MIT" ]
permissive
use std::thread; use std::time::Duration; use std::sync::mpsc::{channel, Sender, Receiver}; fn main() { test_threads_join(10); test_message_passing(); test_passing_multiple_times(); test_multiple_senders(); } fn test_multiple_senders() { fn report(thread_number: u64, tx: &Sender<String>) { let tx = Sender::clone(tx); thread::spawn(move || { for i in 1..10 { tx.send(format!("Message {} from thread {}.", i, thread_number)).unwrap(); thread::sleep(Duration::from_millis(100)); } }); } fn spawn(num: u8) -> Receiver<String> { let (tx, rx) = channel(); for i in 1..num + 1 { report(i as u64, &tx) } rx } let rx = spawn(3); for message in rx { println!("Got message: `{}`", message); } } fn test_passing_multiple_times() { let (tx, rx) = channel(); thread::spawn(move || { let v = vec![1, 2, 3]; for i in v { thread::sleep(Duration::from_millis(100)); println!("Sending {}", i); tx.send(i).unwrap(); } }); for item in rx { println!("received {}", item); } } fn test_message_passing() { let (tx, rx) = channel(); thread::spawn(move || { let v = vec![1, 2, 3]; tx.send(v).unwrap(); }); let v = rx.recv().unwrap(); println!("{:?}", v); } fn test_threads_join(delay: u64) { let handle = thread::spawn(move || { for i in 1..10 { println!("thread {}", i); thread::sleep(Duration::from_millis(delay)); } }); for i in 1..10 { println!("main {}", i); thread::sleep(Duration::from_millis(delay)); } handle.join().unwrap(); }
true
fd6000217bf0bdcb5efe1ab9368b90cad8cc327c
Rust
nvzqz/c-utf8-rs
/src/c_utf8_buf.rs
UTF-8
6,763
3.28125
3
[ "MIT", "Apache-2.0" ]
permissive
use std::borrow::{Borrow, BorrowMut, ToOwned}; use std::fmt; use std::iter::FromIterator; use std::ops::{Deref, DerefMut}; use c_utf8::CUtf8; use ext::Ext; /// An owned, mutable UTF-8 encoded C string (akin to [`String`] or /// [`PathBuf`]). /// /// # Examples /// /// This type retains certain behaviors that are expected from [`String`] such /// as calling [`.collect()`][collect] on iterators. /// /// ``` /// use c_utf8::CUtf8Buf; /// /// let strings = vec![ /// "Hello ", /// "there, ", /// "fellow ", /// "human!" /// ]; /// /// let joined = strings.into_iter().collect::<CUtf8Buf>(); /// let bytes = joined.as_bytes_with_nul(); /// /// assert_eq!(bytes, b"Hello there, fellow human!\0"); /// ``` /// /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html /// [`PathBuf`]: https://doc.rust-lang.org/std/path/struct.PathBuf.html /// [collect]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct CUtf8Buf(String); impl PartialEq<CUtf8> for CUtf8Buf { #[inline] fn eq(&self, other: &CUtf8) -> bool { (**self) == *other } } impl PartialEq<CUtf8Buf> for CUtf8 { #[inline] fn eq(&self, other: &CUtf8Buf) -> bool { other.eq(self) } } impl Default for CUtf8Buf { #[inline] fn default() -> CUtf8Buf { CUtf8Buf::new() } } impl Deref for CUtf8Buf { type Target = CUtf8; #[inline] fn deref(&self) -> &CUtf8 { unsafe { CUtf8::from_str_unchecked(&self.0) } } } impl DerefMut for CUtf8Buf { #[inline] fn deref_mut(&mut self) -> &mut CUtf8 { unsafe { CUtf8::from_str_unchecked_mut(&mut self.0) } } } impl<T> FromIterator<T> for CUtf8Buf where String: FromIterator<T> { #[inline] fn from_iter<I: IntoIterator<Item = T>>(it: I) -> CUtf8Buf { CUtf8Buf::from_string(it.into_iter().collect()) } } impl fmt::Debug for CUtf8Buf { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } } impl fmt::Display for CUtf8Buf { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } } impl fmt::Write for CUtf8Buf { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { self.push_str(s); Ok(()) } #[inline] fn write_char(&mut self, c: char) -> fmt::Result { self.push(c); Ok(()) } #[inline] fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { self.with_string(|s| s.write_fmt(args)) } } impl Borrow<CUtf8> for CUtf8Buf { #[inline] fn borrow(&self) -> &CUtf8 { self } } impl BorrowMut<CUtf8> for CUtf8Buf { #[inline] fn borrow_mut(&mut self) -> &mut CUtf8 { self } } impl AsRef<CUtf8> for CUtf8Buf { #[inline] fn as_ref(&self) -> &CUtf8 { self } } impl AsMut<CUtf8> for CUtf8Buf { #[inline] fn as_mut(&mut self) -> &mut CUtf8 { self } } impl ToOwned for CUtf8 { type Owned = CUtf8Buf; #[inline] fn to_owned(&self) -> CUtf8Buf { CUtf8Buf(self.as_str_with_nul().into()) } } impl<'a> From<&'a CUtf8> for CUtf8Buf { #[inline] fn from(c: &CUtf8) -> CUtf8Buf { c.to_owned() } } impl<'a> From<&'a mut CUtf8> for CUtf8Buf { #[inline] fn from(c: &mut CUtf8) -> CUtf8Buf { c.to_owned() } } impl From<String> for CUtf8Buf { #[inline] fn from(s: String) -> CUtf8Buf { CUtf8Buf::from_string(s) } } impl<'a> From<&'a str> for CUtf8Buf { #[inline] fn from(s: &str) -> CUtf8Buf { String::from(s).into() } } impl<'a> From<&'a mut str> for CUtf8Buf { #[inline] fn from(c: &mut str) -> CUtf8Buf { (c as &str).into() } } impl From<Box<CUtf8>> for CUtf8Buf { #[inline] fn from(b: Box<CUtf8>) -> CUtf8Buf { let raw = Box::into_raw(b) as *mut str; CUtf8Buf(unsafe { Box::from_raw(raw).into() }) } } impl From<CUtf8Buf> for Box<CUtf8> { #[inline] fn from(buf: CUtf8Buf) -> Box<CUtf8> { let raw = Box::into_raw(buf.0.into_boxed_str()) as *mut CUtf8; unsafe { Box::from_raw(raw) } } } impl From<CUtf8Buf> for String { #[inline] fn from(buf: CUtf8Buf) -> String { buf.into_string() } } impl From<CUtf8Buf> for Vec<u8> { #[inline] fn from(buf: CUtf8Buf) -> Vec<u8> { buf.into_bytes() } } impl CUtf8Buf { /// Creates a new empty `CUtf8Buf`. #[inline] pub fn new() -> CUtf8Buf { CUtf8Buf(unsafe { String::from_utf8_unchecked(vec![0; 1]) }) } /// Creates a new C string from a UTF-8 string, appending a nul /// terminator if one doesn't already exist. #[inline] pub fn from_string(mut s: String) -> CUtf8Buf { if !s.is_nul_terminated() { unsafe { s.as_mut_vec().push(0) }; } CUtf8Buf(s) } /// Creates a new C string from a native Rust string without checking for a /// nul terminator. #[inline] pub unsafe fn from_string_unchecked(s: String) -> CUtf8Buf { CUtf8Buf(s) } #[inline] fn with_string<F, T>(&mut self, f: F) -> T where F: FnOnce(&mut String) -> T { // Remove nul byte unsafe { self.0.as_mut_vec().pop() }; let val = f(&mut self.0); // Append nul byte unsafe { self.0.as_mut_vec().push(0) }; val } /// Appends a given string slice onto the end of this `CUtf8Buf`. #[inline] pub fn push_str(&mut self, s: &str) { self.with_string(|inner| inner.push_str(s)); } /// Appends the given `char` to the end of this `CUtf8Buf`. #[inline] pub fn push(&mut self, c: char) { self.with_string(|inner| inner.push(c)); } /// Converts `self` into a native UTF-8 encoded Rust /// [`String`](https://doc.rust-lang.org/std/string/struct.String.html). #[inline] pub fn into_string(self) -> String { let mut string = self.into_string_with_nul(); unsafe { string.as_mut_vec().pop() }; string } /// Converts `self` into a native UTF-8 encoded Rust /// [`String`](https://doc.rust-lang.org/std/string/struct.String.html) with /// a trailing 0 byte. #[inline] pub fn into_string_with_nul(self) -> String { self.0 } /// Converts `self` into its underlying bytes. #[inline] pub fn into_bytes(self) -> Vec<u8> { let mut bytes = self.into_bytes_with_nul(); bytes.pop(); bytes } /// Converts `self` into its underlying bytes with a trailing 0 byte. #[inline] pub fn into_bytes_with_nul(self) -> Vec<u8> { self.into_string_with_nul().into() } }
true
9856041c073255943883ac6d3370b6e8c914115f
Rust
alexander-smoktal/maul
/src/ast/rules.rs
UTF-8
13,803
2.859375
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(clippy::all)] #![cfg_attr(rustfmt, rustfmt_skip)] use std::collections::VecDeque; use crate::ast::parser; use crate::ast::stack; use crate::ast::expressions::*; use crate::ast::lexer::tokens::Keyword; const DEBUG: bool = false; fn ignore(_: &mut stack::Stack) -> bool { true } /// Removes sequences separators (commas, dots, etc). fn second(stack: &mut stack::Stack) { let (second, _first) = stack_unpack!(stack, single, single); stack.push_single(second); } /// Function prepends element on stack before last to the last vector-element (for varlist and namelist) fn prepend_vector_prefix(stack: &mut stack::Stack) { let (mut tail, head) = stack_unpack!(stack, repetition, single); tail.push_front(head); stack.push_repetition(tail); } /// Function to remove enclosing brackets pub fn remove_enclosing_brackets(stack: &mut stack::Stack) { let (_rb, expression, _lb) = stack_unpack!(stack, single, single, single); stack.push_single(expression); } // chunk ::= block rule!(chunk, block); // block ::= {stat} [retstat] rule!(block, and![(repetition!(stat), optional!(retstat, nil)) => blocks::Block::new]); // stat ::= ‘;’ | // varlist ‘=’ explist | // functioncall | // label | // break | // goto Name | // do block end | // while exp do block end | // repeat block until exp | // if exp then block {elseif exp then block} [else block] end | // for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end | // for namelist in explist do block end | // function funcname funcbody | // local function Name funcbody | // local namelist [‘=’ explist] rule!(stat, or![ and![(terminal!(Keyword::SEMICOLONS)) => ignore], and![(varlist, terminal!(Keyword::ASSIGN), explist) => variables::Assignment::new], functioncall, label, statements::Statement::breakstat, and![(terminal!(Keyword::GOTO), variables::Id::rule) => labels::Goto::new], and![(terminal!(Keyword::DO), block, terminal!(Keyword::END)) => blocks::DoBlock::new], and![(terminal!(Keyword::WHILE), exp, terminal!(Keyword::DO), block, terminal!(Keyword::END)) => blocks::WhileBlock::new], and![(terminal!(Keyword::REPEAT), block, terminal!(Keyword::UNTIL), exp) => blocks::RepeatBlock::new], and![( terminal!(Keyword::IF), exp, terminal!(Keyword::THEN), block, repetition!(and![( terminal!(Keyword::ELSEIF), exp, terminal!(Keyword::THEN), block ) => blocks::IfCondition::new_elseif]), optional!(and![(terminal!(Keyword::ELSE), block) => second], nil), terminal!(Keyword::END)) => blocks::IfBlock::new], and![( terminal!(Keyword::FOR), variables::Id::rule_string_id, or![ and![( terminal!(Keyword::ASSIGN), exp, terminal!(Keyword::COMMA), exp, optional!(and![(terminal!(Keyword::COMMA), exp) => second], nil), terminal!(Keyword::DO), block, terminal!(Keyword::END)) => blocks::NumericalForBlock::new], and![( and![(repetition!(and![(terminal!(Keyword::COMMA), variables::Id::rule_string_id) => second])) => prepend_vector_prefix], terminal!(Keyword::IN), explist, terminal!(Keyword::DO), block, terminal!(Keyword::END)) => blocks::GenericForBlock::new] ]) => ignore], and![(terminal!(Keyword::FUNCTION), funcname, funcbody) => function::Function::new], and![(terminal!(Keyword::LOCAL), or![ // Because function expects indication of method name, we push empty optional value after Id and![(terminal!(Keyword::FUNCTION), and![(variables::Id::rule) => |stack: &mut stack::Stack| { stack.push_optional(None) } ], funcbody) => function::Function::new], and![(namelist, variables::Assignment::rule_local) => ignore] ]) => blocks::Local::new] ]); // retstat ::= return [explist] [‘;’] rule!(retstat, and![(terminal!(Keyword::RETURN), optional!(and![(explist) => expression::Expressions::new], nil), optional!(terminal!(Keyword::SEMICOLONS), nil)) => |stack: &mut stack::Stack| { let (_semi, explist, _ret) = stack_unpack!(stack, optional, optional, single); stack.push_single(Box::new(statements::Statement::Return(explist))) }]); // label ::= ‘::’ Name ‘::’ rule!(label, and![(terminal!(Keyword::PATH), variables::Id::rule, terminal!(Keyword::PATH)) => labels::Label::new]); // funcname ::= Name {‘.’ Name} [‘:’ Name] rule!(funcname, and![( and![(variables::Id::rule, repetition!(and![(terminal!(Keyword::DOT), variables::Id::rule_string_id) => second])) => tables::Indexing::new_indexing_chain], optional!(and![(terminal!(Keyword::COLONS), variables::Id::rule_string_id) => second], nil)) => ignore]); // varlist ::= var {‘,’ var} // We push vector not expression on top to check assignment parity rule!(varlist, and![( var, repetition!(and![(terminal!(Keyword::COMMA), var) => second])) => prepend_vector_prefix]); // var_suffix ::= ‘[’ exp ‘]’ [var_suffix] | ‘.’ Name [var_suffix] rule!(var_suffix, or![ and![(and![(terminal!(Keyword::LSBRACKET), exp, terminal!(Keyword::RSBRACKET)) => tables::Indexing::new_table], optional!(var_suffix)) => ignore], and![(and![(terminal!(Keyword::DOT), variables::Id::rule_string_id) => tables::Indexing::new_object], optional!(var_suffix)) => ignore] ]); // var_repetition ::= var_suffix [var_repetition] | functioncall_suffix var_suffix [var_repetition] rule!(var_repetition, or![ and![(var_suffix, optional!(var_repetition)) => ignore], and![(functioncall_suffix, var_suffix, optional!(var_repetition)) => ignore] ]); // var ::= Name [var_repetition] | ‘(’ exp ‘)’ var_repetition rule!(var, or![ and![(variables::Id::rule, optional!(var_repetition)) => ignore], and![( and![(terminal!(Keyword::LBRACE), exp, terminal!(Keyword::RBRACE)) => remove_enclosing_brackets], var_repetition) => ignore]]); // namelist ::= Name {‘,’ Name} // We push vector not expression on top to check assignment parity rule!(namelist, and![( variables::Id::rule_string_id, repetition!(and![(terminal!(Keyword::COMMA), variables::Id::rule_string_id) => second])) => prepend_vector_prefix]); // explist ::= exp {‘,’ exp} rule!(explist, and![( exp, repetition!(and![( terminal!(Keyword::COMMA), exp) => second])) => prepend_vector_prefix]); // exp_suffix ::= binop [exp_suffix] rule!(exp_suffix, and![(binop, optional!(exp)) => ignore]); // exp_prefix ::= nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | // prefixexp | tableconstructor | unop exp rule!(exp_prefix, or![ primitives::Nil::rule, primitives::Boolean::rule, primitives::Number::rule, primitives::String::rule, statements::Statement::ellipsis, functiondef, prefixexp, tableconstructor, unop ]); // exp ::= binop rule!(exp, binop); // prefixexp_prefix ::= Name | ‘(’ exp ‘)’ rule!(prefixexp_prefix, or![ variables::Id::rule, and![(terminal!(Keyword::LBRACE), exp, terminal!(Keyword::RBRACE)) => remove_enclosing_brackets]]); // prefixexp_suffix ::= var_suffix [prefixexp_suffix] | functioncall_suffix [prefixexp_suffix] rule!(prefixexp_suffix, or![ and![(var_suffix, optional!(prefixexp_suffix)) => ignore], and![(functioncall_suffix, optional!(prefixexp_suffix)) => ignore] ]); // prefixexp ::= prefixexp_prefix [prefixexp_suffix] rule!(prefixexp, and![(prefixexp_prefix, optional!(prefixexp_suffix)) => ignore]); // To resolve 3-way recursion (prefixexp, var, functioncall), we need this set of rules // functioncall_suffix ::= args [functioncall_suffix] | ‘:’ Name args [functioncall_suffix] rule!(functioncall_suffix, or![ and![(and![(args) => function::Funcall::new], optional!(functioncall_suffix)) => ignore], and![(and![(terminal!(Keyword::COLONS), variables::Id::rule_string_id, args) => function::Funcall::new_self], optional!(functioncall_suffix)) => ignore] ]); // functioncall_repetition ::= functioncall_suffix [functioncall_repetition] | var_suffix [var_suffix] functioncall_suffix [functioncall_repetition] rule!(functioncall_repetition, or![ and![(functioncall_suffix, optional!(functioncall_repetition)) => ignore], and![(var_suffix, functioncall_suffix, optional!(functioncall_repetition)) => ignore] ]); // functioncall ::= prefixexp_prefix functioncall_repetition rule!(functioncall, and![(prefixexp_prefix, functioncall_repetition) => ignore]); // args ::= ‘(’ [explist] ‘)’ | tableconstructor | LiteralString rule!(args, or![ and![(terminal!(Keyword::LBRACE), optional!(explist), terminal!(Keyword::RBRACE)) => function::Funcall::new_args], tableconstructor, primitives::String::rule ]); // functiondef ::= function funcbody rule!(functiondef, and![(terminal!(Keyword::FUNCTION), funcbody) => function::Closure::new]); // funcbody ::= ‘(’ [parlist] ‘)’ block end rule!(funcbody, and![(and![(terminal!(Keyword::LBRACE), optional!(parlist), terminal!(Keyword::RBRACE)) => // This closure handles parameters. In case we have no parameters, pushed empty objects, // So closure could parse them |stack: &mut stack::Stack| { // rbrace stack.pop_single(); // Contains parameters if let stack::Element::Optional(_) = stack.peek() { let (ellipsis, params, _lb) = stack_unpack!(stack, optional, repetition, single); stack.push_repetition(params); stack.push_optional(ellipsis); } else { // lbrace stack.pop_single(); stack.push_repetition(VecDeque::new()); stack.push_optional(None); } }], block, terminal!(Keyword::END)) => ignore]); // -- Here we have a problem of prefix comma for both variants. Will resolve manually // -- Names always will produce vector and ellipsis will produce single element, which is the indicator of the end // See FunctionParameters::new* function for further documentation // parlist_name ::= Name [parlist_suffix] | ‘...’ rule!(parlist_name, or![ and![(and![(variables::Id::rule_string_id) => function::FunctionParameters::new_name], optional!(parlist_suffix)) => ignore], and![(and![(terminal!(Keyword::DOT3)) => function::FunctionParameters::new_namelist_varargs], optional!(parlist_suffix)) => ignore] ]); // parlist_suffix ::= ‘,’ parlist_name rule!(parlist_suffix, and![(terminal!(Keyword::COMMA), parlist_name) => ignore]); // TODO: Rewrite to manual parsing. This should be much cleaner // parlist ::= Name [parlist_suffix] | ‘...’ rule!(parlist, or![ and![( and![(variables::Id::rule_string_id) => |stack: &mut stack::Stack| { // Each name inside parameters list will produce repetition. Hence we do this with the first name too let name = stack.pop_single(); let mut vec = VecDeque::new(); vec.push_back(name); stack.push_repetition(vec) }], optional!(parlist_suffix)) => function::FunctionParameters::new_namelist], and![(terminal!(Keyword::DOT3)) => function::FunctionParameters::new_single_varargs] ]); // tableconstructor ::= ‘{’ [fieldlist] ‘}’ rule!(tableconstructor, and![(terminal!(Keyword::LCBRACKET), optional!(fieldlist), terminal!(Keyword::RCBRACKET)) => tables::Table::new]); // fieldlist_suffix ::= fieldsep [fieldlist] rule!(fieldlist_suffix, and![(fieldsep, optional!(fieldlist)) => ignore]); // fieldlist ::= field [fieldlist_prefix] rule!(fieldlist, and![( and![(field) => tables::TableField::new_list_name], optional!(fieldlist_suffix)) => ignore]); // field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp rule!(field, or![ and![(terminal!(Keyword::LSBRACKET), exp, terminal!(Keyword::RSBRACKET), terminal!(Keyword::ASSIGN), exp) => tables::TableField::new_table_index], and![(tables::TableField::name_rule, terminal!(Keyword::ASSIGN), exp) => tables::TableField::new_object_index], and![(exp) => tables::TableField::new_value] ]); // fieldsep ::= ‘,’ | ‘;’ rule!(fieldsep, or![ and![((terminal!(Keyword::COMMA))) => |stack: &mut stack::Stack| { stack.pop_single() }], and![((terminal!(Keyword::SEMICOLONS))) => |stack: &mut stack::Stack| { stack.pop_single() }] ]); // binop ::= ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘//’ | ‘^’ | ‘%’ | // ‘&’ | ‘~’ | ‘|’ | ‘>>’ | ‘<<’ | ‘..’ | // ‘<’ | ‘<=’ | ‘>’ | ‘>=’ | ‘==’ | ‘~=’ | // and | or rule!(binop, operators::Binop::rule); // unop ::= ‘-’ | not | ‘#’ | ‘~’ rule!(unop, operators::Unop::rule);
true
59cfc4521ac76866ca92f6380d0ea18e4ea96daf
Rust
GabeDottl/hearttoken_solana_template
/src/instruction.rs
UTF-8
13,117
3
3
[]
no_license
use crate::error::{VaultError, VaultError::InvalidInstruction}; use solana_program::program_error::ProgramError; use solana_program::{ instruction::{AccountMeta, Instruction}, pubkey::Pubkey, program_option::COption, sysvar, }; use std::convert::TryInto; use std::mem::size_of; pub enum VaultInstruction { /// Creates a Vault. /// /// Vaults are designed to be highly composable and don't directly hold any of their /// underlying asset (X) - instead, they just hold the underlying strategy's asset (lX) and then /// wraps it in its own mirror asset (llX) which is returned to the user. The user can redeem /// llX tokens for their underlying X token (plus profits) and will be charged a fixed fee /// against their returned assets. /// /// The interaction with a vault looks like the following: /// /// Deposit: /// User sends X to Vault, Vault sends X to the strategy and gets back an lX token, which it /// stores, and then mints a corresponding llX token which it gives to the user. /// Withdraw: /// User sends llX to Vault, Vault burns the tokens and sends the corresponding lX to the /// strategy and gets back X tokens, which it forwards to the user, minus a fee. /// /// Strategies should be contained within a single program and should implement the /// StrategyInstruction interface below. If a Strategy requires additional data, it can specify /// it in a data account which will be included in calls to the strategy instance. /// /// Accounts expected: /// `[signer]` initializer of the lx token account /// `[writeable]` Vault storage account (vault ID) /// `[]` lX token account /// `[]` The llX Token ID with this program is a mint authority. /// `[]` The strategy program's pubkey. /// `[]` The rent sysvar /// `[]` (Optional) Strategy instance data account /// `[]` (Optional) X token account if hodling. InitializeVault { // TODO: Governance address, strategist address, keeper address. // TODO: Withdrawal fee. // https://github.com/yearn/yearn-vaults/blob/master/contracts/BaseStrategy.sol#L781 strategy_program_deposit_instruction_id: u8, strategy_program_withdraw_instruction_id: u8, // TODO: Maybe change from bool to float percentage for holding. hodl: bool, }, /// Deposits a given token into the vault. /// /// Accounts expected: /// 1. `[signer]` The source wallet containing X tokens. /// 2. `[]` The destination wallet for llX tokens. /// 4. `[]` SPL Token program /// 3. `[]` The Vault storage account. /// `[]` (Optional) X SPL account owned by Vault if hodling. /// TODO: Signer pubkeys for multisignature wallets. Deposit { amount: u64 }, /// Withdraws a token from the strategy. /// /// Accounts expected: /// 2. `[signer]` Source Wallet for derivative token (lX). /// 1. `[]` Target token (X) wallet destination. /// 4. `[]` SPL Token program /// 3. `[]` The Vault storage account. /// `[]` (Optional) X SPL account owned by Vault if hodling. Withdraw { amount: u64, // # of derivative tokens. }, // / An implementation of a Hodl strategy. // / // / TODO: Move this to a separate program? // / Initializes a hodl strategy. // / // / Accounts expected: // / 1 `[signer]` initializer of tokens // / 1. `[writable]` Storage account // / 2. `[]` X token wallet // / 2. `[]` lx mint // / 3. `[]` The rent sysvar // InitializeHodlStrategy{}, // HodlStrategyDeposit { // amount: u64, // }, // HodlStrategyWithdraw { // amount: u64, // } } // Strategy programs should implement the following interface for strategies. pub enum StrategyInstruction { /// Deposits a token into the strategy. /// /// Accounts expected: /// 1. `[signer]` Source token (X) wallet /// 2. `[]` Target wallet for derivative token (lX) /// `[]` SPL Token program /// 3. `[]` (Optional) Strategy instance data account /// TODO: Additional signers. Deposit { amount: u64, // # of X tokens. }, /// Withdraws a token from the strategy. /// /// Accounts expected: /// 1. `[signer]` Source Wallet for derivative token (lX). /// 2. `[]` Target token (X) wallet destination. /// `[]` SPL Token program /// 3. `[]` (Optional) Strategy instance data account /// TODO: Additional signers. Withdraw { amount: u64, // # of lX tokens. }, } impl StrategyInstruction { /// Unpacks a byte buffer into a [VaultInstruction](enum.VaultInstruction.html). pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> { let (tag, rest) = input.split_first().ok_or(InvalidInstruction)?; Ok(match tag { 0 | 1 => { let amount = rest .get(..8) .and_then(|slice| slice.try_into().ok()) .map(u64::from_le_bytes) .ok_or(InvalidInstruction)?; match tag { 1 => Self::Deposit { amount }, 2 => Self::Withdraw { amount }, _ => return Err(VaultError::InvalidInstruction.into()), } } _ => return Err(VaultError::InvalidInstruction.into()), }) } fn pack(&self) -> Vec<u8> { let mut buf = Vec::with_capacity(size_of::<Self>()); match self { &Self::Deposit { amount } => { buf.push(2); buf.extend_from_slice(&amount.to_le_bytes()); } &Self::Withdraw { amount } => { buf.push(3); buf.extend_from_slice(&amount.to_le_bytes()); } } buf } pub fn deposit( program_id: &Pubkey, token_program_id: &Pubkey, source_pubkey: &Pubkey, target_pubkey: &Pubkey, additional_account_metas: Vec<AccountMeta>, amount: u64, ) -> Result<Instruction, ProgramError> { return create_transfer( Self::Deposit { amount }.pack(), program_id, token_program_id, source_pubkey, target_pubkey, additional_account_metas, ); } pub fn withdraw( program_id: &Pubkey, token_program_id: &Pubkey, source_pubkey: &Pubkey, target_pubkey: &Pubkey, additional_account_metas: Vec<AccountMeta>, amount: u64, ) -> Result<Instruction, ProgramError> { return create_transfer( Self::Withdraw { amount }.pack(), program_id, token_program_id, source_pubkey, target_pubkey, additional_account_metas, ); } } impl VaultInstruction { /// Unpacks a byte buffer into a [VaultInstruction](enum.VaultInstruction.html). pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> { let (tag, rest) = input.split_first().ok_or(InvalidInstruction)?; Ok(match tag { 0 => { let hodl = *rest.get(0).unwrap(); let strategy_program_deposit_instruction_id = *rest.get(0).unwrap(); let strategy_program_withdraw_instruction_id = *rest.get(1).unwrap(); Self::InitializeVault { hodl: if hodl == 1 { true } else { false }, strategy_program_deposit_instruction_id, strategy_program_withdraw_instruction_id, } } // 3 => { // Self::InitializeHodlStrategy{} // } 1 | 2 | 4 | 5 => { let amount = rest .get(..8) .and_then(|slice| slice.try_into().ok()) .map(u64::from_le_bytes) .ok_or(InvalidInstruction)?; match tag { 1 => Self::Deposit { amount }, 2 => Self::Withdraw { amount }, // 4 => Self::HodlStrategyDeposit { amount }, // 5 => Self::HodlStrategyWithdraw { amount }, _ => return Err(VaultError::InvalidInstruction.into()), } } _ => return Err(VaultError::InvalidInstruction.into()), }) } fn pack(&self) -> Vec<u8> { let mut buf = Vec::with_capacity(size_of::<Self>()); match self { &Self::InitializeVault { hodl, strategy_program_deposit_instruction_id, strategy_program_withdraw_instruction_id, } => { buf.push(0); buf.push(hodl as u8); buf.push(strategy_program_deposit_instruction_id); buf.push(strategy_program_withdraw_instruction_id); } &Self::Deposit { amount } => { buf.push(1); buf.extend_from_slice(&amount.to_le_bytes()); } &Self::Withdraw { amount } => { buf.push(2); buf.extend_from_slice(&amount.to_le_bytes()); } } buf } pub fn initialize_vault( vault_program_id: &Pubkey, initializer: &Pubkey, vault_storage_account: &Pubkey, lx_token_account: &Pubkey, llx_token_mint_id: &Pubkey, token_program: &Pubkey, strategy_program: &Pubkey, hodl: bool, x_token_account: COption<Pubkey>, strategy_program_deposit_instruction_id: u8, strategy_program_withdraw_instruction_id: u8, ) -> Result<Instruction, ProgramError> { let mut accounts = vec![ AccountMeta::new_readonly(*initializer, true), AccountMeta::new(*vault_storage_account, false), AccountMeta::new_readonly(*lx_token_account, false), AccountMeta::new_readonly(*llx_token_mint_id, false), AccountMeta::new_readonly(*token_program, false), AccountMeta::new_readonly(*strategy_program, false), AccountMeta::new_readonly(sysvar::rent::id(), false), ]; assert_eq!(hodl, x_token_account.is_some()); if hodl { accounts.push(AccountMeta::new_readonly(x_token_account.unwrap(), false)); } let data = VaultInstruction::InitializeVault { hodl, strategy_program_deposit_instruction_id, strategy_program_withdraw_instruction_id, } .pack(); Ok(Instruction { program_id: *vault_program_id, accounts, data, }) } pub fn deposit( vault_program_id: &Pubkey, token_program_id: &Pubkey, source_pubkey: &Pubkey, target_pubkey: &Pubkey, additional_account_metas: Vec<AccountMeta>, amount: u64, ) -> Result<Instruction, ProgramError> { return create_transfer( Self::Deposit { amount }.pack(), vault_program_id, token_program_id, source_pubkey, target_pubkey, additional_account_metas, ); } pub fn withdraw( vault_program_id: &Pubkey, token_program_id: &Pubkey, source_pubkey: &Pubkey, target_pubkey: &Pubkey, additional_account_metas: Vec<AccountMeta>, amount: u64, ) -> Result<Instruction, ProgramError> { return create_transfer( Self::Withdraw { amount }.pack(), vault_program_id, token_program_id, source_pubkey, target_pubkey, additional_account_metas, ); } // pub fn withdraw( // vault_program_id: &Pubkey, // token_program_id: &Pubkey, // source_pubkey: &Pubkey, // target_pubkey: &Pubkey, // amount: u64, // ) -> Result<Instruction, ProgramError> { // let data = VaultInstruction::Deposit { amount }.pack(); // let accounts = vec![ // AccountMeta::new(*source_pubkey, false), // AccountMeta::new(*target_pubkey, false), // AccountMeta::new_readonly(*token_program_id, false), // ]; // Ok(Instruction { // program_id: *vault_program_id, // accounts, // data, // }) // } } pub fn create_transfer( data: Vec<u8>, vault_program_id: &Pubkey, token_program_id: &Pubkey, source_pubkey: &Pubkey, target_pubkey: &Pubkey, additional_account_metas: Vec<AccountMeta>, ) -> Result<Instruction, ProgramError> { let mut accounts = vec![ AccountMeta::new_readonly(*token_program_id, false), AccountMeta::new(*source_pubkey, false), AccountMeta::new(*target_pubkey, false), ]; accounts.extend(additional_account_metas); Ok(Instruction { program_id: *vault_program_id, accounts, data, }) }
true
9b4a42ec310dad52b4733e7d887a6fa564938c8e
Rust
ens-ds23/ensembl-client
/src/assets/browser/app/src/model/train/trainmanager.rs
UTF-8
10,666
2.828125
3
[]
no_license
/* The trainmanager is responsible for creating and deleting TRAINS. * A train represents all the leafs prepared at some scale. * * The COMPOSITOR updates the train manager as to the current stick, * position, zoom, etc, for it to decide which trains are needed, * and provides a tick for animations. This class provides, in return, * a list of current trains to the compositor that it might provide such * info to the trains themselves. * * The PRINTER uses the trainmanager to get a list of leafs to actually * render. */ use composit::{ Leaf, ActiveSource, Stick, Scale, StateManager }; use controller::output::Report; use model::driver::PrinterManager; use super::{ Train, TravellerCreator }; const MS_FADE : f64 = 100.; const OUTER_TRAINS : usize = 0; pub struct TrainManager { printer: PrinterManager, /* the trains themselves */ current_train: Option<Train>, future_train: Option<Train>, transition_train: Option<Train>, outer_train: Vec<Option<Train>>, /* progress of transition */ transition_start: Option<f64>, transition_prop: Option<f64>, /* current position/scale */ stick: Option<Stick>, bp_per_screen: f64, position_bp: f64 } impl TrainManager { pub fn new(printer: &PrinterManager) -> TrainManager { let mut out = TrainManager { printer: printer.clone(), current_train: None, outer_train: Vec::<Option<Train>>::new(), future_train: None, transition_train: None, transition_start: None, transition_prop: None, bp_per_screen: 1., position_bp: 0., stick: None }; out.reset_outers(); out } pub fn update_report(&self, report: &Report) { if let Some(ref stick) = self.stick { report.set_status("stick",&stick.get_name()); } } fn reset_outers(&mut self) { for _ in 0..OUTER_TRAINS { self.outer_train.push(None); } } /* utility: makes new train at given scale */ fn make_train(&mut self, cm: &mut TravellerCreator, scale: Scale, preload: bool) -> Option<Train> { if let Some(ref stick) = self.stick { let mut f = Train::new(&self.printer,&stick,scale); f.set_position(self.position_bp); f.set_zoom(self.bp_per_screen); f.manage_leafs(cm); if !preload { f.enter_service(); } Some(f) } else { None } } /* COMPOSITOR sets new stick. Existing trains useless */ pub fn set_stick(&mut self, st: &Stick, bp_per_screen: f64) { // XXX not the right thing to do: should transition self.stick = Some(st.clone()); self.bp_per_screen = bp_per_screen; let scale = Scale::best_for_screen(bp_per_screen); self.each_train(|x| x.set_active(false)); self.current_train = Some(Train::new(&self.printer,st,scale)); self.current_train.as_mut().unwrap().set_zoom(bp_per_screen); self.current_train.as_mut().unwrap().set_current(); self.transition_train = None; self.future_train = None; self.current_train.as_mut().unwrap().set_active(true); self.reset_outers(); } /* ******************************************************** * Methods used by COMPOSITOR via ticks to run transitions. * ******************************************************** */ /* if there's a transition and it's reached endstop it is current */ fn transition_maybe_done(&mut self, t: f64) { if let Some(start) = self.transition_start { if t-start < MS_FADE { self.transition_prop = Some((t-start)/MS_FADE); } else { self.current_train = self.transition_train.take(); self.current_train.as_mut().unwrap().set_current(); self.transition_start = None; self.transition_prop = None; } } } /* if there is a future train and it is done, move to transition */ fn future_ready(&mut self, cm: &mut TravellerCreator, t: f64) { /* is it ready? */ let mut ready = false; if let Some(ref mut future_train) = self.future_train { if future_train.check_done() { ready = true; } } /* if future ready, transition empty, start one */ if ready && self.transition_train.is_none() { self.transition_train = self.future_train.take(); self.transition_start = Some(t); self.transition_prop = Some(0.); let scale = self.transition_train.as_ref().unwrap().get_scale().clone(); console!("transition to {:?}",scale); for i in 0..OUTER_TRAINS { let out_scale = scale.next_scale(-1-i as i32); self.outer_train[i] = self.make_train(cm,out_scale,true); } } } /* called regularly by compositor to let us perform transitions */ pub fn tick(&mut self, t: f64, cm: &mut TravellerCreator) { self.each_train(|t| { t.check_done(); }); self.transition_maybe_done(t); self.future_ready(cm,t); } /* used by COMPOSITOR to update trains as to manage components etc */ pub fn each_train<F>(&mut self, mut cb: F) where F: FnMut(&mut Train) { if let Some(ref mut current_train) = self.current_train { cb(current_train); } if let Some(ref mut transition_train) = self.transition_train { cb(transition_train); } if let Some(ref mut future_train) = self.future_train { cb(future_train); } for mut train in &mut self.outer_train { if let Some(ref mut train) = train { cb(train); } } } pub fn best_train<F>(&mut self, mut cb: F) where F: FnMut(&mut Train) { if let Some(ref mut future_train) = self.future_train { cb(future_train); } else if let Some(ref mut transition_train) = self.transition_train { cb(transition_train); } else if let Some(ref mut current_train) = self.current_train { cb(current_train); } } /* *********************************************************** * Methods used to manage future creation/destruction based on * indicated current bp/screen from COMPOSITOR * *********************************************************** */ /* current (or soon and inevitable) printing vscale. */ fn printing_vscale(&self) -> Option<Scale> { if let Some(ref transition_train) = self.transition_train { Some(transition_train.get_scale().clone()) } else if let Some(ref current_train) = self.current_train { Some(current_train.get_scale().clone()) } else { None } } /* Create future train */ fn new_future(&mut self, cm: &mut TravellerCreator, scale: Scale) { if let Some(ref mut t) = self.future_train { t.set_active(false); } self.future_train = self.make_train(cm,scale,false); self.future_train.as_mut().unwrap().set_active(true); } /* Abandon future train */ fn end_future(&mut self) { if let Some(ref mut t) = self.future_train { t.set_active(false); } self.future_train = None; } /* scale may have changed significantly to change trains */ fn maybe_change_trains(&mut self, cm: &mut TravellerCreator, bp_per_screen: f64) { if let Some(printing_vscale) = self.printing_vscale() { let best = Scale::best_for_screen(bp_per_screen); let mut end_future = false; let mut new_future = false; if best != printing_vscale { /* we're not currently showing the optimal scale */ if let Some(ref mut future_train) = self.future_train { /* there's a future train ... */ if best != *future_train.get_scale() { /* ... and that's not optimal either */ end_future = true; new_future = true; } } else { /* there's no future, we need one */ new_future = true; } } else if self.future_train.is_some() { /* Future exists, but current is fine. Abandon future */ end_future = true; } /* do anything that needs to be done */ if end_future { self.end_future(); } if new_future { self.new_future(cm,best); } } } /* compositor notifies of bp/screen update (change trains?) */ pub fn set_zoom(&mut self, cm: &mut TravellerCreator, bp_per_screen: f64) { self.bp_per_screen = bp_per_screen; self.maybe_change_trains(cm,bp_per_screen); self.each_train(|t| t.set_zoom(bp_per_screen)); } /* compositor notifies of position update */ pub fn set_position(&mut self, position_bp: f64) { self.position_bp = position_bp; self.each_train(|t| t.set_position(position_bp)); } pub fn update_state(&mut self, oom: &StateManager) { self.each_train(|t| t.update_state(oom)); } /* *************************************************************** * Methods used by PRINTER to actually retrieve data for printing. * *************************************************************** */ /* used by printer to set opacity */ pub fn get_prop_trans(&self) -> f32 { self.transition_prop.unwrap_or(0.) as f32 } /* used by printer to determine responsibilities */ pub fn all_printing_leafs(&self) -> Vec<Leaf> { let mut out = Vec::<Leaf>::new(); if let Some(ref transition_train) = self.transition_train { out.append(&mut transition_train.leafs()); } if let Some(ref current_train) = self.current_train { out.append(&mut current_train.leafs()); } out } /* used by printer for actual printing */ pub fn get_current_train(&mut self) -> Option<&mut Train> { self.current_train.as_mut() } /* used by printer for actual printing */ pub fn get_transition_train(&mut self) -> Option<&mut Train> { self.transition_train.as_mut() } }
true
49d8a6f5797f2a9edcbbe8c8c66e8fa3e1af3d9c
Rust
elsuizo/abstreet
/ezgui/src/widgets/no_op.rs
UTF-8
2,260
2.859375
3
[ "Apache-2.0" ]
permissive
use crate::layout::Widget; use crate::svg; use crate::{DrawBoth, EventCtx, GeomBatch, GfxCtx, RewriteColor, ScreenDims, ScreenPt, Text}; // Just draw something. A widget just so layouting works. pub struct JustDraw { draw: DrawBoth, top_left: ScreenPt, } impl JustDraw { pub fn wrap(draw: DrawBoth) -> JustDraw { JustDraw { draw, top_left: ScreenPt::new(0.0, 0.0), } } pub fn image(filename: &str, ctx: &EventCtx) -> JustDraw { let (color, rect) = ctx.canvas.texture_rect(filename); let batch = GeomBatch::from(vec![(color, rect)]); JustDraw { draw: DrawBoth::new(ctx, batch, vec![]), top_left: ScreenPt::new(0.0, 0.0), } } pub fn svg(filename: &str, ctx: &EventCtx) -> JustDraw { let mut batch = GeomBatch::new(); let bounds = svg::add_svg(&mut batch, filename); let mut draw = DrawBoth::new(ctx, batch, vec![]); // TODO The dims will be wrong; it'll only look at geometry, not the padding in the image. draw.override_bounds(bounds); JustDraw { draw, top_left: ScreenPt::new(0.0, 0.0), } } pub fn svg_transform(filename: &str, rewrite: RewriteColor, ctx: &EventCtx) -> JustDraw { let mut batch = GeomBatch::new(); let bounds = svg::add_svg(&mut batch, filename); batch.rewrite_color(rewrite); let mut draw = DrawBoth::new(ctx, batch, vec![]); // TODO The dims will be wrong; it'll only look at geometry, not the padding in the image. draw.override_bounds(bounds); JustDraw { draw, top_left: ScreenPt::new(0.0, 0.0), } } pub fn text(text: Text, ctx: &EventCtx) -> JustDraw { JustDraw { draw: DrawBoth::new(ctx, GeomBatch::new(), vec![(text, ScreenPt::new(0.0, 0.0))]), top_left: ScreenPt::new(0.0, 0.0), } } pub(crate) fn draw(&self, g: &mut GfxCtx) { self.draw.redraw(self.top_left, g); } } impl Widget for JustDraw { fn get_dims(&self) -> ScreenDims { self.draw.get_dims() } fn set_pos(&mut self, top_left: ScreenPt) { self.top_left = top_left; } }
true
6a1be17133b21233b7c7814430a2b92bb2cb55c9
Rust
XciD/descriptor
/tests/table_test.rs
UTF-8
5,399
3.078125
3
[ "Apache-2.0" ]
permissive
use descriptor::{table_describe_to_string, table_describe_with_header_to_string, Descriptor}; pub fn no_color_and_line_return(str: String) -> String { format!( "\n{}", String::from_utf8(strip_ansi_escapes::strip(str).unwrap()).unwrap() ) .to_string() } #[test] fn test_table_descriptor() { #[derive(Descriptor, Clone)] struct InnerA { state: String, value: String, } let table = vec![ InnerA { state: "f".to_string(), value: "bar".to_string(), }, InnerA { state: "foo".to_string(), value: "b".to_string(), }, ]; let table = table_describe_to_string(&table).unwrap(); assert_eq!( r#" STATE VALUE f bar foo b "#, no_color_and_line_return(table) ) } #[test] fn test_table_skip() { #[derive(Descriptor, Clone)] struct TableHide { table: String, long_column: String, small_one: String, #[descriptor(skip_header)] hidden_one: String, } let list = vec![ TableHide { table: "table".to_string(), long_column: "long".to_string(), small_one: "s".to_string(), hidden_one: "hidden".to_string(), }, TableHide { table: "row2".to_string(), long_column: "row".to_string(), small_one: "s".to_string(), hidden_one: "hidden".to_string(), }, ]; let table = table_describe_to_string(&list).unwrap(); assert_eq!( r#" TABLE LONG_COLUMN SMALL_ONE table long s row2 row s "#, no_color_and_line_return(table) ); let table = table_describe_with_header_to_string(&list, &vec!["hidden_one".to_string()]).unwrap(); assert_eq!( r#" HIDDEN_ONE hidden hidden "#, no_color_and_line_return(table) ); } #[test] fn test_table_headers() { #[derive(Descriptor, Clone)] #[descriptor(default_headers = ["table", "long_column"])] struct Table { table: String, long_column: String, small_one: String, } let table = vec![ Table { table: "table".to_string(), long_column: "long".to_string(), small_one: "s".to_string(), }, Table { table: "row2".to_string(), long_column: "row".to_string(), small_one: "s".to_string(), }, ]; let table = table_describe_to_string(&table).unwrap(); assert_eq!( r#" TABLE LONG_COLUMN table long row2 row "#, no_color_and_line_return(table) ); } #[test] fn test_table_inner() { #[derive(Descriptor)] struct Foo { string: String, } #[derive(Descriptor)] struct Bar { inner_foo: Foo, parent: String, } let foo = Bar { inner_foo: Foo { string: "c".to_string(), }, parent: "parent".to_string(), }; let table = table_describe_to_string(&vec![foo]).unwrap(); assert_eq!( r#" INNER_FOO.STRING PARENT c parent "#, no_color_and_line_return(table) ); } #[test] fn test_into_field_level() { #[derive(Descriptor)] struct Foo { #[descriptor(into = AnotherFoo)] foo: Bar, } struct Bar { foo: String, bar: String, } #[derive(Descriptor)] struct AnotherFoo { lorem: String, } impl From<&Bar> for AnotherFoo { fn from(f: &Bar) -> Self { Self { lorem: format!("{}-{}", f.foo, f.bar), } } } let table = table_describe_to_string(&vec![Foo { foo: Bar { foo: "a".to_string(), bar: "b".to_string(), }, }]) .unwrap(); assert_eq!( r#" FOO.LOREM a-b "#, no_color_and_line_return(table) ); } #[test] fn test_extra_fields() { #[derive(Descriptor)] #[descriptor(extra_fields = ExtraFieldsStruct)] struct Foo { first_field: String, number: u32, } #[derive(Descriptor)] struct ExtraFieldsStruct { anything: String, } impl From<&Foo> for ExtraFieldsStruct { fn from(b: &Foo) -> Self { Self { anything: format!("{}-{}", b.first_field, b.number / 10), } } } let table = table_describe_to_string(&vec![Foo { first_field: "test".to_string(), number: 200, }]) .unwrap(); assert_eq!( r#" FIRST_FIELD NUMBER ANYTHING test 200 test-20 "#, no_color_and_line_return(table) ); } #[test] fn test_map_all() { #[derive(Descriptor)] #[descriptor(map = map_all)] struct Foo { first_field: String, number: u32, } fn map_all(b: &Foo, field: String) -> String { if b.number > 2 { "-".to_string() } else { field } } let table = table_describe_to_string(&vec![ Foo { first_field: "test".to_string(), number: 200, }, Foo { first_field: "test".to_string(), number: 1, }, ]) .unwrap(); assert_eq!( r#" FIRST_FIELD NUMBER - - test 1 "#, no_color_and_line_return(table) ); }
true
e7e314be4f0b15cf7c99490047b766d972fa67bf
Rust
wgwoods/atsamd
/hal/src/samd11/sercom/pads.rs
UTF-8
1,384
2.59375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use crate::gpio::{self, IntoFunction, Port}; pub use crate::pad::PadPin; // sercom0[0]: PA04:D PA06:C PA14:C // sercom0[1]: PA05:D PA07:C PA15:C // sercom0[2]: PA04:C PA06:D PA08:D PA10:C // sercom0[3]: PA05:C PA07:D PA09:D PA11:C pad!(Sercom0Pad0 { Pa4(PfD), Pa6(PfC), Pa14(PfC), }); pad!(Sercom0Pad1 { Pa5(PfD), Pa7(PfC), Pa15(PfC), }); pad!(Sercom0Pad2 { Pa4(PfC), Pa6(PfD), Pa8(PfD), Pa10(PfC), }); pad!(Sercom0Pad3 { Pa5(PfC), Pa7(PfD), Pa9(PfD), Pa11(PfC), }); // sercom1[0]: PA22:C PA30:C // sercom1[1]: PA23:C PA31:C // sercom1[2]: PA08:C PA16:C PA30:D PA24:C // sercom1[3]: PA09:C PA17:C PA31:D PA25:C pad!(Sercom1Pad0 { Pa22(PfC), Pa30(PfC), }); pad!(Sercom1Pad1 { Pa23(PfC), Pa31(PfC), }); pad!(Sercom1Pad2 { Pa8(PfC), Pa16(PfC), Pa30(PfD), Pa24(PfC), }); pad!(Sercom1Pad3 { Pa9(PfC), Pa17(PfC), Pa31(PfD), Pa25(PfC), }); // sercom2[0]: PA14:D PA22:D // sercom2[1]: PA15:D PA23:D // sercom2[2]: PA10:D PA16:D PA24:D // sercom2[3]: PA11:D PA17:D PA25:D pad!(Sercom2Pad0 { Pa14(PfD), Pa22(PfD), }); pad!(Sercom2Pad1 { Pa15(PfD), Pa23(PfD), }); pad!(Sercom2Pad2 { Pa10(PfD), Pa16(PfD), Pa24(PfD), }); pad!(Sercom2Pad3 { Pa11(PfD), Pa17(PfD), Pa25(PfD), });
true
630d79a762d17a7b883640249ffd36cb3c0ef94c
Rust
acruikshank/bellman-examples
/src/circle.rs
UTF-8
4,836
2.78125
3
[]
no_license
#![allow(unused_imports)] #![allow(unused_variables)] extern crate bellman; extern crate pairing; extern crate rand; // For randomness (during paramgen and proof generation) use self::rand::{thread_rng, Rng}; // Bring in some tools for using pairing-friendly curves use self::pairing::{ Engine, Field, PrimeField }; // We're going to use the BLS12-381 pairing-friendly elliptic curve. use self::pairing::bls12_381::{ Bls12, Fr }; // We'll use these interfaces to construct our circuit. use self::bellman::{ Circuit, ConstraintSystem, SynthesisError }; // We're going to use the Groth16 proving system. use self::bellman::groth16::{ Proof, generate_random_parameters, prepare_verifying_key, create_random_proof, verify_proof, }; // proving that I know integer x and y such that (x, y) defines a point on a // circle with radius given as a public variable // Generalized: x^2 + y^2 == r^2 pub struct CircleDemo<E: Engine> { pub x: Option<E::Fr>, pub y: Option<E::Fr>, pub r: Option<E::Fr>, } impl <E: Engine> Circuit<E> for CircleDemo<E> { fn synthesize<CS: ConstraintSystem<E>>( self, cs: &mut CS ) -> Result<(), SynthesisError> { // Flattened into quadratic equations (x^2 + y^2 == r^2): // x * x = x_square // y * y = y_square // r * r = r_square // (x_square + y_square) * 1 = r_square // Resulting R1CS with w = [one, x, x_square, y, y_square, r, r_square] // Allocate the first private "auxiliary" variable let x_val = self.x; let x = cs.alloc(|| "x", || { x_val.ok_or(SynthesisError::AssignmentMissing) })?; // Allocate: x * x = x_square let x_square_val = x_val.map(|mut e| { e.square(); e }); let x_square = cs.alloc(|| "x_square", || { x_square_val.ok_or(SynthesisError::AssignmentMissing) })?; // Enforce: x * x = x_square cs.enforce( || "x_square", |lc| lc + x, |lc| lc + x, |lc| lc + x_square ); // Allocate the second private "auxiliary" variable let y_val = self.y; let y = cs.alloc(|| "y", || { y_val.ok_or(SynthesisError::AssignmentMissing) })?; // Allocate: y * y = y_square let y_square_val = y_val.map(|mut e| { e.square(); e }); let y_square = cs.alloc(|| "y_square", || { y_square_val.ok_or(SynthesisError::AssignmentMissing) })?; // Enforce: y * y = y_sqaure cs.enforce( || "y_square", |lc| lc + y, |lc| lc + y, |lc| lc + y_square ); // Allocating r (a public input) uses alloc_input let r = cs.alloc_input(|| "r", || { self.r.ok_or(SynthesisError::AssignmentMissing) })?; // Allocate: r * r = r_square let r_square_val = self.r.map(|mut e| { e.square(); e }); let r_square = cs.alloc(|| "r_square", || { r_square_val.ok_or(SynthesisError::AssignmentMissing) })?; // Enforce: r * r = r_sqaure cs.enforce( || "r_square", |lc| lc + r, |lc| lc + r, |lc| lc + r_square ); // x_square + y_sqaure = r_square // => (x_square + y_sqaure) * 1 = r_square cs.enforce( || "circle", |lc| lc + x_square + y_square, |lc| lc + CS::one(), |lc| lc + r_square ); Ok(()) } } #[test] fn test_circle_proof(){ // This may not be cryptographically safe, use // `OsRng` (for example) in production software. let rng = &mut thread_rng(); println!("SETUP: Creating parameters..."); // Create parameters for our circuit let params = { let c = CircleDemo::<Bls12> { x: None, y: None, r: None, }; generate_random_parameters(c, rng).unwrap() }; // Prepare the verification key (for proof verification) let pvk = prepare_verifying_key(&params.vk); let public_radius = Fr::from_str("5"); println!("Alice: Creating proofs..."); // Create an instance of circuit let c = CircleDemo::<Bls12> { x: Fr::from_str("4"), y: Fr::from_str("3"), r: public_radius, }; // Create a groth16 proof with our parameters. let proof = create_random_proof(c, &params, rng).unwrap(); println!("Bob: Verifying..."); assert!(verify_proof( &pvk, &proof, &[public_radius.unwrap()] ).unwrap()); }
true
00cad028d8aff68976fd7de322101e4ef0a2aef2
Rust
bbvch/ESE2016-HorizontErweitern-CodeBeispiele
/folienbeispiele/folie018-lebenszeiten-von-variablen.rs
UTF-8
240
3.25
3
[ "MIT" ]
permissive
use std::thread; fn worker(val: &mut i32) { println!("Working on {}", val); *val = *val + 1; } fn main() { let mut value = 1; for i in 0..3 { thread::spawn(|| { worker(&mut value) }); } }
true
2dce390efbff4cc6455be5b590568d1707bff9b9
Rust
isgasho/libunftp
/src/server/controlchan/commands/pasv.rs
UTF-8
4,272
2.578125
3
[ "Apache-2.0" ]
permissive
//! The RFC 959 Passive (`PASV`) command // // This command requests the server-DTP to "listen" on a data // port (which is not its default data port) and to wait for a // connection rather than initiate one upon receipt of a // transfer command. The response to this command includes the // host and port address this server is listening on. use crate::server::controlchan::error::ControlChanError; use crate::server::controlchan::handler::CommandContext; use crate::server::controlchan::handler::CommandHandler; use crate::server::controlchan::Command; use crate::server::controlchan::{Reply, ReplyCode}; use crate::storage; use crate::auth::UserDetail; use async_trait::async_trait; use futures::channel::mpsc::{channel, Receiver, Sender}; use rand::rngs::OsRng; use rand::RngCore; use std::io; use std::ops::Range; use tokio::net::TcpListener; use tokio::sync::Mutex; use lazy_static::*; const BIND_RETRIES: u8 = 10; lazy_static! { static ref OS_RNG: Mutex<OsRng> = Mutex::new(OsRng); } pub struct Pasv {} impl Pasv { pub fn new() -> Self { Pasv {} } async fn try_port_range(local_addr: std::net::SocketAddr, passive_addrs: Range<u16>) -> io::Result<TcpListener> { let rng_length = passive_addrs.end - passive_addrs.start; let mut listener: io::Result<TcpListener> = Err(io::Error::new(io::ErrorKind::InvalidInput, "Bind retries cannot be 0")); let mut rng = OS_RNG.lock().await; for _ in 1..BIND_RETRIES { let port = rng.next_u32() % rng_length as u32 + passive_addrs.start as u32; listener = TcpListener::bind(std::net::SocketAddr::new(local_addr.ip(), port as u16)).await; if listener.is_ok() { break; } } listener } } #[async_trait] impl<S, U> CommandHandler<S, U> for Pasv where U: UserDetail + 'static, S: 'static + storage::StorageBackend<U> + Sync + Send, S::File: tokio::io::AsyncRead + Send, S::Metadata: storage::Metadata, { async fn handle(&self, args: CommandContext<S, U>) -> Result<Reply, ControlChanError> { // obtain the ip address the client is connected to let conn_addr = match args.local_addr { std::net::SocketAddr::V4(addr) => addr, std::net::SocketAddr::V6(_) => panic!("we only listen on ipv4, so this shouldn't happen"), }; let listener = Pasv::try_port_range(args.local_addr, args.passive_ports).await; let mut listener = match listener { Err(_) => return Ok(Reply::new(ReplyCode::CantOpenDataConnection, "No data connection established")), Ok(l) => l, }; let addr = match listener.local_addr()? { std::net::SocketAddr::V4(addr) => addr, std::net::SocketAddr::V6(_) => panic!("we only listen on ipv4, so this shouldn't happen"), }; let octets = conn_addr.ip().octets(); let port = addr.port(); let p1 = port >> 8; let p2 = port - (p1 * 256); let tx = args.tx.clone(); let (cmd_tx, cmd_rx): (Sender<Command>, Receiver<Command>) = channel(1); let (data_abort_tx, data_abort_rx): (Sender<()>, Receiver<()>) = channel(1); { let mut session = args.session.lock().await; session.data_cmd_tx = Some(cmd_tx); session.data_cmd_rx = Some(cmd_rx); session.data_abort_tx = Some(data_abort_tx); session.data_abort_rx = Some(data_abort_rx); } let session = args.session.clone(); // Open the data connection in a new task and process it. // We cannot await this since we first need to let the client know where to connect :-) tokio::spawn(async move { if let Ok((socket, _socket_addr)) = listener.accept().await { let tx = tx.clone(); let session_arc = session.clone(); let mut session = session_arc.lock().await; session.spawn_data_processing(socket, tx); } }); Ok(Reply::new_with_string( ReplyCode::EnteringPassiveMode, format!("Entering Passive Mode ({},{},{},{},{},{})", octets[0], octets[1], octets[2], octets[3], p1, p2), )) } }
true
a098f0851d4b4d4760fa40a1ecaca9cb06bd2b0d
Rust
xi-editor/xi-editor
/rust/experimental/lang/src/peg.rs
UTF-8
9,476
2.9375
3
[ "Apache-2.0" ]
permissive
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Simple parser expression generator use std::char::from_u32; use std::ops; pub trait Peg { fn p(&self, s: &[u8]) -> Option<usize>; } impl<F: Fn(&[u8]) -> Option<usize>> Peg for F { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self(s) } } pub struct OneByte<F>(pub F); impl<F: Fn(u8) -> bool> Peg for OneByte<F> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { if s.is_empty() || !self.0(s[0]) { None } else { Some(1) } } } impl Peg for u8 { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { OneByte(|b| b == *self).p(s) } } pub struct OneChar<F>(pub F); fn decode_utf8(s: &[u8]) -> Option<(char, usize)> { if s.is_empty() { return None; } let b = s[0]; if b < 0x80 { return Some((b as char, 1)); } else if (0xc2..=0xe0).contains(&b) && s.len() >= 2 { let b2 = s[1]; if (b2 as i8) > -0x40 { return None; } let cp = (u32::from(b) << 6) + u32::from(b2) - 0x3080; return from_u32(cp).map(|ch| (ch, 2)); } else if (0xe0..=0xf0).contains(&b) && s.len() >= 3 { let b2 = s[1]; let b3 = s[2]; if (b2 as i8) > -0x40 || (b3 as i8) > -0x40 { return None; } let cp = (u32::from(b) << 12) + (u32::from(b2) << 6) + u32::from(b3) - 0xe2080; if cp < 0x800 { return None; } // overlong encoding return from_u32(cp).map(|ch| (ch, 3)); } else if (0xf0..=0xf5).contains(&b) && s.len() >= 4 { let b2 = s[1]; let b3 = s[2]; let b4 = s[3]; if (b2 as i8) > -0x40 || (b3 as i8) > -0x40 || (b4 as i8) > -0x40 { return None; } let cp = (u32::from(b) << 18) + (u32::from(b2) << 12) + (u32::from(b3) << 6) + u32::from(b4) - 0x03c8_2080; if cp < 0x10000 { return None; } // overlong encoding return from_u32(cp).map(|ch| (ch, 4)); } None } impl<F: Fn(char) -> bool> Peg for OneChar<F> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { if let Some((ch, len)) = decode_utf8(s) { if self.0(ch) { return Some(len); } } None } } // split out into a separate function to help inlining heuristics; even so, // prefer to use bytes even though they're not quite as ergonomic fn char_helper(s: &[u8], c: char) -> Option<usize> { OneChar(|x| x == c).p(s) } impl Peg for char { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { let c = *self; if c <= '\x7f' { (c as u8).p(s) } else { char_helper(s, c) } } } // byte ranges, including inclusive variants /// Use Inclusive(a..b) to indicate an inclusive range. When a...b syntax becomes /// stable, we'll get rid of this and switch to that. pub struct Inclusive<T>(pub T); impl Peg for ops::Range<u8> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { OneByte(|x| x >= self.start && x < self.end).p(s) } } impl Peg for Inclusive<ops::Range<u8>> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { OneByte(|x| x >= self.0.start && x <= self.0.end).p(s) } } // Note: char ranges are also possible, but probably not commonly used, and inefficient impl<'a> Peg for &'a [u8] { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { let len = self.len(); if s.len() >= len && &s[..len] == *self { Some(len) } else { None } } } impl<'a> Peg for &'a str { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.as_bytes().p(s) } } impl<P1: Peg, P2: Peg> Peg for (P1, P2) { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).and_then(|len1| self.1.p(&s[len1..]).map(|len2| len1 + len2)) } } impl<P1: Peg, P2: Peg, P3: Peg> Peg for (P1, P2, P3) { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).and_then(|len1| { self.1 .p(&s[len1..]) .and_then(|len2| self.2.p(&s[len1 + len2..]).map(|len3| len1 + len2 + len3)) }) } } macro_rules! impl_tuple { ( $( $p:ident $ix:ident ),* ) => { impl< $( $p : Peg ),* > Peg for ( $( $p ),* ) { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { let ( $( ref $ix ),* ) = *self; let mut i = 0; $( if let Some(len) = $ix.p(&s[i..]) { i += len; } else { return None; } )* Some(i) } } } } impl_tuple!(P1 p1, P2 p2, P3 p3, P4 p4); /// Choice from two heterogeneous alternatives. pub struct Alt<P1, P2>(pub P1, pub P2); impl<P1: Peg, P2: Peg> Peg for Alt<P1, P2> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).or_else(|| self.1.p(s)) } } /// Choice from three heterogeneous alternatives. pub struct Alt3<P1, P2, P3>(pub P1, pub P2, pub P3); impl<P1: Peg, P2: Peg, P3: Peg> Peg for Alt3<P1, P2, P3> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).or_else(|| self.1.p(s).or_else(|| self.2.p(s))) } } /// Choice from a homogenous slice of parsers. pub struct OneOf<'a, P: 'a>(pub &'a [P]); impl<'a, P: Peg> Peg for OneOf<'a, P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { for p in self.0.iter() { if let Some(len) = p.p(s) { return Some(len); } } None } } /// Repetition with a minimum and maximum (inclusive) bound pub struct Repeat<P, R>(pub P, pub R); impl<P: Peg> Peg for Repeat<P, usize> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let Repeat(ref p, reps) = *self; let mut i = 0; let mut count = 0; while count < reps { if let Some(len) = p.p(&s[i..]) { i += len; count += 1; } else { break; } } Some(i) } } impl<P: Peg> Peg for Repeat<P, ops::Range<usize>> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let Repeat(ref p, ops::Range { start, end }) = *self; let mut i = 0; let mut count = 0; while count + 1 < end { if let Some(len) = p.p(&s[i..]) { i += len; count += 1; } else { break; } } if count >= start { Some(i) } else { None } } } impl<P: Peg> Peg for Repeat<P, ops::RangeFrom<usize>> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let Repeat(ref p, ops::RangeFrom { start }) = *self; let mut i = 0; let mut count = 0; while let Some(len) = p.p(&s[i..]) { i += len; count += 1; } if count >= start { Some(i) } else { None } } } impl<P: Peg> Peg for Repeat<P, ops::RangeFull> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { ZeroOrMore(Ref(&self.0)).p(s) } } impl<P: Peg> Peg for Repeat<P, ops::RangeTo<usize>> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let Repeat(ref p, ops::RangeTo { end }) = *self; Repeat(Ref(p), 0..end).p(s) } } pub struct Optional<P>(pub P); impl<P: Peg> Peg for Optional<P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).or(Some(0)) } } #[allow(dead_code)] // not used by rust lang, but used in tests pub struct OneOrMore<P>(pub P); impl<P: Peg> Peg for OneOrMore<P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { Repeat(Ref(&self.0), 1..).p(s) } } pub struct ZeroOrMore<P>(pub P); impl<P: Peg> Peg for ZeroOrMore<P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let mut i = 0; while let Some(len) = self.0.p(&s[i..]) { i += len; } Some(i) } } /// Fail to match if the arg matches, otherwise match empty. pub struct FailIf<P>(pub P); impl<P: Peg> Peg for FailIf<P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { match self.0.p(s) { Some(_) => None, None => Some(0), } } } /// A wrapper to use whenever you have a reference to a Peg object pub struct Ref<'a, P: 'a>(pub &'a P); impl<'a, P: Peg> Peg for Ref<'a, P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s) } }
true
415225174d47070f32f8a85b4563b02687343b13
Rust
fatoche/asciifier
/src/lib.rs
UTF-8
1,673
3.59375
4
[ "Apache-2.0", "MIT" ]
permissive
pub mod asciifier { use std::collections::HashMap; pub struct Asciifier { character_map: HashMap<char, &'static str>, } impl Asciifier { pub fn new() -> Asciifier { let mut char_map = HashMap::with_capacity(20); char_map.insert('ä', "ae"); char_map.insert('ö', "oe"); char_map.insert('ü', "ue"); char_map.insert('Ä', "Ae"); char_map.insert('Ö', "Oe"); char_map.insert('Ü', "Ue"); char_map.insert('ß', "ss"); Asciifier { character_map: char_map, } } pub fn to_ascii(&self, from: String) -> String { let mut to = from; for (special_char, replacement) in &self.character_map { to = to.replace(*special_char, replacement); } to } } } #[cfg(test)] mod tests { #[test] fn replace_single_char() { let asciifier = super::Asciifier::new(); let ascii_string = asciifier.to_ascii("ä".to_string()); assert_eq!(&ascii_string, "ae"); } #[test] fn replace_lots() { let asciifier = super::Asciifier::new(); let utf8_str = "ÄÖÜßäöü"; //let utf8_str = "ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ"; let ascii_string = asciifier.to_ascii(utf8_str.to_string()); assert_eq!(&ascii_string, "AeOeUessaeoeue"); //assert_eq!(&ascii_string, "SOZsozYYuAAAAAAeACEEEEIIIIDNOOOOOeOeUUUUeYssaaaaaaeaceeeeiiiionoooooeoeuuuueyy"); } }
true
5bf6ea34fe4c78e47d9f25b64225fe41c97554f5
Rust
panicfrog/message-rust
/src/chat/model.rs
UTF-8
885
3
3
[]
no_license
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub enum ChatMessageType { // chat message OneToOne(usize), RoomMessage(String), Broadcast, // action Join(String), // message ack Ack, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct ChatMessage { #[serde(skip_serializing_if = "Option::is_none")] pub from: Option<usize>, pub style: ChatMessageType, #[serde(skip_serializing_if = "Option::is_none")] pub content: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub message_id: Option<String>, } impl ChatMessage { pub fn ack(message_id: String) -> Self { ChatMessage { from: None, style: ChatMessageType::Ack, content: None, message_id: Some(message_id), } } }
true
92deca0def12deb5a73e8f88b2d05331d15811cb
Rust
arun11299/Rust-Practice
/parser.rs
UTF-8
723
3.578125
4
[]
no_license
struct Context<'a>(&'a str); /// Syntax for telling that lifetime of /// Parser struct is longer than the lifetime /// of context. struct Parser<'c, 's : 'c> { context: &'c Context<'s>, } impl<'c, 's> Parser<'c, 's> { /// fn parse(&self) -> Result<(), &'s str> { Err(&self.context.0[1..]) } } /// Below definition of function parse_context will /// fail to compile because, as per the definition of /// the Parser structure, the Context has a lifetime same /// as that of the Parser. But, here we are returning the part /// of data associated with the context object (the string). /* fn parse_context(ctx : Context) -> Result<(), &str> { Parser{context : &ctx}.parse() } */ fn main() { }
true
9472488e0a05605c610c4b24c163ac274317122c
Rust
szymonwieloch/rust-dlopen
/examples/commons/mod.rs
UTF-8
1,366
2.515625
3
[ "MIT" ]
permissive
extern crate dlopen; extern crate libc; extern crate regex; use dlopen::utils::{PLATFORM_FILE_EXTENSION, PLATFORM_FILE_PREFIX}; use std::env; use std::path::PathBuf; use libc::c_int; //Rust when building dependencies adds some weird numbers to file names // find the file using this pattern: //const FILE_PATTERN: &str = concat!(PLATFORM_FILE_PREFIX, "example.*\\.", PLATFORM_FILE_EXTENSION); pub fn example_lib_path() -> PathBuf { let file_pattern = format!( r"{}example.*\.{}", PLATFORM_FILE_PREFIX, PLATFORM_FILE_EXTENSION ); let file_regex = regex::Regex::new(file_pattern.as_ref()).unwrap(); //build path to the example library that covers most cases let mut lib_path = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); lib_path.extend(["target", "debug", "deps"].iter()); let entry = lib_path.read_dir().unwrap().find(|e| match e { &Ok(ref entry) => file_regex.is_match(entry.file_name().to_str().unwrap()), &Err(ref err) => panic!("Could not read cargo debug directory: {}", err), }); lib_path.push(entry.unwrap().unwrap().file_name()); println!("Library path: {}", lib_path.to_str().unwrap()); lib_path } #[allow(dead_code)] //not all examples use this and this generates warnings #[repr(C)] pub struct SomeData { pub first: c_int, pub second: c_int, }
true
eab8786b7ec70da65860e3ce667750700c02c208
Rust
magurotuna/leetcode-rust
/src/bin/648.rs
UTF-8
1,045
3.421875
3
[]
no_license
struct Solution; impl Solution { pub fn replace_words(dict: Vec<String>, sentence: String) -> String { let mut ret = Vec::new(); let mut dict = dict; dict.sort_by_key(|d| d.len()); 'outer: for word in sentence.split(" ") { for root in dict.iter() { if word.starts_with(root) { ret.push(root.clone()); continue 'outer; } } ret.push(word.to_string()); } ret.join(" ") } } fn main() { todo!(); } #[cfg(test)] mod tests { use super::*; #[test] fn test_replace_words() { let dict = vec![ "cate".to_string(), "cat".to_string(), "bat".to_string(), "rat".to_string(), ]; let sentence = "category the cattle was rattled by the battery".to_string(); assert_eq!( Solution::replace_words(dict, sentence), "cat the cat was rat by the bat".to_string() ); } }
true
1c8f5a6b3086f17fb5ef4f9b001bf7efae831f22
Rust
r4gus/sugar-ray
/src/examples/projectile.rs
UTF-8
1,310
3.015625
3
[ "MIT" ]
permissive
use sugar_ray::math::{point::Point, vector::Vector}; use sugar_ray::canvas::{ *, color::*, }; use sugar_ray::ppm::*; use std::io::prelude::*; struct Projectile { pub position: Point, pub velocity: Vector, } struct Environment { pub gravity: Vector, pub wind: Vector, } fn tick<'a>(env:&Environment, proj: &'a mut Projectile) -> &'a Projectile { proj.position = proj.position + proj.velocity; proj.velocity = proj.velocity + env.gravity + env.wind; proj } pub fn fire() -> std::io::Result<()> { println!("Setting up Environment..."); let env = Environment { gravity: Vector::new(0.0,-0.1,0.0), wind: Vector::new(-0.01, 0.0, 0.0) }; println!("Loading projectile..."); let mut proj = Projectile { position: Point::new(0.0,1.0,0.0), velocity: Vector::new(1.0, 1.8, 0.0).norm_cpy() * 11.25 }; println!("Preparing canvas..."); let mut canvas = Canvas::new(900, 550); while proj.position.y() > 0.0 { tick(&env, &mut proj); // everything is inverted so we need to adapt the positions canvas.write_pixel(proj.position.x() as usize, 549 - (proj.position.y() as usize), Color::new(1.0, 0.0, 0.0)); } let mut f = std::fs::File::create("canvas.ppm")?; f.write_all(&canvas.to_ppm().into_bytes())?; Ok(()) }
true
b2bfe52b46d5e29a6deb4d0a863319c3651997a1
Rust
ivan770/teloxide
/src/requests/all/set_chat_sticker_set.rs
UTF-8
1,795
3.140625
3
[ "MIT" ]
permissive
use serde::Serialize; use crate::{ net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; /// Use this method to set a new group sticker set for a supergroup. /// /// The bot must be an administrator in the chat for this to work and must have /// the appropriate admin rights. Use the field can_set_sticker_set optionally /// returned in getChat requests to check if the bot can use this method. /// /// [The official docs](https://core.telegram.org/bots/api#setchatstickerset). #[serde_with_macros::skip_serializing_none] #[derive(Debug, Clone, Serialize)] pub struct SetChatStickerSet { #[serde(skip_serializing)] bot: Bot, chat_id: ChatId, sticker_set_name: String, } #[async_trait::async_trait] impl Request for SetChatStickerSet { type Output = True; async fn send(&self) -> ResponseResult<True> { net::request_json(self.bot.client(), self.bot.token(), "setChatStickerSet", &self).await } } impl SetChatStickerSet { pub(crate) fn new<C, S>(bot: Bot, chat_id: C, sticker_set_name: S) -> Self where C: Into<ChatId>, S: Into<String>, { let chat_id = chat_id.into(); let sticker_set_name = sticker_set_name.into(); Self { bot, chat_id, sticker_set_name } } /// Unique identifier for the target chat or username of the target /// supergroup (in the format `@supergroupusername`). pub fn chat_id<T>(mut self, val: T) -> Self where T: Into<ChatId>, { self.chat_id = val.into(); self } /// Name of the sticker set to be set as the group sticker set. pub fn sticker_set_name<T>(mut self, val: T) -> Self where T: Into<String>, { self.sticker_set_name = val.into(); self } }
true
8a3b62cd9e957c9d4623ef0368c257a865e1d5aa
Rust
thomaslienbacher/Moving-Tower
/src/ui.rs
UTF-8
4,581
3.015625
3
[ "MIT" ]
permissive
use sfml::graphics::*; use sfml::system::Vector2f; use sfml::window::Event; use sfml::window::mouse::Button; pub struct UiButton<'a> { shape: RectangleShape<'a>, text: Text<'a>, rect: FloatRect, clicked: bool, down: bool, fill_color: Color, border_color: Color, } const DOWN_SCALE: f32 = 0.97; const DARKENING_SCALE: f32 = 0.9; impl<'a> UiButton<'a> { pub fn new(font: &'a Font) -> UiButton<'a> { UiButton { shape: RectangleShape::new(), text: Text::new("", font, 16), rect: FloatRect::default(), clicked: false, down: false, fill_color: Color::WHITE, border_color: Color::BLACK, } } pub fn bounds(mut self, x: f32, y: f32, w: f32, h: f32) -> Self { self.rect = FloatRect::new(x, y, w, h); self.shape.set_size(Vector2f { x: w, y: h }); self } pub fn color(mut self, color: Color) -> Self { self.fill_color = color; self } pub fn border_color(mut self, color: Color) -> Self { self.border_color = color; self } pub fn border_thickness(mut self, thickness: f32) -> Self { self.shape.set_outline_thickness(thickness); self } pub fn text(mut self, text: &str) -> Self { self.text.set_string(text); self } pub fn char_size(mut self, size: u32) -> Self { self.text.set_character_size(size); self } pub fn text_color(mut self, color: Color) -> Self { self.text.set_fill_color(&color); self } pub fn pack(mut self) -> Self { self.shape.set_fill_color(&self.fill_color); self.shape.set_outline_color(&self.border_color); let pos = { let x = self.rect.left + self.rect.width / 2.0 - self.text.global_bounds().width / 2.0; let y = self.rect.top + self.rect.height / 2.0 - self.text.global_bounds().height;//TODO: divide by 2 ?? Vector2f::new(x.round(), y.round()) }; self.text.set_position(pos); let org = { let x = self.rect.width / 2.0; let y = self.rect.height / 2.0; Vector2f::new(x, y) }; self.shape.set_origin(org); self.shape.set_position(Vector2f::new(self.rect.left + org.x, self.rect.top + org.y)); self } //TODO: add more down state features pub fn draw(&self, win: &mut RenderWindow) { win.draw(&self.shape); win.draw(&self.text); } pub fn clicked(&mut self) -> bool { if self.clicked { self.clicked = false; return true; } false } pub fn event(&mut self, evt: Event) { match evt { Event::MouseButtonPressed { button: Button::Left, x, y } => { if self.rect.contains2(x as f32, y as f32) { self.shape.set_scale(Vector2f::new(DOWN_SCALE, DOWN_SCALE)); self.down = true; } } Event::MouseButtonReleased { button: Button::Left, x, y } => { if self.down && self.rect.contains2(x as f32, y as f32) { self.clicked = true; } self.shape.set_scale(Vector2f::new(1.0, 1.0)); self.down = false; } Event::MouseMoved { x, y } => { if self.rect.contains2(x as f32, y as f32) { let fc = { let mut c = self.fill_color.clone(); c.r = (c.r as f32 * DARKENING_SCALE) as u8; c.g = (c.g as f32 * DARKENING_SCALE) as u8; c.b = (c.b as f32 * DARKENING_SCALE) as u8; c }; let bc = { let mut c = self.border_color.clone(); c.r = (c.r as f32 * DARKENING_SCALE) as u8; c.g = (c.g as f32 * DARKENING_SCALE) as u8; c.b = (c.b as f32 * DARKENING_SCALE) as u8; c }; self.shape.set_fill_color(&fc); self.shape.set_outline_color(&bc); } else { self.shape.set_fill_color(&self.fill_color); self.shape.set_outline_color(&self.border_color); } } _ => {} } } }
true
aeca335e372e29ce6fec09569ea657feae3492b7
Rust
cloew/KaoBoy
/src/cpu/instructions/sources/addressed_by_short_source.rs
UTF-8
3,864
3.09375
3
[]
no_license
use super::{ByteSource, ConstantShortSource, DoubleRegisterSource, ShortSource}; use super::super::utils::{PostOpFn, dec_double_register, inc_double_register}; use super::super::super::instruction_context::InstructionContext; use super::super::super::registers::DoubleRegisterName; use crate::boxed; pub struct AddressedByShortSource { _address_source: Box<dyn ShortSource>, _follow_up_fn: Option<PostOpFn>, } impl AddressedByShortSource { pub fn new(address_source: Box<dyn ShortSource>) -> AddressedByShortSource { return AddressedByShortSource {_address_source: address_source, _follow_up_fn: None}; } pub fn new_from_constant() -> AddressedByShortSource { return AddressedByShortSource {_address_source: boxed!(ConstantShortSource::new()), _follow_up_fn: None}; } pub fn new_from_register(register_name: DoubleRegisterName) -> AddressedByShortSource { return AddressedByShortSource {_address_source: boxed!(DoubleRegisterSource::new(register_name)), _follow_up_fn: None}; } pub fn new_from_register_then_decrement(register_name: DoubleRegisterName) -> AddressedByShortSource { return AddressedByShortSource {_address_source: boxed!(DoubleRegisterSource::new(register_name)), _follow_up_fn: Some(dec_double_register)}; } pub fn new_from_register_then_increment(register_name: DoubleRegisterName) -> AddressedByShortSource { return AddressedByShortSource {_address_source: boxed!(DoubleRegisterSource::new(register_name)), _follow_up_fn: Some(inc_double_register)}; } } impl ByteSource for AddressedByShortSource { fn read(&self, context: &mut InstructionContext) -> u8 { let address = self._address_source.read(context); match self._follow_up_fn { Some(follow_up_fn) => (follow_up_fn)(context, DoubleRegisterName::HL), // Hardcode to HL since that's the only register with follow up logic None => (), } return context.memory().read_byte(address); } } #[cfg(test)] mod tests { use super::*; use crate::as_hex; use crate::cpu::testing::build_test_instruction_context; #[test] fn test_read_reads_memory() { const EXPECTED_VALUE: u8 = 0xAB; const EXPECTED_ADDRESS: u16 = 0x789A; let mut context = build_test_instruction_context(); context.registers_mut().hl.set(EXPECTED_ADDRESS); context.memory_mut().write_byte(EXPECTED_ADDRESS, EXPECTED_VALUE); let source = AddressedByShortSource::new_from_register(DoubleRegisterName::HL); let result = source.read(&mut context); assert_eq!(as_hex!(result), as_hex!(EXPECTED_VALUE)); } #[test] fn test_read_with_follow_up_reads_memory() { const EXPECTED_ADDRESS: u16 = 0xFEDC; const EXPECTED_VALUE: u8 = 0x78; let mut context = build_test_instruction_context(); context.registers_mut().hl.set(EXPECTED_ADDRESS); context.memory_mut().write_byte(EXPECTED_ADDRESS, EXPECTED_VALUE); let source = AddressedByShortSource::new_from_register_then_decrement(DoubleRegisterName::HL); let result = source.read(&mut context); assert_eq!(as_hex!(result), as_hex!(EXPECTED_VALUE)); } #[test] fn test_read_with_follow_up_fn() { const ORIGINAL_ADDRESS: u16 = 0xFEDC; const EXPECTED_ADDRESS: u16 = ORIGINAL_ADDRESS-1; let mut context = build_test_instruction_context(); context.registers_mut().hl.set(ORIGINAL_ADDRESS); let source = AddressedByShortSource::new_from_register_then_decrement(DoubleRegisterName::HL); source.read(&mut context); assert_eq!(as_hex!(context.registers_mut().hl), as_hex!(EXPECTED_ADDRESS)); } }
true
9d8ce068a4a460d59ef4df4d5a5d7baa0255c22d
Rust
KaitaoQiu/openlimits
/src/exchange/coinbase/model/book_record_l1.rs
UTF-8
499
2.71875
3
[ "BSD-2-Clause" ]
permissive
use serde::Deserialize; use serde::Serialize; use rust_decimal::prelude::Decimal; use super::BookLevel; use super::shared::string_to_decimal; /// This struct represents a level 1 book record #[derive(Serialize, Deserialize, Debug, Clone)] pub struct BookRecordL1 { #[serde(with = "string_to_decimal")] pub price: Decimal, #[serde(with = "string_to_decimal")] pub size: Decimal, pub num_orders: usize, } impl BookLevel for BookRecordL1 { fn level() -> u8 { 1 } }
true
91e541b3d25600b281e42cd5f7e24a9f072496ab
Rust
itsaramcc/ray-tracer
/src/hittable/sphere.rs
UTF-8
1,015
3.125
3
[]
no_license
use core::f64; use super::*; pub struct Sphere { center: Point3, radius: f64 } pub fn sphere(center: Point3, radius: f64) -> Sphere { Sphere { center, radius } } impl Hittable for Sphere { fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool { let oc = ray.origin() - self.center; let a = ray.direction().len_squared(); let half_b = oc.dot(&ray.direction()); let c = oc.dot(&oc) - self.radius*self.radius; let discriminant = half_b*half_b - a*c; if discriminant < 0.0 { return false; } let sqrtd = discriminant.sqrt(); // Find the nearest root that lies in the acceptable range. let mut root = (-half_b - sqrtd) / a; if root < t_min || t_max < root { root = (-half_b + sqrtd) / a; if root < t_min || t_max < root { return false; } } rec.t = root; rec.p = ray.at(rec.t); let outward_normal: Vec3 = (rec.p - self.center) / self.radius; rec.set_face_normal(ray, &outward_normal); true } }
true
72f0404da8c2abc59031e27e16cbeb5517a67f6b
Rust
instrumentisto/cqrs-rs
/cqrs-codegen/tests/event_sourced.rs
UTF-8
2,403
2.84375
3
[ "Apache-2.0" ]
permissive
#![allow(dead_code)] use std::marker::PhantomData; use cqrs::EventSourced as _; use cqrs_codegen::{Aggregate, Event, EventSourced}; #[derive(Aggregate, Default)] #[aggregate(type = "aggregate")] struct Aggregate { id: i32, event1_applied: bool, event2_applied: bool, event3_applied: bool, event4_applied: bool, } impl cqrs::EventSourced<Event1> for Aggregate { fn apply(&mut self, _ev: &Event1) { self.event1_applied = true; } } impl cqrs::EventSourced<Event2> for Aggregate { fn apply(&mut self, _ev: &Event2) { self.event2_applied = true; } } impl<T> cqrs::EventSourced<Event3<T>> for Aggregate { fn apply(&mut self, _ev: &Event3<T>) { self.event3_applied = true; } } impl<T> cqrs::EventSourced<Event4<T>> for Aggregate { fn apply(&mut self, _ev: &Event4<T>) { self.event4_applied = true; } } #[derive(Default, Event)] #[event(type = "event.1")] struct Event1; #[derive(Default, Event)] #[event(type = "event.2")] struct Event2; #[derive(Default, Event)] #[event(type = "event.3")] struct Event3<T>(PhantomData<*const T>); #[derive(Default, Event)] #[event(type = "event.4")] struct Event4<T>(PhantomData<*const T>); #[test] fn derives_for_enum() { #[derive(Event, EventSourced)] #[event_sourced(aggregate = "Aggregate")] enum Event { Event1(Event1), Event2 { event: Event2 }, } let mut aggregate = Aggregate::default(); aggregate.apply(&Event::Event1(Event1)); aggregate.apply(&Event::Event2 { event: Event2 }); assert!(aggregate.event1_applied); assert!(aggregate.event2_applied); } #[test] fn derives_for_generic_enum() { #[derive(Event, EventSourced)] #[event_sourced(aggregate = "Aggregate")] enum Event<E3, E4> { Event1(Event1), Event2 { event: Event2 }, Event3(Event3<E3>), Event4 { event: Event4<E4> }, } let mut aggregate = Aggregate::default(); aggregate.apply(&Event::<u32, i32>::Event1(Event1)); aggregate.apply(&Event::<u32, i32>::Event2 { event: Event2 }); aggregate.apply(&Event::<u32, i32>::Event3(Event3::default())); aggregate.apply(&Event::<u32, i32>::Event4 { event: Event4::default(), }); assert!(aggregate.event1_applied); assert!(aggregate.event2_applied); assert!(aggregate.event3_applied); assert!(aggregate.event4_applied); }
true
a4ba50807a52d05b9933d2cfbd65383e096b6463
Rust
Origen-SDK/o2
/rust/origen/src/generator/processors/upcase_comments.rs
UTF-8
1,528
3.4375
3
[ "MIT" ]
permissive
//! A very simple example processor which returns a new version of the //! given AST with all comments changed to upper case. use super::super::nodes::PAT; use crate::Result; use origen_metal::ast::*; pub struct UpcaseComments {} impl UpcaseComments { #[allow(dead_code)] pub fn run(node: &Node<PAT>) -> Result<Node<PAT>> { let mut p = UpcaseComments {}; Ok(node.process(&mut p)?.unwrap()) } } impl Processor<PAT> for UpcaseComments { fn on_node(&mut self, node: &Node<PAT>) -> origen_metal::Result<Return<PAT>> { match &node.attrs { PAT::Comment(level, msg) => { let new_node = node.replace_attrs(PAT::Comment(*level, msg.to_uppercase())); Ok(Return::Replace(new_node)) } _ => Ok(Return::ProcessChildren), } } } #[cfg(test)] mod tests { use super::*; use crate::generator::nodes::PAT; #[test] fn it_works() { let mut ast = AST::new(); ast.push_and_open(node!(PAT::Test, "t1".to_string())); ast.push(node!(PAT::Cycle, 1, false)); ast.push(node!(PAT::Comment, 1, "some comment".to_string())); let mut expect = AST::new(); expect.push_and_open(node!(PAT::Test, "t1".to_string())); expect.push(node!(PAT::Cycle, 1, false)); expect.push(node!(PAT::Comment, 1, "SOME COMMENT".to_string())); assert_eq!( UpcaseComments::run(&ast.to_node()).expect("Comments upcased"), expect ); } }
true
a1cb5663a47253e51e3e9b3a0f6d61fc983ef551
Rust
Matthias247/futures-intrusive
/src/channel/error.rs
UTF-8
1,952
3.734375
4
[ "Apache-2.0", "MIT" ]
permissive
/// The error which is returned when sending a value into a channel fails. /// /// The `send` operation can only fail if the channel has been closed, which /// would prevent the other actors to ever retrieve the value. /// /// The error recovers the value that has been sent. #[derive(PartialEq, Debug)] pub struct ChannelSendError<T>(pub T); /// The error which is returned when trying to receive from a channel /// without waiting fails. #[derive(PartialEq, Debug, Copy, Clone)] pub enum TryReceiveError { /// The channel is empty. No value is available for reception. Empty, /// The channel had been closed and no more value is available for reception. Closed, } impl TryReceiveError { /// Returns whether the error is the `Empty` variant. pub fn is_empty(self) -> bool { match self { Self::Empty => true, _ => false, } } /// Returns whether the error is the `Closed` variant. pub fn is_closed(self) -> bool { match self { Self::Closed => true, _ => false, } } } /// The error which is returned when trying to send on a channel /// without waiting fails. #[derive(PartialEq, Debug)] pub enum TrySendError<T> { /// The channel is full. Full(T), /// The channel was closed. Closed(T), } impl<T> TrySendError<T> { /// Converts the error into its inner value. pub fn into_inner(self) -> T { match self { Self::Closed(inner) => inner, Self::Full(inner) => inner, } } /// Returns whether the error is the `WouldBlock` variant. pub fn is_full(&self) -> bool { match self { Self::Full(_) => true, _ => false, } } /// Returns whether the error is the `Closed` variant. pub fn is_closed(&self) -> bool { match self { Self::Closed(_) => true, _ => false, } } }
true
0e0bb54a55332e60639f284b95ffaef0b1c54673
Rust
arve0/build-your-own-couchdb
/sakkosekk/src/tests.rs
UTF-8
2,439
3.171875
3
[]
no_license
#[cfg(test)] mod database { use crate::*; use rusqlite::Connection; use std::fs::remove_file; #[test] fn creating_database_twice_should_not_fail() { with("creating_twice.sqlite", |_| { get_db_create_if_missing("creating_twice.sqlite"); }); } #[test] fn insertion() { with("insertion.sqlite", |db| { get_document(0) .insert(&db) .expect("Unable to insert document."); }); } #[test] fn double_insertion_should_fail() { with("double_insertion.sqlite", |db| { get_document(0) .insert(&db) .expect("Unable to insert document."); let second_insert_result = get_document(0).insert(&db); assert!(second_insert_result.is_err()); }); } #[test] fn insert_multiple_revisions() { with("insert_multiple_revisions.sqlite", |db| { get_document(0) .insert(&db) .expect("Unable to insert document."); get_document(1) .insert(&db) .expect("Unable to insert document."); }); } #[test] fn get_by_missing_id_should_give_no_results() { with("get_by_id_missing.sqlite", |db| { let documents = Document::get_by_id("asdf", &db).expect("Unable to get documents."); assert!(documents.is_empty()); }); } #[test] fn get_by_id() { with("get_by_id.sqlite", |db| { get_document(0) .insert(&db) .expect("Unable to insert document."); get_document(1) .insert(&db) .expect("Unable to insert document."); let documents_from_db = Document::get_by_id("asdf", &db); assert!(documents_from_db == Ok(vec![get_document(0), get_document(1)])); }); } fn with<F>(filename: &str, test: F) where F: Fn(Connection) -> (), { remove_file(filename).unwrap_or(()); let db = get_db_create_if_missing(filename); test(db); remove_file(filename).unwrap(); } fn get_document(revision: i64) -> Document { Document { id: String::from("asdf"), revision: revision, hash: vec![0u8], data: String::from(r#"{ "a": 1, "b": 123 }"#), } } }
true
b9a505239118bb432e2c8f4b556720b073867172
Rust
maulikchevli/cns
/caesar-cipher-rs/main.rs
UTF-8
3,393
3.21875
3
[]
no_license
use std::io; use std::io::prelude::*; mod caesar; fn main() { let mut choice = String::new(); loop { println!("CHoice: \nencrypt, decrypt, brute force, frequency analysis, exit"); println!("Enter Choice: "); io::stdin().read_line(&mut choice) .expect("Failed to read line"); println!("choice: {}", choice); // Input thru stdin contains new line character match choice.trim() { "encrypt" => encrypt_caesar(), "decrypt" => decrypt_caesar(), "brute force" => brute_caesar(), "frequency" => frequency_analysis(), "exit" => break, _ => println!("No option"), } choice.clear(); println!("---------------"); } } fn frequency_analysis() { let mut file_name = String::new(); println!("Enter filename:"); io::stdin().read_line(&mut file_name) .expect("Plain Text"); let file_name = file_name.trim(); use std::fs::File; let mut f = File::open(file_name).expect("Unable to open"); let mut cipher_text = String::new(); f.read_to_string(&mut cipher_text).unwrap(); print!("Cipher text: \n{}", cipher_text); print!("Plain text by Frequency analysis: \n{}", caesar::frequency_analysis(&cipher_text)); } fn brute_caesar() { let mut file_name = String::new(); println!("Enter filename:"); io::stdin().read_line(&mut file_name) .expect("Plain Text"); let file_name = file_name.trim(); use std::fs::File; let mut f = File::open(file_name).expect("Unable to open"); let mut cipher_text = String::new(); f.read_to_string(&mut cipher_text).unwrap(); print!("Cipher text: \n{}", cipher_text); print!("Brute Force::"); for key in 1..27 { println!("-------------------"); println!("Key {}", key); println!("{}", caesar::decipher(&cipher_text, key)); } } fn encrypt_caesar() { let mut key = String::new(); println!("Enter key value:"); io::stdin().read_line(&mut key) .expect("Failed to read key"); // Convert to u8 let key: u8 = key.trim().parse().expect("Invalid Input"); let mut file_name = String::new(); println!("Enter filename:"); io::stdin().read_line(&mut file_name) .expect("Plain Text"); let file_name = file_name.trim(); use std::fs::File; let mut f = File::open(file_name).expect("Unable to open"); let mut plain_text = String::new(); f.read_to_string(&mut plain_text).unwrap(); print!("plain text: \n{}", plain_text); print!("Cipher Text:\n{}", caesar::cipher(&plain_text, key)); } fn decrypt_caesar() { let mut key = String::new(); println!("Enter key value:"); io::stdin().read_line(&mut key) .expect("Failed to read key"); // Convert to u8 let key: u8 = key.trim().parse().expect("Invalid Input"); let mut file_name = String::new(); println!("Enter filename:"); io::stdin().read_line(&mut file_name) .expect("Plain Text"); let file_name = file_name.trim(); use std::fs::File; let mut f = File::open(file_name).expect("Unable to open"); let mut cipher_text = String::new(); f.read_to_string(&mut cipher_text).unwrap(); print!("Cipher text: \n{}", cipher_text); print!("Plain Text:\n{}", caesar::decipher(&cipher_text, key)); }
true
6c49581bc1ed96cc7f6693bdd6d6e04c1abc4590
Rust
prataprc/gist
/rs/euler/src/problem0005.rs
UTF-8
864
3.390625
3
[ "MIT" ]
permissive
use primes; /// 2520 is the smallest number that can be divided by each of the numbers /// from 1 to 10 without any remainder. /// What is the smallest positive number that is evenly divisible by all /// of the numbers from 1 to 20? pub fn solve() { let primes: Vec<u32> = primes::Primes::new(20).collect(); let mut result = primes.iter().fold(1, |a, x| a * x); let mut pr = primes::Primes::new(20); let mut factors = Vec::with_capacity(20); for x in vec![4,6,8,10,12,14,15,16,18,20] { let mut val = result; pr.prime_factors(x, &mut factors); for p in factors.iter() { if (val % p) == 0 { val /= p } else { result *= p } } factors.truncate(0); } println!( "smallest positive number that is evenly divisible \ by all of the numbers from 1 to 20 : {}", result ); }
true
d0b4a601c1abb6109ba69026f1aea0f617de213a
Rust
keiono/egraph-rs
/crates/egraph/src/algorithm/connected_components.rs
UTF-8
1,605
2.96875
3
[ "MIT" ]
permissive
use crate::Graph; use std::collections::{HashMap, HashSet, VecDeque}; pub fn connected_components<D, G: Graph<D>>(graph: &G) -> HashMap<usize, usize> { let mut components = HashMap::new(); let mut visited = HashSet::new(); let mut queue = VecDeque::new(); for u in graph.nodes() { if visited.contains(&u) { continue; } queue.push_back(u); while queue.len() > 0 { let v = queue.pop_front().unwrap(); if visited.contains(&v) { continue; } visited.insert(v); components.insert(v, u); for w in graph.neighbors(v) { queue.push_back(w); } } } components } #[cfg(test)] mod test { use super::*; use egraph_petgraph_adapter::PetgraphWrapper; use petgraph::prelude::Graph; #[test] fn test_connected_components() { let mut graph = Graph::new_undirected(); let u1 = graph.add_node(()); let u2 = graph.add_node(()); let u3 = graph.add_node(()); let u4 = graph.add_node(()); let u5 = graph.add_node(()); graph.add_edge(u1, u2, ()); graph.add_edge(u1, u3, ()); graph.add_edge(u2, u3, ()); graph.add_edge(u4, u5, ()); let graph = PetgraphWrapper::new(graph); let components = connected_components(&graph); assert_eq!(components[&0], 0); assert_eq!(components[&1], 0); assert_eq!(components[&2], 0); assert_eq!(components[&3], 3); assert_eq!(components[&4], 3); } }
true
61e3030ee7baa698635f82842232ccd6417c7444
Rust
flosmn/coding
/project_euler/problem_002/solution.rs
UTF-8
199
2.9375
3
[]
no_license
fn main() { let mut x0 = 1; let mut x1 = 1; let mut sum = 0; while x1 < 4000000 { if x1 % 2 == 0 { sum += x1; } let x2 = x0 + x1; x0 = x1; x1 = x2; } println!("sum: {}", sum); }
true
8249bd15cadb14c197002240a62771ca34387ed8
Rust
rschifflin/rust-entity-component-system
/src/systems/color_system.rs
UTF-8
598
2.625
3
[]
no_license
use pubsub::Pubsub; use pubsub::Event; use components::color_component::ColorComponent; use ECS; #[derive(Copy)] pub struct ColorSystem; impl ColorSystem { pub fn subscribe(pubsub: &mut Pubsub<ECS, String, String>) { pubsub.subscribe("component_color".to_string(), ColorSystem::add_listener); } fn add_listener(ecs: &mut ECS, payload: String) -> Vec<Event<String, String>> { ecs.colors.update_color(payload.clone(), ColorComponent::red(payload)); vec![ Event { channel: "log".to_string(), payload: "Added color component!".to_string() } ] } }
true
9e01f5799dfc0d5858c1d4164f604871723c7fe8
Rust
hannahellis4242/sudoku_solver
/src/main.rs
UTF-8
6,414
2.71875
3
[ "MIT" ]
permissive
extern crate futures; extern crate hyper; extern crate itertools; #[macro_use] extern crate serde_json; extern crate valico; use hyper::server::{Request, Response, Service}; use hyper::Method::Get; use hyper::{Chunk, StatusCode}; use futures::future::{Future, FutureResult}; use futures::Stream; mod sudoku; mod json_to_sudoku { use serde_json; fn parse_value(s: &str) -> Option<char> { s.chars() .fold(None, |acc, x| if acc.is_none() { Some(x) } else { acc }) .and_then(|x| if x == '-' { None } else { Some(x) }) } pub fn validate_json(j: serde_json::Value) -> Result<serde_json::Value, String> { use valico::json_dsl; let params = json_dsl::Builder::build(|params| { params.req_nested("grid", json_dsl::object(), |params| { params.req_typed("height", json_dsl::u64()); params.req_typed("square", json_dsl::u64()); params.req_typed("values", json_dsl::array_of(json_dsl::string())); params.req_typed("width", json_dsl::u64()) }); params.req_typed("values", json_dsl::array_of(json_dsl::string())) }); let mut obj = j.clone(); let state = params.process(&mut obj, &None); if state.is_valid() { Ok(obj) } else { Err(format!("{:?}", state)) } } use sudoku; pub fn parse(j: serde_json::Value) -> Result<sudoku::Problem, String> { j["grid"]["height"] .as_u64() .map(|x| x as usize) .and_then(|height| { j["grid"]["width"] .as_u64() .map(|x| x as usize) .map(|width| (height, width)) }).and_then(|(height, width)| { j["grid"]["square"] .as_u64() .map(|x| x as usize) .map(|square| (height, width, square)) }).and_then(|(height, width, square)| { j["grid"]["values"] .as_array() .map(|x| { x.iter() .filter_map(|y| y.as_str().and_then(parse_value)) .collect::<Vec<char>>() }).map(|grid_values| (height, width, square, grid_values)) }).and_then(|(height, width, square, grid_values)| { j["values"] .as_array() .map(|x| { x.iter() .map(|y| y.as_str().and_then(parse_value)) .collect::<Vec<Option<char>>>() }).map(|values| (height, width, square, grid_values, values)) }).map( |(height, width, square, grid_values, values)| sudoku::Problem { grid: sudoku::GridInfo { height: height, width: width, square: square, values: grid_values, }, values: values, }, ).ok_or("could not parse".to_string()) } pub fn validate_problem(p: sudoku::Problem) -> Result<sudoku::Problem, String> { //need to ensure that the given values is complete let size = p.grid.width * p.grid.height; if p.values.len() == size { Ok(p) } else { Err(format!("Given grid information spesifies a grid of {} by {} requiring {} values, number of values given is {}.",p.grid.width,p.grid.height,size,p.values.len())) } } } fn parse_form(form_chunk: Chunk) -> FutureResult<String, hyper::Error> { use serde_json::Value; match serde_json::from_slice::<Value>(&form_chunk) .map_err(|x| format!("{}", x)) .and_then(json_to_sudoku::validate_json) .and_then(json_to_sudoku::parse) .and_then(json_to_sudoku::validate_problem) .map(sudoku::solve) .and_then(move |solutions| match serde_json::to_string(&solutions) { Ok(v)=>Ok(v), Err(e) => Err(format!("{}",e)), }) { Ok(result) => futures::future::ok(result), Err(e) => futures::future::ok(e), } } fn make_error_response(error_message: &str) -> FutureResult<hyper::Response, hyper::Error> { use hyper::header::ContentLength; use hyper::header::ContentType; let payload = json!({ "error": error_message }).to_string(); let response = Response::new() .with_status(StatusCode::InternalServerError) .with_header(ContentLength(payload.len() as u64)) .with_header(ContentType::json()) .with_body(payload); futures::future::ok(response) } fn make_post_response( result: Result<String, hyper::Error>, ) -> FutureResult<hyper::Response, hyper::Error> { use hyper::header::ContentLength; use hyper::header::ContentType; use std::error::Error; match result { Ok(payload) => { let response = Response::new() .with_header(ContentLength(payload.len() as u64)) .with_header(ContentType::json()) .with_body(payload); futures::future::ok(response) } Err(error) => make_error_response(error.description()), } } struct Microservice; impl Service for Microservice { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; fn call(&self, request: Request) -> Self::Future { match (request.method(), request.path()) { (&Get, "/") => { let future = request .body() .concat2() .and_then(parse_form) .then(make_post_response); Box::new(future) } _ => Box::new(futures::future::ok( Response::new().with_status(StatusCode::NotFound), )), } } } fn main() { let _s = "127.0.0.1:8080".parse().map(|address| { hyper::server::Http::new() .bind(&address, || Ok(Microservice {})) .map(|server| { println!("Running microservice at {}", address); server.run().unwrap(); }) }); }
true
e1dbc320ab9fd8db01c9eda5ac617795766f8aef
Rust
yaocanwei/n-sql
/src/lexer/char_locations.rs
UTF-8
1,515
2.53125
3
[ "Apache-2.0", "MIT" ]
permissive
// Copyright 2019 The n-sql Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use super::location::{Column, Line, Location}; use super::parser_source::ParserSource; use std::str::Chars; pub struct CharLocations<'input> { pub location: Location, pub chars: Chars<'input>, } impl<'input> CharLocations<'input> { pub fn new<S>(input: &'input S) -> CharLocations<'input> where S: ?Sized + ParserSource, { CharLocations { location: Location { line: Line(0), column: Column(1), absolute: input.start_index(), }, chars: input.src().chars(), } } } impl<'input> Iterator for CharLocations<'input> { type Item = (Location, char); fn next(&mut self) -> Option<(Location, char)> { self.chars.next().map(|ch| { let location = self.location; self.location = self.location.shift(ch); // HACK: The layout algorithm expects `1` indexing for columns - // this could be altered in the future though if self.location.column == Column(0) { self.location.column = Column(1); } (location, ch) }) } }
true
dfc232faffa81fb1c46dc4b2aa66d9b5215ddf84
Rust
AdelaideAuto-IDLab/bTracked
/base_station/src/config/mod.rs
UTF-8
3,089
3.046875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
mod serial_config; use std::path::PathBuf; use serialport; fn default_true() -> bool { true } fn default_1() -> u64 { 1 } fn default_100() -> u64 { 1 } fn default_some_30() -> Option<u64> { Some(30) } fn default_log() -> String { "warn".into() } #[derive(Serialize, Deserialize)] #[serde(rename_all = "lowercase", tag = "type")] pub enum MeasurementSource { Serial { path: Option<PathBuf>, version: usize, #[serde(flatten)] options: serial_config::SerialOptions, }, WebSocket { url: String }, File { path: PathBuf, #[serde(default = "default_true")] repeat: bool, }, } #[derive(Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub struct HttpConfig { pub endpoint: String, pub http_proxy: Option<String>, pub https_proxy: Option<String>, pub identity_cert: Option<PathBuf>, pub identity_cert_pass: Option<String>, #[serde(default)] pub root_certs: Vec<PathBuf>, #[serde(default = "default_some_30")] pub timeout_ms: Option<u64>, } #[derive(Serialize, Deserialize)] #[serde(rename_all = "lowercase", tag = "type")] pub enum MeasurementDestination { /// Measurements will be serialized as a json array and sent as HTTP POST messages to `endpoint` Http { #[serde(flatten)] config: HttpConfig, /// The number of times to retry sending each request (default = 1) #[serde(default = "default_1")] retry_attempts: u64, /// The rate at which http requests are sent at (default = 100ms) #[serde(default = "default_100")] queue_rate_ms: u64, }, /// Measurements will be serialized as json and sent as websocket text messages to `endpoint` WebSocket { endpoint: String }, /// Measurements will be serialized as json and saved to a file separated by `\n` characters File { path: PathBuf, #[serde(default)] append: bool, }, /// Measurements are written to stdout in json format Stdout, } #[derive(Serialize, Deserialize)] pub struct AppConfig { /// Specifies the logging configuration using the `env_logger` syntax (default = 'warn') /// Example: `log = 'warn,basestation::init=debug'` #[serde(default = "default_log")] pub log: String, /// Specifies where measurements are obtained from pub source: MeasurementSource, /// Specifies where measurements are sent to pub destination: Vec<MeasurementDestination>, } pub fn default_config() -> AppConfig { AppConfig { log: "warn".into(), source: MeasurementSource::Serial { path: Some("COM1".into()), version: 1, options: serial_config::SerialOptions { baud_rate: 921600, data_bits: serialport::DataBits::Eight, stop_bits: serialport::StopBits::One, parity: serialport::Parity::None, flow_control: serialport::FlowControl::None, } }, destination: vec![MeasurementDestination::Stdout], } }
true
dc6b173660a36d41dd02d9d637cb10820ec9f947
Rust
tillrohrmann/rust-challenges
/aoc_2019_13/src/lib.rs
UTF-8
8,796
3.015625
3
[ "Apache-2.0" ]
permissive
use aoc_2019_2::IntComputer; use std::cell::RefCell; use std::fmt::Formatter; use std::io::{BufRead, BufReader, Error, ErrorKind, Stdout}; use std::rc::Rc; use std::str::FromStr; pub struct Pinball { game_memory: Vec<i64>, } impl Pinball { pub fn new(path: &str) -> Pinball { let mut game_memory = aoc_2019_2::read_memory_from_file(path); game_memory[0] = 2; Pinball { game_memory } } pub fn start(&self) { let mut game = Rc::new(RefCell::new(PinballGame::new())); let game_output_reader = PinballGameOutputReader::new(Rc::clone(&game)); let joystick_controller = JoystickController::new(Rc::clone(&game)); let mut output_reader = IntComputerOutputReader::new(Box::new(game_output_reader)); let input = std::io::BufReader::new(std::io::stdin()); let mut computer = IntComputer::new( self.game_memory.clone(), BufReader::new(joystick_controller), &mut output_reader, ); computer.compute(); game.borrow_mut().finalize_input_sequence(); } } #[derive(Debug, Copy, Clone, PartialEq)] enum Tile { EMPTY, WALL, BLOCK, PADDLE, BALL, } impl core::fmt::Display for Tile { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { let output = match self { Tile::EMPTY => " ", Tile::WALL => "#", Tile::BLOCK => "B", Tile::PADDLE => "_", Tile::BALL => "*", }; write!(f, "{}", output) } } impl From<isize> for Tile { fn from(value: isize) -> Self { match value { 0 => Tile::EMPTY, 1 => Tile::WALL, 2 => Tile::BLOCK, 3 => Tile::PADDLE, 4 => Tile::BALL, _ => std::panic!("Unknown tile type {}", value), } } } struct Display { display: Vec<Vec<Tile>>, score: isize, } impl Display { fn new(width: usize, height: usize) -> Display { Display { display: vec![vec![Tile::EMPTY; width]; height], score: 0, } } fn draw(&self) -> () { for line in &self.display { for tile in line { print!("{}", tile); } println!(); } println!("Score: {}", self.score); } fn update_tile(&mut self, point: aoc_common::math::Point, tile: Tile) -> () { let aoc_common::math::Point(x, y) = point; self.display[y as usize][x as usize] = tile; } fn update_score(&mut self, score_value: isize) -> () { self.score = score_value; } fn find_first(&self, tile_to_find: Tile) -> Option<aoc_common::math::Point> { for (y, line) in self.display.iter().enumerate() { for (x, tile) in line.iter().enumerate() { if *tile == tile_to_find { return Some(aoc_common::math::Point(x as isize, y as isize)); } } } None } } #[derive(Debug)] enum GameElement { SCORE(isize), TILE(aoc_common::math::Point, Tile), } struct PinballGame { display: Display, next_joystick_move: Option<Joystick>, } impl PinballGame { fn new() -> PinballGame { PinballGame { display: Display::new(44, 23), next_joystick_move: None, } } fn notify_display(&mut self, game_element: GameElement) { match game_element { GameElement::SCORE(score_value) => self.display.update_score(score_value), GameElement::TILE(point, tile) => self.display.update_tile(point, tile), } } fn finalize_input_sequence(&mut self) { self.display.draw(); self.calculate_next_joystick_move(); } fn calculate_next_joystick_move(&mut self) { let ball = self.display.find_first(Tile::BALL); let paddle = self.display.find_first(Tile::PADDLE); self.next_joystick_move = Some(match (ball, paddle) { ( Some(aoc_common::math::Point(x_ball, _)), Some(aoc_common::math::Point(x_paddle, _)), ) => match x_ball.cmp(&x_paddle) { std::cmp::Ordering::Equal => Joystick::NEUTRAL, std::cmp::Ordering::Less => Joystick::LEFT, std::cmp::Ordering::Greater => Joystick::RIGHT, }, _ => Joystick::NEUTRAL, }) } } struct PinballGameOutputReader { buffer: Vec<isize>, game: Rc<RefCell<PinballGame>>, } impl PinballGameOutputReader { fn new(game: Rc<RefCell<PinballGame>>) -> PinballGameOutputReader { PinballGameOutputReader { buffer: Vec::with_capacity(16), game, } } } impl OutputReader for PinballGameOutputReader { fn read(&mut self, output_value: &str) -> Result<(), Error> { let value = isize::from_str(output_value).map_err(|err| Error::new(ErrorKind::InvalidData, err))?; self.buffer.push(value); while self.buffer.len() >= 3 { let x = self.buffer[0]; let y = self.buffer[1]; let score_value = (-1, 0); let game_element = if (x, y) == score_value { GameElement::SCORE(self.buffer[2]) } else { GameElement::TILE(aoc_common::math::Point(x, y), Tile::from(self.buffer[2])) }; self.game.borrow_mut().notify_display(game_element); self.buffer.drain(0..3); } Ok(()) } fn finalize_input_sequence(&mut self) { self.game.borrow_mut().finalize_input_sequence(); } } enum Joystick { LEFT, RIGHT, NEUTRAL, } pub struct StdoutOutputReader {} impl StdoutOutputReader { pub fn new() -> StdoutOutputReader { StdoutOutputReader {} } } impl OutputReader for StdoutOutputReader { fn read(&mut self, output_value: &str) -> Result<(), Error> { println!("{}", output_value); Ok(()) } fn finalize_input_sequence(&mut self) {} } impl InputWriter for StdoutOutputReader { fn request_input(&self) -> Result<(), Error> { println!("Request input"); Ok(()) } } pub trait OutputReader { fn read(&mut self, output_value: &str) -> Result<(), Error>; fn finalize_input_sequence(&mut self); } trait InputWriter { fn request_input(&self) -> Result<(), Error>; } pub struct IntComputerOutputReader { buffer: Vec<u8>, output_reader: Box<dyn OutputReader>, } impl IntComputerOutputReader { pub fn new(output_reader: Box<dyn OutputReader>) -> IntComputerOutputReader { IntComputerOutputReader { buffer: Vec::with_capacity(1024), output_reader, } } } impl std::io::Write for IntComputerOutputReader { fn write(&mut self, buf: &[u8]) -> Result<usize, Error> { let terminates_input = buf.contains(&b'\n'); self.buffer.extend_from_slice(buf); if terminates_input { let mut reader = BufReader::new(&self.buffer[..]); let mut line = String::new(); let mut total_bytes_read = 0; loop { let bytes_read = reader.read_line(&mut line)?; total_bytes_read += bytes_read; if bytes_read > 0 { if line.starts_with(aoc_2019_2::OUTPUT_PREFIX) { let output_value = line.trim_start_matches(aoc_2019_2::OUTPUT_PREFIX).trim(); self.output_reader.read(output_value)? } else { self.output_reader.finalize_input_sequence() } } else { break; } } self.buffer.drain(0..total_bytes_read); } Ok(buf.len()) } fn flush(&mut self) -> Result<(), Error> { unimplemented!() } } struct JoystickController { game: Rc<RefCell<PinballGame>>, } impl JoystickController { fn new(game: Rc<RefCell<PinballGame>>) -> JoystickController { JoystickController { game } } fn create_command(joystick_move: Joystick) -> String { match joystick_move { Joystick::NEUTRAL => "0\n", Joystick::LEFT => "-1\n", Joystick::RIGHT => "1\n", } .into() } } impl std::io::Read for JoystickController { fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> { let joystick_move = self.game.borrow_mut().next_joystick_move.take(); let joystick_move = joystick_move.unwrap(); let command = JoystickController::create_command(joystick_move); command.as_bytes().read(buf) } }
true
3a49b7aa5f68e8c6a62a63386546a69329e7cafe
Rust
eeverett6/route-rs
/src/utils/test/packet_generators.rs
UTF-8
2,790
3.09375
3
[ "MIT" ]
permissive
use crate::api::ElementStream; use futures::{stream, Async, Poll, Stream}; use std::time::Duration; use tokio::timer::Interval; // Immediately yields a collection of packets to be poll'd. // Thin wrapper around iter_ok. pub fn immediate_stream<I>(collection: I) -> ElementStream<I::Item> where I: IntoIterator, I::IntoIter: Send + 'static, { Box::new(stream::iter_ok::<_, ()>(collection)) } /* LinearIntervalGenerator Generates a series of monotonically increasing integers, starting at 0. `iterations` "packets" are generated in the stream. One is yielded every `duration`. */ pub struct LinearIntervalGenerator { interval: Interval, iterations: usize, seq_num: i32, } impl LinearIntervalGenerator { pub fn new(duration: Duration, iterations: usize) -> Self { LinearIntervalGenerator { interval: Interval::new_interval(duration), iterations, seq_num: 0, } } } impl Stream for LinearIntervalGenerator { type Item = i32; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, ()> { try_ready!(self.interval.poll().map_err(|_| ())); if self.seq_num as usize > self.iterations { Ok(Async::Ready(None)) } else { let next_packet = Ok(Async::Ready(Some(self.seq_num))); self.seq_num += 1; next_packet } } } /// Packet Interval Generator procduces a Stream of packets on a defined interval.AsMut /// /// Which packet is next sent is determined by the Iterator, provided during creation. This /// is intended to be a full fledged packet eventually, but the trait bound is only set to /// something that is Sized. The Iterator is polled until it runs out of values, at which /// point we close the Stream by sending a Ready(None). pub struct PacketIntervalGenerator<Iterable, Packet> where Iterable: Iterator<Item = Packet>, Packet: Sized, { interval: Interval, packets: Iterable, } impl<Iterable, Packet> PacketIntervalGenerator<Iterable, Packet> where Iterable: Iterator<Item = Packet>, Packet: Sized, { pub fn new(duration: Duration, packets: Iterable) -> Self { PacketIntervalGenerator { interval: Interval::new_interval(duration), packets, } } } impl<Iterable, Packet> Stream for PacketIntervalGenerator<Iterable, Packet> where Iterable: Iterator<Item = Packet>, Packet: Sized, { type Item = Packet; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, ()> { try_ready!(self.interval.poll().map_err(|_| ())); match self.packets.next() { Some(packet) => Ok(Async::Ready(Some(packet))), None => Ok(Async::Ready(None)), } } }
true
84cfe4efd33a61bcfce5cbc31aedce6b187fcd37
Rust
liyuntao/adventofcode2018
/examples/day20.rs
UTF-8
2,466
3.09375
3
[]
no_license
use std::collections::HashMap; use std::collections::VecDeque; use std::fs::File; use std::io::Read; fn solution(input: String) { let mut grid: HashMap<(i32, i32), usize> = HashMap::new(); let mut cur_pos: (i32, i32) = (0, 0); grid.insert(cur_pos, 0); let mut stack = VecDeque::new(); for c in input.chars() { match c { 'N' => { grid.insert((cur_pos.0, cur_pos.1 - 1), 0); cur_pos.1 -= 2; grid.insert(cur_pos, usize::max_value()); } 'S' => { grid.insert((cur_pos.0, cur_pos.1 + 1), 0); cur_pos.1 += 2; grid.insert(cur_pos, usize::max_value()); } 'W' => { grid.insert((cur_pos.0 - 1, cur_pos.1), 0); cur_pos.0 -= 2; grid.insert(cur_pos, usize::max_value()); } 'E' => { grid.insert((cur_pos.0 + 1, cur_pos.1), 0); cur_pos.0 += 2; grid.insert(cur_pos, usize::max_value()); } '(' => stack.push_back(cur_pos), ')' => cur_pos = stack.pop_back().unwrap(), '|' => cur_pos = *stack.back().unwrap(), _ => {} } } let mut queue = VecDeque::new(); queue.push_back((0, 0)); while !queue.is_empty() { let cur = queue.pop_front().unwrap(); let cur_fewest = *grid.get(&cur).unwrap(); for t in &[(0, -1), (0, 1), (-1, 0), (1, 0)] { let next_x = cur.0 + t.0 * 2; let next_y = cur.1 + t.1 * 2; if grid.contains_key(&(cur.0 + t.0, cur.1 + t.1)) { let last_fewest = *grid.get(&(next_x, next_y)).unwrap(); if cur_fewest + 1 < last_fewest { grid.insert((next_x, next_y), cur_fewest + 1); queue.push_back((next_x, next_y)); } } } } let q1 = grid.iter().max_by(|&e1, &e2| e1.1.cmp(e2.1)).unwrap(); println!("result of q01 is {}", q1.1); let q2 = grid.iter().filter(|&entry| *entry.1 >= 1000).count(); println!("result of q02 is {}", q2); } fn main() { let input = { let mut input = String::new(); let path = format!("./input/{}", "day20.txt"); let mut file = File::open(path).unwrap(); file.read_to_string(&mut input).unwrap(); input }; solution(input); }
true
173495243dcea23ead663ef8f1f622c7dc4a5555
Rust
NickSchmitt/Exercism
/rust/nth-prime/src/lib.rs
UTF-8
919
3.5625
4
[]
no_license
pub fn nth(n: usize) -> usize { prime_sieve(n+1, n+2) } pub fn prime_sieve(target_prime: usize, max_number_to_check: usize) -> usize { let mut prime_mask = vec![true; max_number_to_check]; prime_mask[0] = false; prime_mask[1] = false; let mut total_primes_found = 0; for current_num in 2..max_number_to_check { if prime_mask[current_num] { total_primes_found += 1; if total_primes_found == target_prime { return current_num } let mut multiple = 2 * current_num; while multiple < max_number_to_check { prime_mask[multiple] = false; multiple += current_num; } } } println!("{}th prime not found in {}", target_prime, max_number_to_check); println!("running larger prime sieve"); prime_sieve(target_prime, max_number_to_check * 2) }
true
3cc047597402441074de4c51f7c814e5a97d59ce
Rust
rust3dr3d/rest_api_quickstart
/src/data.rs
UTF-8
1,952
3.0625
3
[]
no_license
use serde::{Serialize, Deserialize}; use std::fs::{File, OpenOptions}; use rocket::response::NamedFile; use std::io::prelude::*; use std::str; pub const _DB_PATH:&'static str = "messages_db.txt"; #[derive(Serialize, Deserialize, Debug)] pub struct Message{ pub id: u8, pub message:String, pub from:String } // Return all messages as Result<String> pub fn read_all_messages() -> std::io::Result<String>{ let messages_db = NamedFile::open(_DB_PATH); let mut buffer:String = String::new(); match messages_db{ Ok(_) => { buffer = parse_all_messages_str()?; }, Err(_) => { let _f = File::create(_DB_PATH)?; } }; Ok(buffer) } // Parse and return as Messages pub fn parse_all_messages() ->std::io::Result<Vec<Message>>{ let mut contents_u8:Vec<u8> = Vec::new(); let mut messages_db = match File::open(_DB_PATH){ Ok(db) => db, Err(_) => File::create(_DB_PATH)? }; messages_db.read_to_end(&mut contents_u8)?; let msgs_str = str::from_utf8(&contents_u8[..]).unwrap(); let msgs:Vec<Message> = serde_json::from_str(msgs_str)?; Ok(msgs) } // Parse and return as String pub fn parse_all_messages_str() ->std::io::Result<String>{ let mut contents_u8:Vec<u8> = Vec::new(); let mut messages_db = NamedFile::open(_DB_PATH)?; messages_db.read_to_end(&mut contents_u8)?; let msgs_str = str::from_utf8(&contents_u8[..]).unwrap(); let _msgs:Vec<Message> = serde_json::from_str(msgs_str)?; Ok(String::from(msgs_str)) } // Truncate existing contents and writes all the messages to the db pub fn save_all_to_db(messages: String) -> std::io::Result<()>{ let mut messages_db = OpenOptions::new() .write(true) .truncate(true) .open(_DB_PATH)?; messages_db.write_all(&messages.as_bytes())?; Ok(()) }
true
915d1fb8adc466ac18d9e1e9c910f3794d73dac1
Rust
tjnt/atcoder-rust
/src/accept/past201912_h.rs
UTF-8
2,381
2.828125
3
[]
no_license
/* {{{ */ use std::io::*; use std::str::FromStr; struct Scanner<R: Read> { reader: R, } impl<R: Read> Scanner<R> { fn new(r: R) -> Scanner<R> { Scanner { reader: r } } fn read<T: FromStr>(&mut self) -> T { let token = self .reader .by_ref() .bytes() .map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::<String>(); token.parse::<T>().ok().unwrap() } } /* }}} */ fn main() { let cin = stdin(); let cin = cin.lock(); let mut sc = Scanner::new(cin); let n: usize = sc.read(); let mut c = Vec::new(); for _ in 0..n { c.push(sc.read::<u64>()); } let q: usize = sc.read(); let mut v1 = vec![0u64;n]; let mut v2 = 0u64; let mut v3 = 0u64; let mut min_all: u64 = *c.iter().min().unwrap(); let mut min_even: u64 = *c.iter().enumerate().filter(|&t| t.0 % 2 == 0) .map(|t| t.1).min().unwrap(); for _ in 0..q { match sc.read::<usize>() { 1 => { let x = sc.read::<usize>() - 1; let a = sc.read::<u64>(); let b = if x % 2 == 0 { v1[x] + v2 + v3 } else { v1[x] + v3 } + a; if b <= c[x] { v1[x] += a; min_all = std::cmp::min(c[x]-b, min_all); if x % 2 == 0 { min_even = std::cmp::min(c[x]-b, min_even); } } }, 2 => { let a = sc.read::<u64>(); if a <= min_even { v2 += a; min_even -= a; min_all = std::cmp::min(min_all, min_even); } }, 3 => { let a = sc.read::<u64>(); if a <= min_all { v3 += a; min_all -= a; min_even -= a; } }, _ => panic!() } } let res = v1.iter().sum::<u64>() + v2 * (((n as u64) + 1) / 2) + v3 * (n as u64); println!("{}", res); } /* vim:set foldmethod=marker: */
true
a3ae2926394e3ea8780ae03bbcf7e436dec92489
Rust
prescod/advent-of-code-2019
/day04/day4b.rs
UTF-8
912
3.109375
3
[]
no_license
use std::io; extern crate regex; use regex::Regex as Regex; fn check(i: u32, re1: &Regex, re2: &Regex) -> bool{ let as_string = i.to_string(); let matched : bool = false; for cap in re1.captures_iter(&as_string) { for i in 1..10{ if let Some(val) = cap.get(i){ if val.as_str().len() == 2 { return true; } } } } return false; } fn main() -> io::Result<()> { let min = 264793; let max = 803935; let mut count = 0; let re1 : Regex = Regex::new(r"^(1+)?(2+)?(3+)?(4+)?(5+)?(6+)?(7+)?(8+)?(9+)?$").unwrap(); re1.find(&"abcd".to_string()); let re2 : Regex = Regex::new(r".*").unwrap(); for i in min..max{ if check(i, &re1, &re2){ println!("Matched: {}",i); count += 1; } } println!("Matches: {}", count); Ok(()) }
true
3679f4ff3dae96a16cca54fb79fc338666c6f819
Rust
cohyou/epiqs
/src/parser/mod.rs
UTF-8
11,971
2.96875
3
[ "MIT" ]
permissive
macro_rules! push { ($s:ident, $t:expr) => {{ // println!("parser push: {:?}", $t); Ok($s.vm.borrow_mut().alloc($t)) }} } mod error; use std::rc::Rc; use std::cell::RefCell; use core::*; use lexer::*; use self::error::Error; use self::TokenState::*; const UNIT_INDX: usize = 0; const K: usize = 3; #[derive(Eq, PartialEq, Clone, Debug)] pub enum TokenState { SOT, // Start Of Tokens Has(Tokn), EOT, // End Of Tokens } impl Default for TokenState { fn default() -> Self { SOT } } pub struct Parser<'a> { lexer: Lexer<'a, 'a>, vm: Rc<RefCell<Heliqs>>, // state: State, // current_token: RefCell<TokenState>, // aexp_tokens: Vec<Vec<Tokn>>, lookahead: [TokenState; K], p: usize, } impl<'a> Parser<'a> { pub fn new(lexer: Lexer<'a, 'a>, vm: Rc<RefCell<Heliqs>>) -> Self { let mut parser = Parser { lexer: lexer, vm: vm, // state: State::Aexp, // current_token: RefCell::new(SOT), // aexp_tokens: vec![vec![]], lookahead: Default::default(), p: 0, }; for _ in 0..K { parser.consume_token(); } parser } pub fn parse(&mut self) { self.add_unit(); self.add_prim("decr"); self.add_prim("ltoreq"); self.add_prim("eq"); self.add_prim("plus"); self.add_prim("minus"); self.add_prim("print"); self.add_prim("concat"); self.add_prim("dbqt"); match self.parse_aexp() { Ok(_) => {}, Err(e) => { println!("parse error: {:?}", e); }, } } fn parse_aexp(&mut self) -> Result<usize, Error> { self.log("parse_aexp"); match self.current_token() { Has(Tokn::Sgqt) => self.parse_tpiq_single(), Has(Tokn::Pipe) => self.parse_tpiq(), Has(Tokn::Crrt) => self.parse_mpiq(), _ => { let l = (self.parse_expression())?; match self.current_token() { Has(Tokn::Coln) => self.parse_cons(l), _ => Ok(l), } }, } } fn parse_tpiq_single(&mut self) -> Result<usize, Error> { self.log("parse_tpiq_single"); self.consume_token(); // dispatcher Sgqtのはず match self.current_token() { Has(Tokn::Otag(ref otag)) => { self.consume_token(); // 引数は一つ、それをqとみなす let qidx = (self.parse_aexp())?; self.match_otag(UNIT_INDX, qidx, otag) }, t @ _ => Err(Error::TpiqSingle(t)), } } fn parse_tpiq(&mut self) -> Result<usize, Error> { self.log("parse_tpiq"); self.consume_token(); // dispatcher Pipeのはず match self.current_token() { Has(Tokn::Otag(ref otag)) => { self.consume_token(); let pidx = (self.parse_aexp())?; let qidx = (self.parse_aexp())?; self.match_otag(pidx, qidx, otag) }, Has(Tokn::Pipe) => { // Pipeなのに引数は一つだけという、特殊なパターンになるが一度試す self.consume_token(); let qidx = (self.parse_aexp())?; push!(self, Epiq::Quot(UNIT_INDX, qidx)) }, _ => panic!("parse_tpiq {:?}はOtag/Pipeではありません", self.current_token()), } } fn parse_mpiq(&mut self) -> Result<usize, Error> { self.consume_token(); // dispatcher Crrtのはず match self.current_token() { Has(Tokn::Otag(ref otag)) => { self.consume_token(); match otag.as_ref() { // ^Tと^Fは特別扱い "T" => push!(self, Epiq::Tval), "F" => push!(self, Epiq::Fval), _ => { let pidx = (self.parse_aexp())?; let qidx = (self.parse_aexp())?; push!(self, Epiq::Mpiq{o: otag.clone(), p: pidx, q: qidx}) }, } }, Has(Tokn::Lbkt) => { let pidx = UNIT_INDX; //self.vm.borrow_mut().alloc(Epiq::Uit8(-1)); let qidx = (self.parse_list())?; push!(self, Epiq::Mpiq{o:">".to_string(), p: pidx, q: qidx }) }, _ => panic!("parse_mpiq {:?}がOtag/Lbktではありません", self.current_token()) /*Err(Error::Unimplemented)*/, } } fn match_otag(&mut self, pidx: NodeId, qidx: NodeId, otag: &str) -> Result<usize, Error> { match otag { ">" => push!(self, Epiq::Eval(pidx, qidx)), ":" => push!(self, Epiq::Lpiq(pidx, qidx)), "!" => push!(self, Epiq::Appl(pidx, qidx)), "@" => push!(self, Epiq::Rslv(pidx, qidx)), "?" => push!(self, Epiq::Cond(pidx, qidx)), "%" => push!(self, Epiq::Envn(pidx, qidx)), "#" => push!(self, Epiq::Bind(pidx, qidx)), "." => push!(self, Epiq::Accs(pidx, qidx)), r"\" => push!(self, Epiq::Lmbd(pidx, qidx)), _ => push!(self, Epiq::Tpiq{o: otag.to_string(), p: pidx, q: qidx}), } } fn parse_cons(&mut self, pidx: usize) -> Result<usize, Error> { self.log("parse_cons"); self.consume_token(); // Coln // aexpではない、あえてexpressionしか入れられないように // 中置記法の使い方を限定する let qidx = (self.parse_expression())?; match self.current_token() { Has(Tokn::Coln) => { let new_cons = (self.parse_cons(qidx))?; push!(self, Epiq::Lpiq(pidx, new_cons)) }, _ => push!(self, Epiq::Lpiq(pidx, qidx)), } } // expressionとは、ここでは中置記法の中の値になれるものを指している fn parse_expression(&mut self) -> Result<usize, Error> { self.log("parse_expression"); // ここはcomsume_tokenしない match self.current_token() { Has(Tokn::Lbkt) => self.parse_list(), Has(Tokn::Crrt) => self.parse_mpiq(), _ => { let l = (self.parse_accessing_term())?; match self.current_token() { Has(Tokn::Bang) => self.parse_apply(l), _ => Ok(l), } } } } fn parse_list(&mut self) -> Result<usize, Error> { self.log("parse_list"); self.consume_token(); self.parse_list_internal() } fn parse_list_internal(&mut self) -> Result<usize, Error> { self.log("parse_list_internal"); // 閉じbracketが出るまで再帰呼出 match self.current_token() { Has(Tokn::Rbkt) => { self.consume_token(); push!(self, Epiq::Unit) }, _ => { let pidx = (self.parse_aexp())?; let qidx = (self.parse_list_internal())?; push!(self, Epiq::Lpiq(pidx, qidx)) } } } fn parse_accessing_term(&mut self) -> Result<usize, Error> { self.log("parse_accessing_term"); let l = (self.parse_term())?; match self.current_token() { Has(Tokn::Stop) => self.parse_accessor(l), _ => Ok(l), } } fn parse_accessor(&mut self, left: usize) -> Result<usize, Error> { self.log("parse_accessor"); self.consume_token(); let qidx = (self.parse_term())?; // TODO: 左側はexpressionにしたいが一旦保留 match self.current_token() { Has(Tokn::Stop) => { let id = self.vm.borrow_mut().alloc(Epiq::Accs(left, qidx)); let new_left = self.vm.borrow_mut().alloc(Epiq::Eval(UNIT_INDX, id)); let new_cons = (self.parse_accessor(new_left))?; push!(self, Epiq::Eval(UNIT_INDX, new_cons)) }, _ => { let id = self.vm.borrow_mut().alloc(Epiq::Accs(left, qidx)); push!(self, Epiq::Eval(UNIT_INDX, id)) }, } } /// "term" means resolve or literal in this context fn parse_term(&mut self) -> Result<usize, Error> { self.log("parse_term"); match self.current_token() { Has(Tokn::Atsm) => self.parse_resolve(), _ => self.parse_literal(), } } fn parse_apply(&mut self, left: usize) -> Result<usize, Error> { self.consume_token(); let qidx = (self.parse_expression())?; let id = self.vm.borrow_mut().alloc(Epiq::Appl(left, qidx)); push!(self, Epiq::Eval(UNIT_INDX, id)) } fn parse_resolve(&mut self) -> Result<usize, Error> { self.consume_token(); // Atsm let qidx = (self.parse_literal())?; let id = self.vm.borrow_mut().alloc(Epiq::Rslv(UNIT_INDX, qidx)); push!(self, Epiq::Eval(UNIT_INDX, id)) } fn parse_literal(&mut self) -> Result<usize, Error> { self.log("parse_literal"); match self.current_token() { Has(Tokn::Smcl) => self.parse_unit(), Has(Tokn::Dbqt) => self.parse_text(), Has(Tokn::Chvc(ref s)) => self.parse_name(s), Has(Tokn::Nmbr(ref s)) => self.parse_number(s), _ => panic!("parse_literal {:?}がSmcl/Dbqt/Chvc/Nmbrではありません", self.current_token())/*Err(Error::Unimplemented)*/, } } fn parse_unit(&mut self) -> Result<usize, Error> { self.log("parse_unit"); self.consume_token(); // Smclのはず self.vm.borrow_mut().set_entry(UNIT_INDX); // これをしないと;だけの時にentrypointがダメになる Ok(UNIT_INDX) } fn parse_text(&mut self) -> Result<usize, Error> { self.consume_token(); // Dbqt if let Has(Tokn::Chvc(ref s)) = self.current_token() { self.consume_token(); if let Has(Tokn::Dbqt) = self.current_token() { self.consume_token(); push!(self, Epiq::Text(s.clone())) } else { Err(Error::Unimplemented) } } else { Err(Error::Unimplemented) } } fn parse_name(&mut self, s: &str) -> Result<usize, Error> { self.log("parse_name"); self.consume_token(); push!(self, Epiq::Name(s.to_string())) } fn parse_number(&mut self, s: &str) -> Result<usize, Error> { self.consume_token(); push!(self, Epiq::Uit8(s.parse::<i64>().unwrap())) } // Unitは常に1つにする(index固定) fn add_unit(&mut self) { let _unit = self.vm.borrow_mut().alloc(Epiq::Unit); } fn add_prim(&mut self, name: &str) { let prim = self.vm.borrow_mut().alloc(Epiq::Prim(name.to_string())); log(format!("add_prim: {:?} {:?}", name, prim)); self.vm.borrow_mut().define(name, prim); } fn consume_token(&mut self) { let res = self.lexer.tokenize(); match res { TokenizeResult::Ok(t) => self.set_current_token(Has(t)), TokenizeResult::Err(_e) => {}, TokenizeResult::EOF => self.set_current_token(EOT), } } fn set_current_token(&mut self, t: TokenState) { self.lookahead[self.p] = t; self.p = (self.p + 1) % K; } fn token(&self, i: usize) -> TokenState { self.lookahead[(self.p + i) % K].clone() } fn current_token(&self) -> TokenState { self.token(0) } fn log(&self, func_name: &str) { if false { println!("{}: {:?}", func_name, self.current_token()); } } }
true
42c2347d0d0e1bdb8d2a3e7850a2163658a7cf05
Rust
marti1125/rust-ejemplos
/funciones/src/main.rs
UTF-8
647
3.71875
4
[ "MIT" ]
permissive
fn main() { saludo("Mozilla".to_string()); println!("Suma: {:?}", sumar(100,898)); println!("Potencia: {:?}", potencia(5,5)); let total = sumar(100,898) + potencia(5,5); println!("Total: {:?}", total); } fn saludo(name :String) { println!("Hello, {:?}", name) } fn sumar(x :i32, y :i32) -> i32 { x + y } pub fn suma(a: i32, b: i32) -> i32 { a + b } fn resta(a: i32, b: i32) { let r: i32 = a - b; println!("Result {:?}", r); } fn potencia(x :i32, y :i32) -> i32 { let mut result = 1; for i in 1..y+1 { result = result * x; println!("Respuesta, {:?}", result); } result }
true
e7d25e4fb64843197b99cfeeb6f6bcdfa528b1a6
Rust
askoufis/advent-of-code-2020
/src/day12.rs
UTF-8
6,480
3.40625
3
[]
no_license
use std::num::ParseIntError; use std::str::FromStr; use crate::vec::Vec2; const RIGHT_ROTATION_ORDER: [Direction; 4] = [Direction::N, Direction::E, Direction::S, Direction::W]; const LEFT_ROTATION_ORDER: [Direction; 4] = [Direction::N, Direction::W, Direction::S, Direction::E]; #[derive(Clone, Copy, Debug)] enum Action { F { steps: usize }, N { steps: usize }, S { steps: usize }, E { steps: usize }, W { steps: usize }, L { degrees: usize }, R { degrees: usize }, } impl FromStr for Action { type Err = ParseIntError; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut iter = s.chars(); let c = iter.next().unwrap(); let num: usize = iter.collect::<String>().parse().unwrap(); match c { 'F' => Ok(Action::F { steps: num }), 'N' => Ok(Action::N { steps: num }), 'S' => Ok(Action::S { steps: num }), 'E' => Ok(Action::E { steps: num }), 'W' => Ok(Action::W { steps: num }), 'L' => Ok(Action::L { degrees: num }), 'R' => Ok(Action::R { degrees: num }), _ => panic!("Bad input"), } } } #[derive(Clone, Copy, PartialEq)] enum Direction { N, E, S, W, } struct Ship { position: Vec2, facing: Direction, waypoint: Vec2, } impl Ship { fn new() -> Self { Ship { position: Vec2 { x: 0, y: 0 }, facing: Direction::E, waypoint: Vec2 { x: 10, y: 1 }, } } fn execute_action(&mut self, action: Action) { match action { Action::N { steps } => self.move_n(steps), Action::S { steps } => self.move_s(steps), Action::E { steps } => self.move_e(steps), Action::W { steps } => self.move_w(steps), Action::F { steps } => self.move_f(steps), Action::L { degrees } => self.rotate_l(degrees), Action::R { degrees } => self.rotate_r(degrees), } } fn execute_waypoint_action(&mut self, action: Action) { match action { Action::N { steps } => self.move_waypoint_n(steps), Action::S { steps } => self.move_waypoint_s(steps), Action::E { steps } => self.move_waypoint_e(steps), Action::W { steps } => self.move_waypoint_w(steps), Action::F { steps } => self.move_f2(steps), Action::L { degrees } => self.rotate_waypoint_l(degrees), Action::R { degrees } => self.rotate_waypoint_r(degrees), } } fn move_f(&mut self, steps: usize) { match self.facing { Direction::N => self.move_n(steps), Direction::S => self.move_s(steps), Direction::E => self.move_e(steps), Direction::W => self.move_w(steps), } } fn move_f2(&mut self, steps: usize) { self.position.x += self.waypoint.x * steps as isize; self.position.y += self.waypoint.y * steps as isize; } fn move_n(&mut self, steps: usize) { self.position.y += steps as isize; } fn move_waypoint_n(&mut self, steps: usize) { self.waypoint.y += steps as isize; } fn move_s(&mut self, steps: usize) { self.position.y -= steps as isize; } fn move_waypoint_s(&mut self, steps: usize) { self.waypoint.y -= steps as isize; } fn move_e(&mut self, steps: usize) { self.position.x += steps as isize; } fn move_waypoint_e(&mut self, steps: usize) { self.waypoint.x += steps as isize; } fn move_w(&mut self, steps: usize) { self.position.x -= steps as isize; } fn move_waypoint_w(&mut self, steps: usize) { self.waypoint.x -= steps as isize; } fn rotate_l(&mut self, degrees: usize) { let turns = degrees / 90; let current_order_index = LEFT_ROTATION_ORDER .iter() .position(|f| self.facing == *f) .unwrap(); let new_index = (current_order_index + turns) % 4; self.facing = LEFT_ROTATION_ORDER[new_index]; } fn rotate_waypoint_l(&mut self, degrees: usize) { let turns = degrees / 90; let mut new_waypoint = self.waypoint.clone(); for _ in 0..turns { let new_x = -new_waypoint.y; let new_y = new_waypoint.x; new_waypoint = Vec2 { x: new_x, y: new_y }; } self.waypoint = new_waypoint; } fn rotate_r(&mut self, degrees: usize) { let turns = degrees / 90; let current_order_index = RIGHT_ROTATION_ORDER .iter() .position(|f| self.facing == *f) .unwrap(); let new_index = (current_order_index + turns) % 4; self.facing = RIGHT_ROTATION_ORDER[new_index]; } fn rotate_waypoint_r(&mut self, degrees: usize) { let turns = degrees / 90; let mut new_waypoint = self.waypoint.clone(); for _ in 0..turns { let new_x = new_waypoint.y; let new_y = -new_waypoint.x; new_waypoint = Vec2 { x: new_x, y: new_y }; } self.waypoint = new_waypoint; } fn get_manhattan_distance(&self) -> usize { (self.position.x.abs() + self.position.y.abs()) as usize } } #[aoc_generator(day12)] fn input_generator(input: &str) -> Vec<Action> { input .lines() .map(|line| Action::from_str(line).unwrap()) .collect() } #[aoc(day12, part1)] fn part1(actions: &[Action]) -> usize { let mut ship = Ship::new(); actions .iter() .for_each(|action| ship.execute_action(*action)); ship.get_manhattan_distance() } #[aoc(day12, part2)] fn part2(actions: &[Action]) -> usize { let mut ship = Ship::new(); actions.iter().for_each(|action| { ship.execute_waypoint_action(*action); }); ship.get_manhattan_distance() } #[cfg(test)] mod tests { use super::*; #[test] fn part1_test() { let input = r"F10 N3 F7 R90 F11"; let generated_input = input_generator(&input); let result = part1(&generated_input); let expected = 25; assert_eq!(result, expected); } #[test] fn part2_test() { let input = r"F10 N3 F7 R90 F11"; let generated_input = input_generator(&input); let result = part2(&generated_input); let expected = 286; assert_eq!(result, expected); } }
true
1362962dc35180887133c21f4cf4e7ba0755e6f5
Rust
sagan-software/oak
/crates/oak/src/render.rs
UTF-8
10,338
2.734375
3
[]
no_license
use crate::{ html::{Attribute, Children, Element, EventListener, EventToMessage, Html}, program::Program, }; use itertools::{EitherOrBoth, Itertools}; use std::fmt::Debug; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub struct Renderer<Model, Msg> { program: Rc<Program<Model, Msg>>, to_remove: Vec<(web_sys::Node, web_sys::Node)>, } fn eiter_or_both_to_option_tuple<T>(pair: EitherOrBoth<T, T>) -> (Option<T>, Option<T>) { use itertools::EitherOrBoth::{Both, Left, Right}; match pair { Both(a, b) => (Some(a), Some(b)), Left(a) => (Some(a), None), Right(b) => (None, Some(b)), } } impl<Model, Msg> Renderer<Model, Msg> where Msg: PartialEq + Debug + Clone + 'static, Model: Debug + Clone + 'static, { pub fn render( root: &web_sys::Node, program: &Rc<Program<Model, Msg>>, new_tree: &Html<Msg>, old_tree: &Option<Html<Msg>>, ) -> Result<(), JsValue> { let mut renderer = Renderer { program: program.clone(), to_remove: vec![], }; // TODO: We should probably not assume that the number here is 0 renderer.update_element(root, Some(new_tree), old_tree.as_ref(), 0)?; for (parent, child) in &renderer.to_remove { parent.remove_child(&child)?; } Ok(()) } fn update_element( &mut self, parent: &web_sys::Node, new: Option<&Html<Msg>>, old: Option<&Html<Msg>>, index: u32, ) -> Result<(), JsValue> { match (old, new) { (None, Some(new_html)) => { // Node is added parent.append_child(&self.create_node(new_html)?)?; } (Some(_removed), None) => { // Node is removed if let Some(child) = parent.child_nodes().item(index) { // Don't remove childs until after every iteration is finished. If not, the // indexes will not point to the correct nodes anymore self.to_remove.push((parent.clone(), child)); } else { // console_log!( // "Could not find node with index {} when removing {}", // index, // removed.to_html_text(0) // ); } } (Some(old), Some(new)) => match (old, new) { (Html::Element(old_tag), Html::Element(new_tag)) if old_tag.name == new_tag.name && old_tag.key() == new_tag.key() => { let current_node: web_sys::Element = match parent.child_nodes().item(index) { Some(n) => n.dyn_into()?, None => { return Err(JsValue::from_str(&format!( "ERROR: Could not find node at index {}", index ))); } }; // We have a node (current_node) that has changed from old_tag to new_tag, though // the tag is still the same. This means we need to diff children and attributes // First we diff attributes // We start by removing the ones that are no longer active for old_attr in &old_tag.attrs { let new_attr = new_tag.attrs.iter().find(|e| e == &old_attr); if new_attr.is_none() { remove_attribute(&current_node, old_attr)?; } else if let Attribute::Event(old_listener) = old_attr { if let Some(Attribute::Event(new_listener)) = new_attr { if let Some(js_closure) = old_listener.js_closure.0.borrow_mut().take() { new_listener.js_closure.0.replace(Some(js_closure)); } } } } // Then we add the ones that are added for attr in &new_tag.attrs { if !old_tag.attrs.contains(attr) { self.add_attribute(&current_node, attr)?; } } if let (Children::Nodes(old_children), Children::Nodes(new_children)) = (&old_tag.children, &new_tag.children) { for (child_index, pair) in old_children .iter() .zip_longest(new_children.iter()) .enumerate() { let (old_child, new_child) = eiter_or_both_to_option_tuple(pair); self.update_element( &current_node, new_child, old_child, child_index as u32, )?; } } } (Html::Text(s1), Html::Text(s2)) => { if s1 != s2 { if let Some(child) = parent.child_nodes().item(index) { child.set_text_content(Some(&s2)); } else { return Err(JsValue::from_str(&format!( "ERROR: Could not find node at index {}", index, ))); } } } _ => { if let Some(child) = parent.child_nodes().item(index) { parent.replace_child(&self.create_node(new)?, &child)?; } else { return Err(JsValue::from_str(&format!( "ERROR: Could not find node at index {}", index, ))); } } }, (None, None) => { // Should never happen, but if it happens we can just do nothing and it will be okay } } Ok(()) } fn create_node(&self, input: &Html<Msg>) -> Result<web_sys::Node, JsValue> { match input { Html::Element(Element { name, attrs, children, .. }) => { let el = self.program.browser.document.create_element(&name)?; for attr in attrs { self.add_attribute(&el, attr)?; } let node: web_sys::Node = el.into(); if let Children::Nodes(children) = children { for child in children { let child_node = self.create_node(&child)?; node.append_child(&child_node)?; } } Ok(node) } Html::Text(text) => { let node = self.program.browser.document.create_text_node(&text); Ok(node.into()) } } } fn add_attribute( &self, node: &web_sys::Element, attribute: &Attribute<Msg>, ) -> Result<(), JsValue> { match attribute { Attribute::Key(_) => Ok(()), Attribute::Text(key, value) => node.set_attribute(&key, &value), Attribute::Bool(key) => node.set_attribute(&key, "true"), Attribute::Event(EventListener { type_, to_message, stop_propagation, prevent_default, js_closure, }) => { let to_message = to_message.clone(); let program = self.program.clone(); let stop_propagation = *stop_propagation; let prevent_default = *prevent_default; let closure = Closure::wrap(Box::new(move |event: web_sys::Event| { if prevent_default { event.prevent_default(); } if stop_propagation { event.stop_propagation(); } let result = match &to_message { EventToMessage::StaticMsg(msg) => Program::dispatch(&program, msg), }; if let Err(error) = result { log::error!("{:#?}", error); } }) as Box<Fn(_)>); let node_et: &web_sys::EventTarget = &node; node_et .add_event_listener_with_callback(&type_, closure.as_ref().unchecked_ref())?; let ret = js_closure.0.replace(Some(closure)); if ret.is_some() { log::warn!("to_message did already have a closure???"); } Ok(()) } } } } fn remove_attribute<Msg>( node: &web_sys::Element, attribute: &Attribute<Msg>, ) -> Result<(), JsValue> { match attribute { Attribute::Key(_) => {} // TODO: I think I know why elm normalizes before adding and removing attributes. We should probably do the same Attribute::Text(key, _) => { node.remove_attribute(key)?; } Attribute::Bool(key) => { node.remove_attribute(key)?; } Attribute::Event(EventListener { type_, js_closure, .. }) => { if let Some(closure) = js_closure.0.replace(None) { let node_et: &web_sys::EventTarget = &node; node_et.remove_event_listener_with_callback( &type_, closure.as_ref().unchecked_ref(), )?; } else { log::warn!("Could not get a function to remove listener"); } } } Ok(()) }
true
98daeb4ad09fbe47547460753d3ee2557c91af08
Rust
rekka/ndarray-npy
/src/lib.rs
UTF-8
3,563
3.140625
3
[ "MIT" ]
permissive
//! A simple serialization of ndarray arrays of simple types (`f32`, `f64`) into //! [NumPy](http://www.numpy.org/)'s [`.npy` //! format](https://docs.scipy.org/doc/numpy/neps/npy-format.html). //! //! Files produced this way can be loaded with //! [`numpy.load`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.load.html). //! //! # Simple example //! //! ```rust,no_run //! extern crate ndarray; //! extern crate ndarray_npy; //! //! use ndarray::prelude::*; //! use std::fs::File; //! //! fn main() { //! let arr: Array2<f64> = Array2::zeros((3, 4)); //! //! let mut file = File::create("test.npy").unwrap(); //! //! ndarray_npy::write(&mut file, &arr).unwrap(); //! } //! ``` //! extern crate byteorder; extern crate ndarray; use byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian, WriteBytesExt}; use std::io; use ndarray::prelude::*; use ndarray::Data; static MAGIC_VALUE: &[u8] = b"\x93NUMPY"; /// npy format Version 1.0 static NPY_VERSION: &[u8] = b"\x01\x00"; /// Types that can be serialized using this crate. pub trait DType<B> { fn dtype() -> &'static str; fn write_bytes(self, w: &mut io::Write) -> io::Result<()>; } macro_rules! impl_dtype { ($type:ty, $dtype:expr, $byteorder_fn:ident) => { impl<B: ByteOrder> DType<B> for $type { fn dtype() -> &'static str { $dtype } fn write_bytes(self, w: &mut io::Write) -> io::Result<()> { w.$byteorder_fn::<B>(self) } } } } impl_dtype!(f32, "f4", write_f32); impl_dtype!(f64, "f8", write_f64); trait NumpyEndian { fn endian_symbol() -> &'static str; } impl NumpyEndian for LittleEndian { fn endian_symbol() -> &'static str { "<" } } impl NumpyEndian for BigEndian { fn endian_symbol() -> &'static str { ">" } } fn get_header<A, B>(shape: &[usize]) -> String where A: DType<B>, B: NumpyEndian, { use std::fmt::Write; let mut shape_str = String::new(); for (i, s) in shape.iter().enumerate() { if i > 0 { shape_str.push_str(","); } write!(&mut shape_str, "{}", s).unwrap(); } format!( "{{'descr': '{endian}{dtype}','fortran_order': False,'shape': ({shape})}}\n", endian = B::endian_symbol(), dtype = A::dtype(), shape = shape_str ) } /// Write an ndarray to a writer in the numpy format. /// /// Can be saved with file extension `npy` and loaded using `numpy.load`. pub fn write<A, S, D>(w: &mut io::Write, array: &ArrayBase<S, D>) -> io::Result<()> where S: Data<Elem = A>, D: Dimension, A: DType<NativeEndian> + Copy, { let header = get_header::<A, NativeEndian>(array.shape()); let padding = (16 - (MAGIC_VALUE.len() + 4 + header.len()) % 16) % 16; let header_len = header.len() + padding; // the following value must be divisible by 16 assert_eq!( (MAGIC_VALUE.len() + 4 + header_len) % 16, 0, "Invalid alignment of the npy header" ); assert!( header_len <= u16::max_value() as usize, "Length of the npy header overflowed." ); w.write(MAGIC_VALUE)?; w.write(NPY_VERSION)?; w.write_u16::<LittleEndian>(header_len as u16)?; w.write(header.as_bytes())?; // padding for _ in 0..padding { w.write_u8(b' ')?; } // actual data for x in array.iter() { x.write_bytes(w)?; } Ok(()) } // #[cfg(test)] // mod tests { // #[test] // fn it_works() { // } // }
true
a139b33a69e8f4f93c02603ef245d95ff65fcef3
Rust
plyhun/plygui
/api/src/callbacks.rs
UTF-8
2,752
2.6875
3
[ "MIT", "Apache-2.0" ]
permissive
use crate::{controls, types::{adapter}}; pub use crate::inner::{ auto::OnFrame, has_size::OnSize, has_visibility::OnVisibility, clickable::OnClick, closeable::OnClose, item_clickable::OnItemClick, member::MemberBase, }; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{SendError, Sender}; static GLOBAL_COUNT: AtomicUsize = AtomicUsize::new(0); #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct CallbackId(usize); impl CallbackId { pub fn next() -> CallbackId { CallbackId(atomic_next()) } } impl Display for CallbackId { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "#{}", self.0) } } fn atomic_next() -> usize { GLOBAL_COUNT.fetch_add(1, Ordering::SeqCst) } pub trait Callback { fn name(&self) -> &'static str; fn id(&self) -> CallbackId; } #[derive(Debug, Clone)] pub struct AsyncFeeder<T: Callback> { sender: Sender<T>, } impl<T: Callback> AsyncFeeder<T> { pub fn feed(&mut self, data: T) -> Result<(), SendError<T>> { self.sender.send(data) } } impl<T: Callback> From<Sender<T>> for AsyncFeeder<T> { fn from(s: Sender<T>) -> Self { AsyncFeeder { sender: s } } } unsafe impl<T: Callback> Send for AsyncFeeder<T> {} unsafe impl<T: Callback> Sync for AsyncFeeder<T> {} macro_rules! callback { ($id: ident, $($typ:tt)+) => { pub struct $id(CallbackId, Box<dyn $($typ)+>); impl Callback for $id { fn name(&self) -> &'static str { stringify!($id) } fn id(&self) -> CallbackId { self.0 } } impl <T> From<T> for $id where T: $($typ)+ + Sized + 'static { fn from(t: T) -> $id { $id(CallbackId::next(), Box::new(t)) } } impl AsRef<dyn $($typ)+> for $id { fn as_ref(&self) -> &(dyn $($typ)+ + 'static) { self.1.as_ref() } } impl AsMut<dyn $($typ)+> for $id { fn as_mut(&mut self) -> &mut (dyn $($typ)+ + 'static) { self.1.as_mut() } } impl From<$id> for (CallbackId, Box<dyn $($typ)+>) { fn from(a: $id) -> Self { (a.0, a.1) } } impl From<(CallbackId, Box<dyn $($typ)+>)> for $id { fn from(a: (CallbackId, Box<dyn $($typ)+>)) -> Self { $id(a.0, a.1) } } impl ::std::fmt::Debug for $id { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}({})", self.name(), self.id().0) } } impl ::std::cmp::PartialEq for $id { fn eq(&self, other: &$id) -> bool { self.id().eq(&other.id()) } } } } //callback!(OnFrame, FnMut(&mut dyn controls::Window) -> bool); callback!(Action, FnMut(&mut dyn controls::Member) -> bool); on!(ItemChange (&mut MemberBase, adapter::Change));
true
5f588224059b2eac14e389bec50030a9d57246cb
Rust
plyhun/plygui
/api/src/inner/closeable.rs
UTF-8
4,065
2.765625
3
[ "MIT", "Apache-2.0" ]
permissive
use crate::callbacks::*; use super::auto::{AsAny, HasInner, Abstract}; use super::member::{AMember, Member, MemberInner, MemberBase}; use super::application::Application; define_abstract! { Closeable : Member { extends: { 'static + AsAny }, outer: { fn on_close(& mut self, callback : Option < OnClose >) ; fn application(&self) -> &dyn Application; fn application_mut(&mut self) -> &mut dyn Application; }, inner: { fn close (& mut self, skip_callbacks : bool) -> bool ; fn on_close(& mut self, callback : Option < OnClose >) ; fn application<'a>(&'a self, base: &'a MemberBase) -> &'a dyn Application; fn application_mut<'a>(&'a mut self, base: &'a mut MemberBase) -> &'a mut dyn Application; } base: { application: usize, } } } pub struct OnClose(CallbackId, Box < dyn FnMut (& mut dyn Closeable,) -> bool >) ; impl Callback for OnClose { fn name (& self) -> & 'static str { stringify ! (OnClose) } fn id (& self) -> CallbackId { self . 0 } } impl < T > From < T > for OnClose where T : FnMut (& mut dyn Closeable) -> bool + Sized + 'static { fn from (t : T) -> OnClose { OnClose (CallbackId :: next (), Box :: new (t)) } } impl AsRef < dyn FnMut (& mut dyn Closeable,) -> bool > for OnClose { fn as_ref (& self) -> &(dyn FnMut (& mut dyn Closeable) -> bool + 'static) { self . 1 . as_ref () } } impl AsMut < dyn FnMut (& mut dyn Closeable,) -> bool > for OnClose { fn as_mut (& mut self) -> & mut (dyn FnMut (& mut dyn Closeable) -> bool + 'static) { self . 1 . as_mut () } } impl From < OnClose > for (CallbackId, Box < dyn FnMut (& mut dyn Closeable) -> bool >) { fn from (a : OnClose) -> Self { (a . 0, a . 1) } } impl From <(CallbackId, Box < dyn FnMut (& mut dyn Closeable) -> bool >) > for OnClose { fn from(a : (CallbackId, Box < dyn FnMut (& mut dyn Closeable) -> bool >)) -> Self { OnClose (a . 0, a . 1) } } impl :: std :: fmt :: Debug for OnClose { fn fmt (& self, f : & mut :: std :: fmt :: Formatter) -> :: std :: fmt :: Result { write ! (f, "{}({})", self . name (), self . id ()) } } impl :: std :: cmp :: PartialEq for OnClose { fn eq (& self, other : & OnClose) -> bool { self . id () . eq (& other . id ()) } } impl<II: CloseableInner, T: HasInner<I = II> + Abstract + 'static> CloseableInner for T { fn close(&mut self, skip_callbacks: bool) -> bool { self.inner_mut().close(skip_callbacks) } fn on_close(&mut self, callback: Option<OnClose>) { self.inner_mut().on_close(callback) } fn application<'a>(&'a self, base: &'a MemberBase) -> &'a dyn Application { self.inner().application(base) } fn application_mut<'a>(&'a mut self, base: &'a mut MemberBase) -> &'a mut dyn Application { self.inner_mut().application_mut(base) } } impl<T: CloseableInner> Closeable for AMember<T> { fn on_close(&mut self, callback: Option<OnClose>) { self.inner.on_close(callback) } fn as_closeable(&self) -> &dyn Closeable { self } fn as_closeable_mut(&mut self) -> &mut dyn Closeable { self } fn into_closeable(self: Box<Self>) -> Box<dyn Closeable> { self } fn application(&self) -> &dyn Application { self.inner.application(&self.base) } fn application_mut(&mut self) -> &mut dyn Application { self.inner.application_mut(&mut self.base) } } impl<T: CloseableInner> ACloseable<T> { pub fn with_inner<A: Application>(inner: T, application: &mut A) -> Self { Self { base: CloseableBase { application: application as *mut _ as usize }, inner, } } pub fn application_impl<A: Application>(&self) -> &A { unsafe { ::std::mem::transmute(self.base.application) } } pub fn application_impl_mut<A: Application>(&mut self) -> &mut A { unsafe { ::std::mem::transmute(self.base.application) } } }
true
f176f21513ba694460e722cad1f219af2abb8a2a
Rust
afprusin/leetcode-rust
/src/bin/68_text_justification.rs
UTF-8
796
3.296875
3
[]
no_license
pub struct Solution {} impl Solution { pub fn full_justify(words: Vec<String>, max_width: i32) -> Vec<String> { let mut lines: Vec<Vec<&String>> = Vec::new(); let mut current_line = Vec::new(); let mut character_count = 0; for word in &words { if (character_count + word.len() + current_line.len()) as i32 <= max_width { current_line.push(word); character_count += word.len(); } else { lines.push(current_line); current_line = Vec::new(); current_line.push(word); character_count = word.len(); } } return vec![]; } } fn main() { assert_eq!(Vec::<String>::new(), Solution::full_justify(vec![], 0)); }
true
6b294bc4ab7910c9dd74c2dc6e595addfa24b072
Rust
FreeCX/advent-of-code
/2020/day04/src/part_one.rs
UTF-8
721
2.875
3
[ "CC0-1.0" ]
permissive
use crate::id::Id; pub fn is_valid_one(id: &Id) -> bool { id.birth_year.is_some() && id.issue_year.is_some() && id.expiration_year.is_some() && id.height.is_some() && id.hair_color.is_some() && id.eye_color.is_some() && id.passport_id.is_some() } pub fn process(ids: &Vec<Id>) -> u32 { let mut valid_count = 0; for id in ids { if is_valid_one(id) { valid_count += 1; } } valid_count } #[cfg(test)] mod tests { use crate::parse; use crate::part_one; #[test] fn example01() { let result = part_one::process(&parse::parse(include_str!("../data/example01"))); assert_eq!(result, 2); } }
true
00b7a940b5d5524c1c248895d868d66ee67898ac
Rust
kpcyrd/cargo-deb
/src/debarchive.rs
UTF-8
1,787
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use crate::error::CDResult; use crate::manifest::Config; use crate::pathbytes::*; use ar::{Builder, Header}; use std::fs; use std::fs::File; use std::path::{Path, PathBuf}; pub struct DebArchive { out_abspath: PathBuf, prefix: PathBuf, ar_builder: Builder<File>, } impl DebArchive { pub fn new(config: &Config) -> CDResult<Self> { let out_filename = format!("{}_{}_{}.deb", config.deb_name, config.deb_version, config.architecture); let prefix = config.deb_temp_dir(); let out_abspath = config.deb_output_path(&out_filename); { let deb_dir = out_abspath.parent().ok_or("invalid dir")?; let _ = fs::create_dir_all(deb_dir); } let ar_builder = Builder::new(File::create(&out_abspath)?); Ok(DebArchive { out_abspath, prefix, ar_builder, }) } pub(crate) fn filename_glob(config: &Config) -> String { format!("{}_*_{}.deb", config.deb_name, config.architecture) } pub fn add_path(&mut self, path: &Path) -> CDResult<()> { let dest_path = path.strip_prefix(&self.prefix).map_err(|_| "invalid path")?; let mut file = File::open(&path)?; self.ar_builder.append_file(&dest_path.as_unix_path(), &mut file)?; Ok(()) } pub fn add_data(&mut self, dest_path: &str, mtime_timestamp: u64, data: &[u8]) -> CDResult<()> { let mut header = Header::new(dest_path.as_bytes().to_owned(), data.len() as u64); header.set_mode(0o644); header.set_mtime(mtime_timestamp); header.set_uid(0); header.set_gid(0); self.ar_builder.append(&header, data)?; Ok(()) } pub fn finish(self) -> CDResult<PathBuf> { Ok(self.out_abspath) } }
true
ef64255d0fe908f02f09cd6386896a7000a0d307
Rust
carl-erwin/unlimited
/src/lib.rs
UTF-8
390
2.625
3
[ "MIT" ]
permissive
/// This module contains the server core pub mod core; /// This module contains the ui front-ends.<br/> /// The current design uses Sender/Receiver to exchange data/state to the core pub mod ui; // TODO(ceg): pub mod misc /// simple function to sort a (T, T) pair pub fn sort_pair<T: PartialOrd>(t: (T, T)) -> (T, T) { if t.0 > t.1 { (t.1, t.0) } else { t } }
true
38e1a65e186cc04cdf8c31b495f874ec071f4f4c
Rust
jessicalally/rust-regex
/src/parser.rs
UTF-8
12,698
3.1875
3
[]
no_license
use self::{Atom::*, ClassMember::*, Quantifier::*, Term::*}; use crate::lexer::{Lexemes, Lexemes::*}; use std::iter::Peekable; use std::slice::Iter; pub type Expr = Vec<Term>; #[derive(Debug, PartialEq, Clone)] pub enum Term { TAtom(Atom), TOp(Quantifier), } #[derive(Debug, PartialEq, Clone)] pub enum Atom { AtomExpr(Expr), AtomCh(char), CharClass(Vec<ClassMember>), } #[derive(Debug, PartialEq, Clone)] pub enum ClassMember { Ch(char), Range(char, char), Caret(Box<[ClassMember]>), } #[derive(Debug, PartialEq, Clone)] pub enum Quantifier { Plus(Atom), Star(Atom), Question(Atom), Invert(Atom), } const ASCII_MIN: char = ' '; const ASCII_MAX: char = '~'; const WORD_CHARS: [ClassMember; 4] = [Ch('_'), Range('a', 'z'), Range('A', 'Z'), Range('0', '9')]; /// Parses a single meta-character, converting it to ASCII characters /// /// # Arguments /// /// * 'c': the meta-character /// * 'class_members': a mutable vector that contains all the parsed members of the current character class fn parse_meta_characters( c: char, class_members: &mut Vec<ClassMember>, ) -> Result<(), &'static str> { match c { '.' => { class_members.push(Ch('\t')); class_members.push(Range(ASCII_MIN, ASCII_MAX)); } 'b' => class_members.push(Ch('\n')), 's' => { class_members.push(Ch(' ')); class_members.push(Ch('\t')); } 'w' => class_members.append(&mut WORD_CHARS.to_vec()), 'd' => class_members.push(Range('0', '9')), 'B' => class_members.push(Caret(Box::new([Ch('\n')]))), 'S' => class_members.push(Caret(Box::new([Ch(' '), Ch('\t')]))), 'W' => class_members.push(Caret(Box::new(WORD_CHARS))), 'D' => class_members.push(Caret(Box::new([Range('0', '9')]))), _ => return Err("Invalid meta character"), } Ok(()) } /// Parses a range of characters /// /// # Arguments /// /// * 'lexemes': an iterator through the regex lexemes /// * 'class_members': a mutable vector that contains all the parsed members of the current character class fn parse_range( lexemes: &mut Peekable<Iter<'_, Lexemes>>, class_members: &mut Vec<ClassMember>, ) -> Result<(), &'static str> { if let Some(Ch(lower)) = class_members.pop() { if let Some(Char(upper)) = lexemes.next() { class_members.push(Range(lower, *upper)); return Ok(()); } } Err("Invalid range expression") } /// Parses a single member of a character class /// /// # Arguments /// /// * 'lexeme': the current lexemes being parsed /// * 'lexemes': an iterator through the regex lexemes /// * 'class_members': a mutable vector that contains all the parsed members of the current character class fn parse_class_member( lexeme: &Lexemes, lexemes: &mut Peekable<Iter<'_, Lexemes>>, class_members: &mut Vec<ClassMember>, ) -> Result<(), &'static str> { match lexeme { Quantifier('-') => parse_range(lexemes, class_members)?, Char(c) => class_members.push(Ch(*c)), Meta(c) => parse_meta_characters(*c, class_members)?, _ => return Err("Invalid class member"), } Ok(()) } /// Parses a character class /// /// # Arguments /// /// * 'lexemes': an iterator through the regex lexemes fn parse_character_class(lexemes: &mut Peekable<Iter<'_, Lexemes>>) -> Result<Atom, &'static str> { let mut class_members = Vec::new(); while let Some(lexeme) = lexemes.next() { match lexeme { RSquare => { if let Some(Quantifier('^')) = lexemes.peek() { lexemes.next(); return Ok(CharClass(vec![Caret(class_members.into_boxed_slice())])); } return Ok(CharClass(class_members)); } _ => parse_class_member(lexeme, lexemes, &mut class_members)?, } } Err("Character class does not contain a closing bracket") } /// Parses an atom of the regex string, e.g. a character, meta-character, or square bracket /// /// # Arguments /// /// * 'lexemes': an iterator through the regex lexemes fn parse_atom(lexemes: &mut Peekable<Iter<'_, Lexemes>>) -> Result<Atom, &'static str> { if let Some(lexeme) = lexemes.next() { match lexeme { LSquare => return parse_character_class(lexemes), LRound => return Ok(AtomExpr(parse_expression(lexemes)?)), Char(c) => return Ok(AtomCh(*c)), Meta(c) => { let mut members = Vec::new(); parse_meta_characters(*c, &mut members)?; return Ok(CharClass(members)); } Quantifier(_) => return Err("An quantifier must be preceeded by another atom"), _ => return Err("Lexeme is not an atom"), }; } Err("No lexemes present") } /// Parses a regex quantifier, e.g. +, *, ? or ^ /// /// # Arguments /// /// * 'lexemes': an iterator through the regex lexemes fn parse_quantifier<'a>( lexemes: &mut Peekable<Iter<'_, Lexemes>>, ) -> Result<Box<dyn Fn(Atom) -> Quantifier + 'a>, &'static str> { // PRE: the next lexeme is an quantifier match lexemes.next().unwrap() { Quantifier('+') => Ok(Box::new(Plus)), Quantifier('*') => Ok(Box::new(Star)), Quantifier('?') => Ok(Box::new(Question)), Quantifier('^') => Ok(Box::new(Invert)), _ => Err("Lexeme is not an quantifier"), } } /// Parses a regex term, which may be either an atom, or an atom with a quantifier /// /// # Arguments /// /// * 'lexemes': an iterator through the regex lexemes fn parse_term(lexemes: &mut Peekable<Iter<'_, Lexemes>>) -> Result<Term, &'static str> { let atom = parse_atom(lexemes)?; if let Some(Quantifier(_)) = lexemes.peek() { let op = parse_quantifier(lexemes)?; return Ok(TOp(op(atom))); } Ok(TAtom(atom)) } /// Parses a regex expression /// /// # Arguments /// /// * 'lexemes': an iterator through the regex lexemes fn parse_expression(lexemes: &mut Peekable<Iter<'_, Lexemes>>) -> Result<Expr, &'static str> { let mut expr: Vec<Term> = Vec::new(); while let Some(lexeme) = lexemes.peek() { match lexeme { RRound => { lexemes.next(); return Ok(expr); } _ => expr.push(parse_term(lexemes)?), } } Ok(expr) } /// Parses the whole lexed regex pattern /// /// # Arguments /// /// * 'lexemes': a slice that contains all the lexemes of the regex pattern pub fn parse(lexemes: &[Lexemes]) -> Result<Expr, &'static str> { let mut lexeme_iter = lexemes.iter().peekable(); let expr = parse_expression(&mut lexeme_iter)?; if lexeme_iter.next().is_none() { return Ok(expr); } Err("Invalid regex expression") } #[cfg(test)] mod parser_tests { use crate::lexer::lex; use crate::parser::*; #[test] fn test_parse_class_member() { let mut class_members = vec![]; parse_class_member( &Char('a'), &mut vec![].iter().peekable(), &mut class_members, ) .expect("Failure with parsing char"); assert_eq!(class_members, vec![Ch('a')]); let mut class_members = vec![]; parse_class_member( &Char('A'), &mut vec![Quantifier('-'), Char('Z')].iter().peekable(), &mut class_members, ) .expect("Failure with parsing range"); assert_eq!(class_members, vec![Ch('A')]); } #[test] fn test_parse_character_class() { let result = parse_character_class(&mut vec![Char('a'), Char('b'), RSquare].iter().peekable()) .expect("Failure with char"); assert_eq!(result, CharClass(vec![Ch('a'), Ch('b')])); let result = parse_character_class( &mut vec![Char('A'), Quantifier('-'), Char('Z'), RSquare] .iter() .peekable(), ) .expect("Failure with range"); assert_eq!(result, CharClass(vec![Range('A', 'Z')])); let result = parse_character_class( &mut vec![ Char('A'), Quantifier('-'), Char('Z'), Char('a'), Quantifier('-'), Char('z'), RSquare, ] .iter() .peekable(), ) .expect("Failure with multiple ranges"); assert_eq!(result, CharClass(vec![Range('A', 'Z'), Range('a', 'z')])); } #[test] fn test_parse_atom() { let result = parse_atom(&mut vec![Char('a'), Char('b')].iter().peekable()) .expect("Failure parsing Char atom"); assert_eq!(result, AtomCh('a')); let result = parse_atom( &mut vec![LSquare, Char('A'), Quantifier('-'), Char('Z'), RSquare] .iter() .peekable(), ) .expect("Failure parsing character class"); assert_eq!(result, CharClass(vec![Range('A', 'Z')])); let result = parse_atom( &mut vec![ LSquare, Char('A'), Quantifier('-'), Char('Z'), Char('a'), Quantifier('-'), Char('z'), RSquare, ] .iter() .peekable(), ) .expect("Failure parsing character class with multiple ranges"); assert_eq!(result, CharClass(vec![Range('A', 'Z'), Range('a', 'z')])); } #[test] fn test_parse_term() { let lexemes = vec![Char('a'), Char('b')]; let result = parse_term(&mut lexemes.iter().peekable()).expect("Failure parsing character term"); assert_eq!(result, TAtom(AtomCh('a'))); let lexemes = vec![ LSquare, Char('A'), Quantifier('-'), Char('Z'), RSquare, Quantifier('+'), ]; let result = parse_term(&mut lexemes.iter().peekable()) .expect("Failure parsing term with plus quantifier"); assert_eq!(result, TOp(Plus(CharClass(vec![Range('A', 'Z')])))); let lexemes = vec![ LSquare, Char('A'), Quantifier('-'), Char('Z'), Char('a'), Quantifier('-'), Char('z'), RSquare, Quantifier('?'), ]; let result = parse_term(&mut lexemes.iter().peekable()) .expect("Failure parsing term with question quantifier"); assert_eq!( result, TOp(Question(CharClass(vec![Range('A', 'Z'), Range('a', 'z')]))) ); } #[test] fn test_parse() { let mut lexemes = lex(&String::from("yee+t")).expect("Failure lexing string with plus quantifier"); let result = parse(&mut lexemes).expect("Failure parsing lexemes with plus quantifier"); assert_eq!( result, vec![ TAtom(AtomCh('y')), TAtom(AtomCh('e')), TOp(Plus(AtomCh('e'))), TAtom(AtomCh('t')) ] ); let mut lexemes = lex(&String::from( "(mailto:)?[\\w\\-\\.]+'[\\w\\-]+(.[A-Za-z]+)+", )) .expect("Failure lexing string with subexpression"); let result = parse(&mut lexemes).expect("Failure parsing lexemes with subexpression"); assert_eq!( result, vec![ TOp(Question(AtomExpr(vec![ TAtom(AtomCh('m')), TAtom(AtomCh('a')), TAtom(AtomCh('i')), TAtom(AtomCh('l')), TAtom(AtomCh('t')), TAtom(AtomCh('o')), TAtom(AtomCh(':')) ]))), TOp(Plus(CharClass(vec![ Ch('_'), Range('a', 'z'), Range('A', 'Z'), Range('0', '9'), Ch('-'), Range('!', '~') ]))), TAtom(AtomCh('\'')), TOp(Plus(CharClass(vec![ Ch('_'), Range('a', 'z'), Range('A', 'Z'), Range('0', '9'), Ch('-') ]))), TOp(Plus(AtomExpr(vec![ TAtom(AtomCh('.')), TOp(Plus(CharClass(vec![Range('A', 'Z'), Range('a', 'z')]))) ]))) ] ); } }
true
fced12806eebc04444760191087d615f840e5e36
Rust
JamesMcGuigan/ecosystem-research
/rust/rust-crash-course/src/arrays.rs
UTF-8
1,421
3.515625
4
[ "MIT" ]
permissive
use std::mem; use std::mem::size_of_val; pub fn run() { // Arrays are stack allocated let numbers: [i32; 5] = [1, 2, 3, 4, 5]; println!("numbers: {:?}", numbers); println!("numbers[0]: {:?}", numbers[0]); println!("&numbers: {:?}", &numbers); println!("&numbers[1..3]: {:?}", &numbers[1..3]); // create a view slice println!("&numbers[2..]: {:?}", &numbers[2..]); // create a view slice println!("&numbers[..2]: {:?}", &numbers[..2]); // create a view slice // Vectors are heap allocated let mut vector: Vec<i32> = vec![1, 2, 3, 4, 5]; vector.push(6); vector.push(7); vector.extend_from_slice(&[8,9,10]); vector.pop(); println!("vector: {:?}", vector); for n in vector.iter_mut() { *n *= 2; } // inplace .map() println!("vector: {:?}", vector); for n in vector.iter() { println!("{}", n); } println!("std::mem::size_of_val(&vector): {}", std::mem::size_of_val(&vector)); println!("std::mem::size_of_val(&numbers): {}", std::mem::size_of_val(&numbers)); println!("use std::mem; mem::size_of_val(&numbers): {}", mem::size_of_val(&numbers)); // with use std::mem; println!("use std::mem::size_of_val; size_of_val(&numbers): {}", size_of_val(&numbers)); // with use std::mem::size_of_val; println!("use std::mem::size_of_val; size_of_val(&numbers): {}", size_of_val(&numbers)); }
true
6f256879c0fc8e7f376f03388996f8e700f6ca2a
Rust
ivan-brko/can_over_zmq_broker
/src/main.rs
UTF-8
1,587
2.953125
3
[]
no_license
extern crate zmq; //TODO: move this function to it's own module fn initialize_zmq() -> (zmq::Context, zmq::Socket, zmq::Socket) { let context = zmq::Context::new(); let broadcaster = context.socket(zmq::PUB).unwrap(); //TODO: add error handling here! assert!(broadcaster.bind("tcp://127.0.0.1:5558").is_ok()); //TODO: handle this in a nicer way let listener = context.socket(zmq::PULL).unwrap(); //TODO: again, handle this in a nicer way assert!(listener.bind("tcp://127.0.0.1:4568").is_ok()); //TODO: same thing (context, broadcaster, listener) } fn get_id_from_message(msg: &[u8]) -> u32 { let mut sum: u32 = 0; for (i, v) in msg[..4].iter().rev().enumerate() { sum += 256u32.pow(i as u32) * (*v as u32); } sum } fn print_message(msg: &[u8]) { let mut printed_message = String::from("Message:\tid:"); let id = get_id_from_message(msg); printed_message.push_str(&id.to_string()); printed_message.push_str("; data: "); for msg_byte in msg.iter().skip(4) { printed_message.push_str(&format!("{:X} ", msg_byte)) } println!("{}", printed_message); } fn main() { println!("Starting the can-over-zmq broker"); let (_context, broadcaster, listener) = initialize_zmq(); loop { //TODO: some flag should be added here, when we want to gracefully exit let msg = listener.recv_bytes(0).unwrap(); //TODO: check what this flags set, TODO: Error handling! print_message(&msg); broadcaster.send(&msg, 0).unwrap(); //TODO: checks flags and error handling } }
true
0b35202e2ddb64c1b75ed1fc5e3f72a9ee8fa873
Rust
digitalbitbox/bitbox02-firmware
/src/rust/vendor/bytes/src/lib.rs
UTF-8
3,536
2.875
3
[ "MIT", "Apache-2.0" ]
permissive
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] #![doc(test( no_crate_inject, attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables)) ))] #![doc(html_root_url = "https://docs.rs/bytes/1.0.0")] #![no_std] //! Provides abstractions for working with bytes. //! //! The `bytes` crate provides an efficient byte buffer structure //! ([`Bytes`](struct.Bytes.html)) and traits for working with buffer //! implementations ([`Buf`], [`BufMut`]). //! //! [`Buf`]: trait.Buf.html //! [`BufMut`]: trait.BufMut.html //! //! # `Bytes` //! //! `Bytes` is an efficient container for storing and operating on contiguous //! slices of memory. It is intended for use primarily in networking code, but //! could have applications elsewhere as well. //! //! `Bytes` values facilitate zero-copy network programming by allowing multiple //! `Bytes` objects to point to the same underlying memory. This is managed by //! using a reference count to track when the memory is no longer needed and can //! be freed. //! //! A `Bytes` handle can be created directly from an existing byte store (such as `&[u8]` //! or `Vec<u8>`), but usually a `BytesMut` is used first and written to. For //! example: //! //! ```rust //! use bytes::{BytesMut, BufMut}; //! //! let mut buf = BytesMut::with_capacity(1024); //! buf.put(&b"hello world"[..]); //! buf.put_u16(1234); //! //! let a = buf.split(); //! assert_eq!(a, b"hello world\x04\xD2"[..]); //! //! buf.put(&b"goodbye world"[..]); //! //! let b = buf.split(); //! assert_eq!(b, b"goodbye world"[..]); //! //! assert_eq!(buf.capacity(), 998); //! ``` //! //! In the above example, only a single buffer of 1024 is allocated. The handles //! `a` and `b` will share the underlying buffer and maintain indices tracking //! the view into the buffer represented by the handle. //! //! See the [struct docs] for more details. //! //! [struct docs]: struct.Bytes.html //! //! # `Buf`, `BufMut` //! //! These two traits provide read and write access to buffers. The underlying //! storage may or may not be in contiguous memory. For example, `Bytes` is a //! buffer that guarantees contiguous memory, but a [rope] stores the bytes in //! disjoint chunks. `Buf` and `BufMut` maintain cursors tracking the current //! position in the underlying byte storage. When bytes are read or written, the //! cursor is advanced. //! //! [rope]: https://en.wikipedia.org/wiki/Rope_(data_structure) //! //! ## Relation with `Read` and `Write` //! //! At first glance, it may seem that `Buf` and `BufMut` overlap in //! functionality with `std::io::Read` and `std::io::Write`. However, they //! serve different purposes. A buffer is the value that is provided as an //! argument to `Read::read` and `Write::write`. `Read` and `Write` may then //! perform a syscall, which has the potential of failing. Operations on `Buf` //! and `BufMut` are infallible. extern crate alloc; #[cfg(feature = "std")] extern crate std; pub mod buf; pub use crate::buf::{Buf, BufMut}; mod bytes; mod bytes_mut; mod fmt; mod loom; pub use crate::bytes::Bytes; pub use crate::bytes_mut::BytesMut; // Optional Serde support #[cfg(feature = "serde")] mod serde; #[inline(never)] #[cold] fn abort() -> ! { #[cfg(feature = "std")] { std::process::abort(); } #[cfg(not(feature = "std"))] { struct Abort; impl Drop for Abort { fn drop(&mut self) { panic!(); } } let _a = Abort; panic!("abort"); } }
true
ab6d481c52919fa26b1a51e83f735c5c17aaa285
Rust
d3k4r/aqueren
/src/lib.rs
UTF-8
14,843
2.703125
3
[ "MIT" ]
permissive
extern crate rustc_serialize; mod game; pub mod types; pub mod server; use game::*; use types::*; type BoardTiles = [[i32; COLS as usize]; ROWS as usize]; type PlayerTiles = [[(i32,i32); 6]; PLAYERS as usize]; #[test] fn players_start_with_six_tiles() { let game = new_game(); for player in game.players { assert_eq!(player.tiles.len(), 6); } } #[test] fn players_start_with_6000_in_cash() { let game = new_game(); for player in game.players { assert_eq!(player.money, 6000); } } #[test] fn players_start_with_zero_shares() { let game = new_game(); for player in game.players { assert_eq!(player.shares.luxor, 0); assert_eq!(player.shares.tower, 0); assert_eq!(player.shares.american, 0); assert_eq!(player.shares.festival, 0); assert_eq!(player.shares.worldwide, 0); assert_eq!(player.shares.continental, 0); assert_eq!(player.shares.imperial, 0); } } #[test] fn game_starts_with_four_placed_tiles() { let game = new_game(); let board_tiles = game.board.slots.iter().filter(|s| s.has_tile).count(); assert_eq!(board_tiles, 4) } #[test] fn placing_a_tile_adds_tile_to_board() { let start_tiles = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let end_tiles = [[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let player_tiles = [[ (0,0), (0,1), (0,2), (0,3), (0,4), (0,5) ], [ (1,0), (1,1), (1,2), (1,3), (1,4), (1,5) ], [ (2,2), (2,1), (2,2), (2,3), (2,4), (2,5) ], [ (3,3), (3,1), (3,2), (3,3), (3,4), (3,5) ]]; let game = new_game_with_tiles(start_tiles, player_tiles); let tile_to_place = Tile::new(0,2).unwrap(); let action = Action::PlaceTile { player: PlayerId::One, tile: tile_to_place }; match play_turn(&game, &action) { TurnResult::Success(game_after) => { assert_boards_equal(&tiles_to_board(&end_tiles), &game_after.board); } _ => { panic!("Placing a valid tile failed") } } } #[test] fn placing_a_tile_fails_if_player_does_not_have_tile() { let start_tiles = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let player_tiles = [[ (0,0), (0,1), (0,2), (0,3), (0,4), (0,5) ], [ (1,0), (1,1), (1,2), (1,3), (1,4), (1,5) ], [ (2,2), (2,1), (2,2), (2,3), (2,4), (2,5) ], [ (3,3), (3,1), (3,2), (3,3), (3,4), (3,5) ]]; let game = new_game_with_tiles(start_tiles, player_tiles); let tile_to_place = Tile::new(5,11).unwrap(); let action = Action::PlaceTile { player: PlayerId::One, tile: tile_to_place }; match play_turn(&game, &action) { TurnResult::Success(_) => { panic!("Placing a tile succeeded when player did not have tile") } _ => {} } } #[test] fn placing_a_tile_fails_if_player_does_not_have_turn() { let start_tiles = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let player_tiles = [[ (0,0), (0,1), (0,2), (0,3), (0,4), (0,5) ], [ (1,0), (1,1), (1,2), (1,3), (1,4), (1,5) ], [ (2,2), (2,1), (2,2), (2,3), (2,4), (2,5) ], [ (3,3), (3,1), (3,2), (3,3), (3,4), (3,5) ]]; let game = new_game_with_tiles(start_tiles, player_tiles); let tile_to_place = Tile::new(1,4).unwrap(); let action = Action::PlaceTile { player: PlayerId::Two, tile: tile_to_place }; match play_turn(&game, &action) { TurnResult::Success(_) => { panic!("Placing a tile succeeded when player did not have turn") } _ => {} } } #[test] fn placing_a_tile_removes_tile_from_player() { let start_tiles = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let player_tiles = [[ (0,0), (0,1), (0,2), (0,3), (0,4), (0,5) ], [ (1,0), (1,1), (1,2), (1,3), (1,4), (1,5) ], [ (2,2), (2,1), (2,2), (2,3), (2,4), (2,5) ], [ (3,3), (3,1), (3,2), (3,3), (3,4), (3,5) ]]; let game = new_game_with_tiles(start_tiles, player_tiles); let tile_to_place = Tile::new(0,2).unwrap(); let action = Action::PlaceTile { player: PlayerId::One, tile: tile_to_place.clone() }; match play_turn(&game, &action) { TurnResult::Success(game_after) => { let player = game_after.players.iter().find(|p| p.id == PlayerId::One).unwrap(); let has_tile = player.tiles.iter().any(|t| *t == tile_to_place); assert!(!has_tile, "Placed tile was still on player") } _ => { panic!("Placing a valid tile failed") } } } #[test] fn buying_stocks_reduces_player_money() { let start_tiles = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let player_tiles = [[ (0,0), (0,1), (0,2), (0,3), (0,4), (0,5) ], [ (1,0), (1,1), (1,2), (1,3), (1,4), (1,5) ], [ (2,2), (2,1), (2,2), (2,3), (2,4), (2,5) ], [ (3,3), (3,1), (3,2), (3,3), (3,4), (3,5) ]]; let game = new_game_with_tiles(start_tiles, player_tiles); let action = Action::BuyStocks { player: PlayerId::One, hotel1: Some(Hotel::Luxor), hotel2: None, hotel3: None }; match play_turn(&game, &action) { TurnResult::Success(game_after) => { let player = game_after.players.iter().find(|p| p.id == PlayerId::One).unwrap(); let expected_money = 5800; let error_msg = format!("After buying stocks, expected player to have {:?} dollars but player had {:?} dollars", expected_money, player.money); assert!(player.money == expected_money, error_msg) } _ => { panic!("Failed buying stocks") } } } #[test] fn buying_stocks_gives_player_bought_stocks() { let start_tiles = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let player_tiles = [[ (0,0), (0,1), (0,2), (0,3), (0,4), (0,5) ], [ (1,0), (1,1), (1,2), (1,3), (1,4), (1,5) ], [ (2,2), (2,1), (2,2), (2,3), (2,4), (2,5) ], [ (3,3), (3,1), (3,2), (3,3), (3,4), (3,5) ]]; let game = new_game_with_tiles(start_tiles, player_tiles); let action = Action::BuyStocks { player: PlayerId::One, hotel1: Some(Hotel::Luxor), hotel2: Some(Hotel::Luxor), hotel3: Some(Hotel::Imperial) }; match play_turn(&game, &action) { TurnResult::Success(game_after) => { let player = game_after.players.iter().find(|p| p.id == PlayerId::One).unwrap(); let expected_shares = PlayerShares { luxor: 2, tower: 0, american: 0, festival: 0, worldwide: 0, continental: 0, imperial: 1 }; let error_msg = format!("After buying stocks, expected player to have shares\n{:?} but player had shares\n{:?}", expected_shares, player.shares); assert!(player.shares == expected_shares, error_msg) } _ => { panic!("Failed buying stocks") } } } #[test] fn player_can_draw_tile() { } #[test] fn drawing_tile_ends_players_turn() { } #[test] fn placing_an_adjacent_tile_creates_chain() { let start_tiles = [[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let player_tiles = [[ (0,0), (0,1), (0,2), (0,3), (0,4), (0,5) ], [ (1,0), (1,1), (1,2), (1,3), (1,4), (1,5) ], [ (2,2), (2,1), (2,2), (2,3), (2,4), (2,5) ], [ (3,3), (3,1), (3,2), (3,3), (3,4), (3,5) ]]; let game = new_game_with_tiles(start_tiles, player_tiles); let tile_to_place = Tile::new(0,5).unwrap(); let action = Action::PlaceTile { player: PlayerId::One, tile: tile_to_place.clone() }; match play_turn(&game, &action) { TurnResult::Success(game_after) => { let game_state = game_after.turn_state; assert!(game_state == TurnState::CreatingChain, "Placing adjacent tile did not change state to creating chain") } _ => { panic!("Placing a valid tile failed") } } } #[test] fn placing_a_tile_goes_to_buy_and_draw() { let start_tiles = [[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let player_tiles = [[ (0,0), (0,1), (0,2), (0,3), (0,4), (0,5) ], [ (1,0), (1,1), (1,2), (1,3), (1,4), (1,5) ], [ (2,2), (2,1), (2,2), (2,3), (2,4), (2,5) ], [ (3,3), (3,1), (3,2), (3,3), (3,4), (3,5) ]]; let game = new_game_with_tiles(start_tiles, player_tiles); let tile_to_place = Tile::new(0,2).unwrap(); let action = Action::PlaceTile { player: PlayerId::One, tile: tile_to_place.clone() }; match play_turn(&game, &action) { TurnResult::Success(game_after) => { let game_state = game_after.turn_state; assert!(game_state == TurnState::BuyingOrDrawing, "Placing a tile did not change state to buying or drawing") } _ => { panic!("Placing a valid tile failed") } } } fn new_game_with_tiles(start_tiles: BoardTiles, player_tiles: PlayerTiles) -> Game { let (starting_tiles, _) = board_tiles_to_tiles(&start_tiles); let players = player_tiles .iter() .enumerate() .map(|(i, tiles)| { let _tiles = tiles .iter() .map(|&(r,c)| Tile::new(r as u8, c as u8).unwrap() ) .collect(); new_player(PlayerId::new((i+1) as u8).unwrap(), _tiles) }) .collect(); let slots = initial_slots(starting_tiles); Game { board: Board { slots: slots }, players: players, turn: PlayerId::One, turn_state: TurnState::Placing } } fn board_tiles_to_tiles(tiles: &BoardTiles) -> (Vec<Tile>, Vec<Tile>) { let mut chosen = Vec::new(); let mut others = Vec::new(); for row in 0..tiles.len() { for col in 0..tiles[0].len() { let tile = Tile::new(row as u8, col as u8).unwrap(); if tiles[row][col] == 1 { chosen.push(tile) } else { others.push(tile) } } } (chosen, others) } fn assert_boards_equal(expected: &Board, actual: &Board) { let are_equal = expected.slots .iter() .zip(actual.slots.iter()) .all(|(left, right)| *left == *right ); let error_msg = format!("\n\nBoard did not have expected tiles.\n\nExpected tiles:\n{}\n\nActual tiles:\n{}\n\n", print_board(&expected), print_board(&actual)); assert!(are_equal, error_msg); } fn tiles_to_board(tiles: &BoardTiles) -> Board { let board_tiles = tiles .iter() .enumerate() .flat_map(|(row, row_tiles)| { let slots: Vec<Slot> = row_tiles .iter() .enumerate() .map(|(col, val): (usize, &i32)| { let has_tile = *val == 1; Slot { row: row as u8, col: col as u8, has_tile: has_tile, hotel: None } }) .collect(); slots }).collect(); Board { slots: board_tiles } } fn row_to_char<'a>(row: u8) -> &'a str { let mapping = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]; mapping[row as usize] } fn print_tile(slot: &Slot) -> String{ format!("{}{}", row_to_char(slot.row), slot.col + 1) } fn print_board(board: &Board) -> String { let mut string = String::new(); string.push_str(" 1 2 3 4 5 6 7 8 9 10 11 12\n"); for row in board.slots.chunks(COLS as usize) { let row_char = row_to_char(row[0].row); string.push_str(&format!("{} ", row_char)); for slot in row { string.push_str(&format!("{:<2} ", if slot.has_tile { '\u{25FC}' } else { '\u{25FB}' })); } string.push_str(&format!("{}\n", row_char)); } string.push_str(" 1 2 3 4 5 6 7 8 9 10 11 12"); string }
true
6cfd1332ab03a183320744b25f324cccaa2fb700
Rust
NatoliChris/rust-learn
/rust-by-example/modules.rs
UTF-8
491
3.390625
3
[]
no_license
mod my_mod { fn private_function() { println!("Shh I'm private, only called inside `private_function()`"); } pub fn pub_function() { println!("Hi I'm a public function `my_mod::function()`"); } pub fn call_priv() { println!("I'm about to call private!!"); private_function(); } pub mod nested { pub fn function() { println!("I'm nested"); } } } fn main() { my_mod::pub_function(); my_mod::nested::function(); my_mod::call_priv(); }
true
9fcd10fe25894d44161cc7586b8ac296663bf451
Rust
Cerber-Ursi/auto_curry
/tests/smoke.rs
UTF-8
239
2.625
3
[]
no_license
#![feature(unboxed_closures)] #![feature(fn_traits)] use auto_curry::auto_curry; #[auto_curry] fn test(arg1: u8, arg2: &str) -> String { format!("{}-{}", arg1, arg2) } fn main() { assert_eq!(test(0, "test"), test(0)("test")); }
true
ea3487ec19e76c67b67d50e50f69244b85c2fdbd
Rust
kristianhasselknippe/shooter
/engine/src/game_state.rs
UTF-8
717
2.875
3
[]
no_license
use super::glm::Vector2; use entities::*; #[derive(Debug)] pub struct GameState { ecs: EntityComponentStore, name: String, } impl GameState { pub fn new(name: &str) -> GameState { GameState { ecs: EntityComponentStore::new(), name: name.to_string(), } } pub fn new_entity(&mut self, name: &str) -> EntityRef { self.ecs .add_entity(Entity::new(name, Vector2::new(0.0, 0.0))) } pub fn new_entity_with_pos(&mut self, name: &str, pos: Vector2<f32>) -> EntityRef { self.ecs.add_entity(Entity::new(name, pos)) } pub fn get_entity(&self, er: &EntityRef) -> Option<&Entity> { self.ecs.get_entity(er) } }
true
2bc22def857cf8fc6e1e16cf8b2ab8dc1cbeb5cc
Rust
vangroan/rlox
/rlox-core/tests/test_array_init.rs
UTF-8
403
2.90625
3
[]
no_license
//! Macro tests cannot live in the special proc macro package. use rlox_derive::array_init; /// Importantly, this type does not implement `Clone` or `Copy`. #[derive(Debug, PartialEq, Eq)] struct Foo { value: u32, } #[test] fn test_array_init() { let arr1 = array_init!(Foo, [Foo { value: 169_093_200 }; 16]); for el in &arr1 { assert_eq!(el, &Foo { value: 169_093_200 }); } }
true
629e94e73073fb5a4b0f139b79538cc86227cdea
Rust
genos/online_problems
/exercism/rust/hello-world/tests/hello-world.rs
UTF-8
322
3.03125
3
[ "MIT" ]
permissive
extern crate hello_world; #[test] fn test_no_name() { assert_eq!("Hello, World!", hello_world::hello(None)); } #[test] fn test_sample_name() { assert_eq!("Hello, Alice!", hello_world::hello(Some("Alice"))); } #[test] fn test_other_same_name() { assert_eq!("Hello, Bob!", hello_world::hello(Some("Bob"))); }
true
c3190daf36d6cf9e1d32e4010ac84f86d1e2abfa
Rust
vojtechkral/rust-c-import
/src/def.rs
UTF-8
1,727
2.515625
3
[]
no_license
use syntax::codemap::{Span, Spanned}; use syntax::ast; use syntax::ast::{Name, Ident, Expr, Item, Visibility}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::ptr::P; use rustc_serialize::json::{Json, Decoder}; use rustc_serialize::Decodable; pub fn hack_vis(item: &mut P<Item>, vis: Visibility) { let item_mut = unsafe { &mut *::std::mem::transmute::<_, *mut Item>(&**item) }; item_mut.vis = vis; } pub trait Def { fn make_item(&self, cx: &mut ExtCtxt, sp: Span, name: Name) -> P<Item>; } pub type Defs = Vec<Box<Def>>; pub fn def_from_json(json: &Json) -> Option<Box<Def>> { if !json.is_object() { return None; } if let Some(cnst) = json.find("const") { if let Some(const_int) = cnst.find("int") { let mut decoder = Decoder::new(const_int.clone()); return Some(Box::new(DefConstInt::decode(&mut decoder).unwrap())); } } None } #[derive(RustcDecodable)] struct DefConstInt { bits: i32, value: i64, } impl Def for DefConstInt { fn make_item(&self, cx: &mut ExtCtxt, sp: Span, name: Name) -> P<Item> { use syntax::ast::Expr_::ExprLit; use syntax::ast::Lit_::LitInt; use syntax::ast::LitIntType::UnsuffixedIntLit; use syntax::ast::Sign::*; let sign = if self.value >= 0 { Plus } else { Minus }; let ty = match self.bits { 8 => quote_ty!(cx, i8), 16 => quote_ty!(cx, i16), 32 => quote_ty!(cx, i32), _ => quote_ty!(cx, i64), }; let value = P(Expr{ id: ast::DUMMY_NODE_ID, node: ExprLit(P(Spanned{ node: LitInt(self.value as u64, UnsuffixedIntLit(sign)), span: sp, })), span: sp, }); let mut item = cx.item_const(sp, Ident::new(name), ty, value); hack_vis(&mut item, Visibility::Public); item } }
true