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
d84a7eba9a7818a8e8672d6a48bd3408bb42c1c7
Rust
uldza/serde_eetf
/src/ser.rs
UTF-8
17,790
3.09375
3
[]
no_license
use num_bigint::BigInt; use num_traits::cast::FromPrimitive; use serde::ser::{self, Serialize}; use std::convert::TryFrom; use std::io; use heck::SnakeCase; use eetf::{self, Term}; use crate::error::{Error, Result}; /// Serializes a value into EETF using a Write pub fn to_writer<T, W>(value: &T, writer: &mut W) -> Result<()> where T: Serialize + ?Sized, W: io::Write + ?Sized, { let serializer = Serializer {}; let term = value.serialize(&serializer)?; match term.encode(writer) { Ok(_result) => Ok(()), Err(_error) => Err(Error::EncodeError("TODO".to_string())), } } /// Serializes a value into a EETF in a Vec of bytes pub fn to_bytes<T>(value: &T) -> Result<Vec<u8>> where T: Serialize + ?Sized, { let mut cursor = io::Cursor::new(Vec::new()); match to_writer(value, &mut cursor) { Ok(_) => Ok(cursor.into_inner()), Err(e) => Err(e), } } /// Serializes struct Serializer {} struct SequenceSerializer { items: Vec<Term>, } struct NamedSequenceSerializer { name: Term, items: Vec<Term>, } struct MapSerializer { items: Vec<(Term, Term)>, } struct NamedMapSerializer { name: Term, items: Vec<(Term, Term)>, } impl<'a> ser::Serializer for &'a Serializer { // The output type produced by this `Serializer` during successful // serialization. type Ok = Term; // The error type when some error occurs during serialization. type Error = Error; // Associated types for keeping track of additional state while serializing // compound data structures like sequences and maps. type SerializeSeq = SequenceSerializer; type SerializeTuple = SequenceSerializer; type SerializeTupleStruct = SequenceSerializer; type SerializeTupleVariant = NamedSequenceSerializer; type SerializeMap = MapSerializer; type SerializeStruct = MapSerializer; type SerializeStructVariant = NamedMapSerializer; // The following 12 methods receive one of the primitive types of the data // model and map it to eetf fn serialize_bool(self, v: bool) -> Result<Term> { // TODO: Make this actually a boolean? Ok(Term::Atom(eetf::Atom::from(if v { "true" } else { "false" }))) } // eetf has two kinds of integers: 32 bit ones and big ints. fn serialize_i8(self, v: i8) -> Result<Term> { self.serialize_i32(i32::from(v)) } fn serialize_i16(self, v: i16) -> Result<Term> { self.serialize_i32(i32::from(v)) } fn serialize_i32(self, v: i32) -> Result<Term> { Ok(Term::FixInteger(eetf::FixInteger { value: v })) } fn serialize_i64(self, v: i64) -> Result<Term> { let big_int = BigInt::from_i64(v).expect("TODO: Handle failure here"); Ok(Term::BigInteger(eetf::BigInteger { value: big_int })) } fn serialize_u8(self, v: u8) -> Result<Term> { self.serialize_u16(u16::from(v)) } fn serialize_u16(self, v: u16) -> Result<Term> { Ok(Term::FixInteger(eetf::FixInteger::from(v))) } // The eetf crate uses an i32 to encode FixIntegers, so for unsigned numbers // we use a BigInteger instead. fn serialize_u32(self, v: u32) -> Result<Term> { self.serialize_u64(u64::from(v)) } fn serialize_u64(self, v: u64) -> Result<Term> { let big_int = BigInt::from_u64(v).expect("TODO: Handle failure here"); Ok(Term::BigInteger(eetf::BigInteger { value: big_int })) } fn serialize_f32(self, v: f32) -> Result<Term> { self.serialize_f64(f64::from(v)) } fn serialize_f64(self, v: f64) -> Result<Term> { Ok(Term::Float(eetf::Float::try_from(v)?)) } // Serialize a char as a single-character string. // TODO: Decide if this is a good idea. fn serialize_char(self, v: char) -> Result<Term> { self.serialize_str(&v.to_string()) } fn serialize_str(self, v: &str) -> Result<Term> { Ok(Term::Binary(eetf::Binary::from(v.as_bytes()))) } fn serialize_bytes(self, v: &[u8]) -> Result<Term> { Ok(Term::Binary(eetf::Binary::from(v))) } // An absent optional is represented as the JSON `null`. fn serialize_none(self) -> Result<Term> { Ok(Term::Atom(eetf::Atom::from("nil"))) } // At present optional is represented as just the contained value. Note that // this is a lossy representation. For example the values `Some(())` and // `None` both serialize as just `null`. // TODO: Decide if this makes sense. fn serialize_some<T>(self, value: &T) -> Result<Term> where T: ?Sized + Serialize, { value.serialize(self) } // In Serde, unit means an anonymous value containing no data. // Map this to eetf as `nil`. fn serialize_unit(self) -> Result<Term> { // TODO: Decide if this is right. self.serialize_none() } // Unit struct means a named value containing no data. // We basically just treat this like nil for now. fn serialize_unit_struct(self, _name: &'static str) -> Result<Term> { self.serialize_unit() } // When serializing a unit variant (or any other kind of variant), formats // can choose whether to keep track of it by index or by name. Binary // formats typically use the index of the variant and human-readable formats // typically use the name. fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result<Term> { Ok(Term::Atom(eetf::Atom::from(variant.to_snake_case()))) } // We treat newtype structs as insignificant wrappers around the data they // contain. fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Term> where T: ?Sized + Serialize, { value.serialize(self) } // Note that newtype variant (and all of the other variant serialization // methods) refer exclusively to the "externally tagged" enum // representation. // // We serialize this to {value_name, value}, which hopefully allows results // to be serialized into fairly standard erlang ok/err tuples. fn serialize_newtype_variant<T>( self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result<Term> where T: ?Sized + Serialize, { let serialized_value = value.serialize(self)?; Ok(Term::Tuple(eetf::Tuple::from(vec![ Term::Atom(eetf::Atom::from(variant.to_snake_case())), serialized_value, ]))) } fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { let vec = match len { None => Vec::new(), Some(len) => Vec::with_capacity(len), }; Ok(SequenceSerializer { items: vec }) } fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { Ok(SequenceSerializer { items: Vec::with_capacity(len), }) } // We treat tuple structs exactly like tuples for now. // TODO: Decide if this is a good idea. fn serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct> { self.serialize_tuple(len) } // Tuple variants are represented in eetf as `{name, {data}}`. Again // this method is only responsible for the externally tagged representation. // TODO: decide if this is a good idea... fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant> { Ok(NamedSequenceSerializer { name: Term::Atom(eetf::Atom::from(variant.to_snake_case())), items: Vec::with_capacity(len), }) } fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { let vec = match len { None => Vec::new(), Some(len) => Vec::with_capacity(len), }; Ok(MapSerializer { items: vec }) } fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> { // TODO: decide how to do this.... // do we want to tag things? self.serialize_map(Some(len)) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant> { Ok(NamedMapSerializer { name: Term::Atom(eetf::Atom::from(variant.to_snake_case())), items: Vec::with_capacity(len), }) } } impl<'a> ser::SerializeSeq for SequenceSerializer { type Ok = Term; type Error = Error; // Serialize a single element of the sequence. fn serialize_element<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { let term_value = value.serialize(&Serializer {})?; self.items.push(term_value); Ok(()) } fn end(self) -> Result<Term> { Ok(Term::List(eetf::List { elements: self.items, })) } } impl<'a> ser::SerializeTuple for SequenceSerializer { type Ok = Term; type Error = Error; // Serialize a single element of the sequence. fn serialize_element<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { let term_value = value.serialize(&Serializer {})?; self.items.push(term_value); Ok(()) } fn end(self) -> Result<Term> { Ok(Term::Tuple(eetf::Tuple { elements: self.items, })) } } impl<'a> ser::SerializeTupleStruct for SequenceSerializer { type Ok = Term; type Error = Error; // Serialize a single element of the sequence. fn serialize_field<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { let term_value = value.serialize(&Serializer {})?; self.items.push(term_value); Ok(()) } fn end(self) -> Result<Term> { Ok(Term::Tuple(eetf::Tuple { elements: self.items, })) } } impl<'a> ser::SerializeTupleVariant for NamedSequenceSerializer { type Ok = Term; type Error = Error; // Serialize a single element of the sequence. fn serialize_field<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { let term_value = value.serialize(&Serializer {})?; self.items.push(term_value); Ok(()) } fn end(self) -> Result<Term> { // TODO: rename items to elements. let serialized_data = Term::Tuple(eetf::Tuple { elements: self.items, }); Ok(Term::Tuple(eetf::Tuple::from(vec![ self.name, serialized_data, ]))) } } impl<'a> ser::SerializeMap for MapSerializer { type Ok = Term; type Error = Error; // Serialize a single element of the sequence. fn serialize_key<T>(&mut self, _value: &T) -> Result<()> where T: ?Sized + Serialize, { panic!("Not Implemented") } fn serialize_value<T>(&mut self, _value: &T) -> Result<()> where T: ?Sized + Serialize, { panic!("Not Implemented") } fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<()> where K: Serialize, V: Serialize, { let key_term = key.serialize(&Serializer {})?; let value_term = value.serialize(&Serializer {})?; self.items.push((key_term, value_term)); Ok(()) } fn end(self) -> Result<Term> { // TODO: rename items to entries. Ok(Term::Map(eetf::Map { entries: self.items, })) } } impl<'a> ser::SerializeStruct for MapSerializer { type Ok = Term; type Error = Error; fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + Serialize, { let value_term = value.serialize(&Serializer {})?; self.items .push((Term::Atom(eetf::Atom::from(key)), value_term)); Ok(()) } fn end(self) -> Result<Term> { Ok(Term::Map(eetf::Map { entries: self.items, })) } } impl<'a> ser::SerializeStructVariant for NamedMapSerializer { type Ok = Term; type Error = Error; fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + Serialize, { let value_term = value.serialize(&Serializer {})?; self.items .push((Term::Atom(eetf::Atom::from(key)), value_term)); Ok(()) } fn end(self) -> Result<Term> { let serialized_data = Term::Map(eetf::Map { entries: self.items, }); Ok(Term::Tuple(eetf::Tuple::from(vec![ self.name, serialized_data, ]))) } } // TODO: More Tests #[cfg(test)] mod tests { use super::*; // Helper function for tests. Runs things through our serializer then // decodes and returns. fn serialize_and_decode<T>(data: T) -> Term where T: Serialize, { let bytes = to_bytes(&data).expect("serialize failed"); Term::decode(io::Cursor::new(bytes)).expect("Decode failed") } #[test] fn test_unsigned_ints_and_structs() { #[derive(PartialEq, Serialize)] struct TestStruct { unsigned8: u8, unsigned16: u16, unsigned32: u32, unsigned64: u64, } let result = serialize_and_decode(TestStruct { unsigned8: 129, unsigned16: 65530, unsigned32: 65530, unsigned64: 65530, }); assert_eq!( result, Term::Map(eetf::Map::from(vec![ ( Term::Atom(eetf::Atom::from("unsigned8")), Term::FixInteger(eetf::FixInteger::from(129)) ), ( Term::Atom(eetf::Atom::from("unsigned16")), Term::FixInteger(eetf::FixInteger::from(65530)) ), ( Term::Atom(eetf::Atom::from("unsigned32")), Term::BigInteger(eetf::BigInteger::from(65530)) ), ( Term::Atom(eetf::Atom::from("unsigned64")), Term::BigInteger(eetf::BigInteger::from(65530)) ) ])) ) } #[test] fn test_signed_ints_and_tuple_structs() { #[derive(PartialEq, Serialize)] struct TestStruct(i8, i16, i32, i64); let result = serialize_and_decode(TestStruct(-127, 30000, 65530, 65530)); assert_eq!( result, Term::Tuple(eetf::Tuple::from(vec![ Term::FixInteger(eetf::FixInteger::from(-127)), Term::FixInteger(eetf::FixInteger::from(30000)), Term::FixInteger(eetf::FixInteger::from(65530)), Term::BigInteger(eetf::BigInteger::from(65530)), ])) ) } #[test] fn test_binaries_tuples_and_lists() { let result = serialize_and_decode(("ABCD", vec![0, 1, 2])); assert_eq!( result, Term::Tuple(eetf::Tuple::from(vec![ Term::Binary(eetf::Binary::from("ABCD".as_bytes())), Term::List(eetf::List::from(vec![ Term::FixInteger(eetf::FixInteger::from(0)), Term::FixInteger(eetf::FixInteger::from(1)), Term::FixInteger(eetf::FixInteger::from(2)), ])) ])) ) } #[test] fn test_option() { let none: Option<u8> = None; let nil_result = serialize_and_decode(none); let some_result = serialize_and_decode(Some(0)); assert_eq!(nil_result, Term::Atom(eetf::Atom::from("nil"))); assert_eq!(some_result, Term::FixInteger(eetf::FixInteger::from(0))); } #[test] fn test_unit_variant() { #[derive(Serialize)] enum E { AnOption, AnotherOption, }; let result = serialize_and_decode(E::AnOption); assert_eq!(result, Term::Atom(eetf::Atom::from("an_option"))) } #[test] fn test_newtype_variant() { // Not 100% sure if this is a tuple variant or a newtype variant. // But whatever I guess? #[derive(Serialize)] enum ErlResult { Ok(String), }; let result = serialize_and_decode(ErlResult::Ok("test".to_string())); assert_eq!( result, Term::Tuple(eetf::Tuple::from(vec![ Term::Atom(eetf::Atom::from("ok")), Term::Binary(eetf::Binary::from("test".as_bytes())), ])) ); } #[test] fn test_tuple_variant() { // Not 100% sure if this is a tuple variant or a newtype variant. // But whatever I guess? #[derive(Serialize)] enum Testing { Ok(u8, u8), }; let result = serialize_and_decode(Testing::Ok(1, 2)); assert_eq!( result, Term::Tuple(eetf::Tuple::from(vec![ Term::Atom(eetf::Atom::from("ok")), Term::Tuple(eetf::Tuple::from(vec![ Term::FixInteger(eetf::FixInteger::from(1)), Term::FixInteger(eetf::FixInteger::from(2)), ])) ])) ); } }
true
14cb3537313d50e67be6b434e32d9c15f7395a45
Rust
isaacthefallenapple/rust-ansi
/src/cursor.rs
UTF-8
2,113
3.421875
3
[]
no_license
use regex::Regex; macro_rules! print_esc { ($e:expr) => { print!("\x1b{}", $e); }; } pub fn move_vert(n: i32) { if n >= 0 { print_esc!(format!("[{}A", n)); } print_esc!(format!("[{}B", -n)); } pub fn move_hor(n: i32) { if n >= 0 { print_esc!(format!("[{}C", n)); } print_esc!(format!("[{}D", -n)); } pub fn move_to_upper_left() { print_esc!("[H"); } pub fn move_to(line: u32, column: u32) { print_esc!(format!("[{};{}H", line, column)); } pub fn move_to_next_line() { print_esc!("[E"); } pub fn scroll_up() { print_esc!("D"); } pub fn scroll_down() { print_esc!("M"); } pub fn clear_right() { print_esc!("[K"); } pub fn clear_left() { print_esc!("[1K"); } pub fn clear_line() { print_esc!("[2K"); } pub fn clear_down() { print_esc!("[J"); } pub fn clear_up() { print_esc!("[1J"); } pub fn clear_screen() { print_esc!("[2J"); } pub fn save_position() { print_esc!("7"); } pub fn restore_position() { print_esc!("8"); } pub fn get_position() -> (u32, u32) { use std::io::{self, stdin, Read}; lazy_static! { static ref RE: Regex = Regex::new(r"\x1b\[(\d+);(\d+)R").unwrap(); } let mut s = String::new(); print_esc!("[6n\r\n"); std::io::stdin().read_line(&mut s).unwrap(); let m = RE.captures(&s).unwrap(); let (line, column) = (&m[1], &m[2]); let line: u32 = line.parse().unwrap(); let column: u32 = column.parse().unwrap(); (line, column) } #[cfg(test)] mod test { use super::*; #[test] fn cursor_basic() { clear_up(); } #[test] fn test_move_hor() { print!("hello"); move_hor(10); print!("world"); move_hor(-15); print!(","); println!(); } #[test] fn test_move_diagonal() { for i in 0..8 { move_hor(i); println!("{}", std::char::from_u32((i+65) as u32).unwrap()); } println!(); } #[test] fn test_get_pos() { let pos = get_position(); println!("{:?}", pos); } }
true
a2daf3139ed62095c67f042130c6bb3a970da2eb
Rust
tyehle/advent-of-code
/2019/d04/src/main.rs
UTF-8
2,071
3.84375
4
[]
no_license
fn is_valid(pw: &[u8]) -> bool { let mut double = false; let mut prev = pw[0]; for d in pw.iter().skip(1) { if *d < prev { return false; } if *d == prev { double = true; } prev = *d; } double } fn is_valid_b(pw: &[u8]) -> bool { let mut run = 0; let mut double = false; let mut prev = pw[0]; for d in pw.iter().skip(1) { if *d < prev { return false; } if *d == prev { run += 1; } else { if run == 1 { double = true; } run = 0; } prev = *d; } double || run == 1 } fn digits(n: i32) -> Vec<u8> { n.to_string() .chars() .map(|c| c.to_string().parse().unwrap()) .collect() } fn inc(ds: &mut Vec<u8>) { let mut pos = ds.len() - 1; // look for the first digit that's not a 9 while ds[pos] >= 9 { pos -= 1; } // set digit ds[pos] += 1; // set digits below for i in pos + 1..ds.len() { ds[i] = ds[i - 1]; } } fn counter(low: i32, high: i32, predicate: impl Fn(&[u8]) -> bool) -> u32 { let mut ds = digits(low); let end = digits(high); let mut count = 0; loop { if predicate(&ds) { count += 1; } inc(&mut ds); // check end condition for i in 0..ds.len() { if end[i] > ds[i] { break; } if end[i] < ds[i] { return count; } } } } fn main() { println!("{}", counter(153_517, 630_395, is_valid)); println!("{}", counter(153_517, 630_395, is_valid_b)); } #[cfg(test)] mod test { use super::*; #[test] fn test_b_valid() { assert!(is_valid_b(&digits(111_122))); assert!(!is_valid_b(&digits(123_444))); } #[test] fn test_inc() { let mut ds = vec![3, 5, 5, 9, 9]; inc(&mut ds); assert_eq!(ds, vec![3, 5, 6, 6, 6]); } }
true
9b98b23745263b010e6f0b8b2d0ac069efbe666a
Rust
cottonguard/kyopro-rust
/src/libs/io/output.rs
UTF-8
3,857
2.765625
3
[]
no_license
use std::{io::prelude::*, mem::MaybeUninit, ptr, slice, str}; pub struct KOutput<W: Write> { dest: W, delim: bool, } impl<W: Write> KOutput<W> { pub fn new(dest: W) -> Self { Self { dest, delim: false } } pub fn bytes(&mut self, s: &[u8]) { self.dest.write_all(s).unwrap(); } pub fn byte(&mut self, b: u8) { self.bytes(slice::from_ref(&b)); } pub fn output<T: OutputItem>(&mut self, x: T) { if self.delim { self.byte(b' '); } self.delim = true; x.output(self); } pub fn ln(&mut self) { self.delim = false; self.byte(b'\n'); self.flush_debug(); } pub fn inner(&mut self) -> &mut W { &mut self.dest } pub fn seq<T: OutputItem, I: IntoIterator<Item = T>>(&mut self, iter: I) { for x in iter.into_iter() { self.output(x); } } pub fn flush(&mut self) { self.dest.flush().unwrap(); } pub fn flush_debug(&mut self) { if cfg!(debug_assertions) { self.flush(); } } } pub trait OutputItem { fn output<W: Write>(self, dest: &mut KOutput<W>); } impl OutputItem for &str { fn output<W: Write>(self, dest: &mut KOutput<W>) { dest.bytes(self.as_bytes()); } } impl OutputItem for char { fn output<W: Write>(self, dest: &mut KOutput<W>) { self.encode_utf8(&mut [0; 4]).output(dest); } } macro_rules! output_fmt { ($($T:ty)*) => { $(impl OutputItem for $T { fn output<W: Write>(self, dest: &mut KOutput<W>) { write!(dest.inner(), "{}", self).unwrap(); } })* } } output_fmt!(f32 f64); macro_rules! output_int { ($conv:ident; $U:ty; $($T:ty)*) => { $(impl OutputItem for $T { fn output<W: Write>(self, dest: &mut KOutput<W>) { let mut buf = MaybeUninit::<[u8; 20]>::uninit(); unsafe { let ptr = buf.as_mut_ptr() as *mut u8; let ofs = $conv(self as $U, ptr, 20); dest.bytes(slice::from_raw_parts(ptr.add(ofs), 20 - ofs)); } } } impl OutputItem for &$T { fn output<W: Write>(self, dest: &mut KOutput<W>) { (*self).output(dest); } })* }; } output_int!(i64_to_bytes; i64; isize i8 i16 i32 i64); output_int!(u64_to_bytes; u64; usize u8 u16 u32 u64); static DIGITS_LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\ 2021222324252627282930313233343536373839\ 4041424344454647484950515253545556575859\ 6061626364656667686970717273747576777879\ 8081828384858687888990919293949596979899"; unsafe fn i64_to_bytes(x: i64, buf: *mut u8, len: usize) -> usize { let (neg, x) = if x < 0 { (true, -x) } else { (false, x) }; let mut i = u64_to_bytes(x as u64, buf, len); if neg { i -= 1; *buf.add(i) = b'-'; } i } unsafe fn u64_to_bytes(mut x: u64, buf: *mut u8, len: usize) -> usize { let lut = DIGITS_LUT.as_ptr(); let mut i = len; let mut two = |x| { i -= 2; ptr::copy_nonoverlapping(lut.add(2 * x), buf.add(i), 2); }; while x >= 10000 { let rem = (x % 10000) as usize; two(rem % 100); two(rem / 100); x /= 10000; } let mut x = x as usize; if x >= 100 { two(x % 100); x /= 100; } if x >= 10 { two(x); } else { i -= 1; *buf.add(i) = x as u8 + b'0'; } i } #[macro_export] macro_rules! out { ($out:expr, $($args:expr),*) => {{ $($out.output($args);)* }}; } #[macro_export] macro_rules! outln { ($out:expr) => { $out.ln(); }; ($out:expr, $($args:expr),*) => {{ out!($out, $($args),*); outln!($out); }} }
true
34379d5f2138f2f9f43113d234ff3cc5e56b0f90
Rust
gen0083/atcoder_python
/rust/abc218/src/bin/d.rs
UTF-8
895
2.796875
3
[]
no_license
use std::collections::{BTreeSet, HashMap}; use proconio::input; fn main() { input!{ n: usize, points: [(u64, u64); n] } let mut count = 0; let mut xs_by_y: HashMap<u64, BTreeSet<u64>> = HashMap::new(); let mut ys_by_x: HashMap<u64, BTreeSet<u64>> = HashMap::new(); for (x, y) in points.iter() { xs_by_y.entry(*y).or_insert(BTreeSet::new()); ys_by_x.entry(*x).or_insert(BTreeSet::new()); xs_by_y.get_mut(y).unwrap().insert(*x); ys_by_x.get_mut(x).unwrap().insert(*y); } for (x, y) in points { for bx in xs_by_y[&y].range(x+1..) { for by in ys_by_x[&x].range(y+1..) { if let Some(set) = xs_by_y.get(by) { if set.contains(bx) { count+=1; } } } } } println!("{}", count); }
true
7cf2372fd62c2d84ee0fe9e318e4e2f4c333921e
Rust
danieldickison/kachiclash
/build.rs
UTF-8
527
2.890625
3
[ "MIT" ]
permissive
use std::process::Command; fn main() -> Result<(), String> { println!("running sass"); let status = Command::new("sass") .arg("public/scss/:public/css/") .status() .expect("run sass"); if !status.success() { return Err(format!("sass failed with {}", status)); } println!("running npx tsc"); let status = Command::new("npx").arg("tsc").status().expect("run tsc"); if !status.success() { return Err(format!("tsc failed with {}", status)); } Ok(()) }
true
9947ab9952a538d544e4e3cc13983ac592101fe0
Rust
Xaeroxe/nonzero_signed
/src/lib.rs
UTF-8
3,272
3.640625
4
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
use std::cmp::Ordering; use std::fmt; use std::num::*; macro_rules! impl_nonzero_fmt { ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => { $( impl fmt::$Trait for $Ty { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.get().fmt(f) } } )+ } } macro_rules! def_signed { ( $($name:ident($inner:ident, $zeroable_signed:ident, $zeroable:ident),)+) => { $( /// An integer that is known not to equal zero. /// /// This enables some memory layout optimization. /// For example, `Option<NonZeroI32>` is the same size as `i32`: /// /// ```rust /// use std::mem::size_of; /// use nonzero_signed::NonZeroI32; /// assert_eq!(size_of::<Option<NonZeroI32>>(), size_of::<i32>()); /// ``` #[cfg_attr(new_rustc, deprecated(since = "1.0.3", note = "These became part of std::num in Rust 1.34, please use the std types instead of this crate."))] #[derive(Copy, Clone, Eq, PartialEq, Hash)] #[repr(transparent)] pub struct $name($inner); impl $name { /// Create a non-zero without checking the value. /// /// # Safety /// /// The value must not be zero. #[inline] pub unsafe fn new_unchecked(n: $zeroable_signed) -> Self { $name($inner::new_unchecked(n as $zeroable)) } /// Create a non-zero if the given value is not zero. #[inline] pub fn new(n: $zeroable_signed) -> Option<Self> { if n != 0 { Some(unsafe {$name::new_unchecked(n)}) } else { None } } /// Returns the value as a primitive type. #[inline] pub fn get(self) -> $zeroable_signed { self.0.get() as $zeroable_signed } } impl Ord for $name { fn cmp(&self, other: &Self) -> Ordering { self.get().cmp(&other.get()) } } impl PartialOrd for $name { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl_nonzero_fmt! { (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $name } )+ } } def_signed!( NonZeroI8(NonZeroU8, i8, u8), NonZeroI16(NonZeroU16, i16, u16), NonZeroI32(NonZeroU32, i32, u32), NonZeroI64(NonZeroU64, i64, u64), NonZeroI128(NonZeroU128, i128, u128), NonZeroIsize(NonZeroUsize, isize, usize), ); #[cfg(test)] mod tests { use super::*; #[test] fn wrapping_test() { assert!(NonZeroI8::new(0).is_none()); assert!(NonZeroI8::new(-5).unwrap().get() == -5); } #[test] fn format_test() { assert_eq!(format!("{}", NonZeroI8::new(-5).unwrap()), "-5") } }
true
d4029f71804eb6f947237e4b4d09911119f4fcf1
Rust
PSudoLang/PSudo
/libpsudoc/src/parse/rules/expression/field_get.rs
UTF-8
1,984
2.734375
3
[ "MIT" ]
permissive
use super::*; use crate::coretypes::{Expression, MemberExpression, Spanned, Token, TokenCategory}; pub struct FieldGet; impl ParseFunction for FieldGet { type Output = Box<dyn FnOnce(Expression) -> Expression>; fn try_parse( context: &mut ParseContext, session: &mut CompileSession, ) -> ParseResult<Self::Output> { context.skip_whitespaces(true); let question = context .next_token_categoried(&[TokenCategory::PunctuationQuestionMark]) .is_some(); let dot = if let Some(dot) = context.next_token_categoried(&[TokenCategory::PunctuationFullStop]) { dot.clone() } else { return ParseResult::Fail(false); }; context.skip_whitespaces(true); match context .next_token_categoried(&[TokenCategory::IdentifierIdentifier]) .cloned() { Some(Token { category: TokenCategory::IdentifierIdentifier, span, }) => { let text = span.source_text(&session); ParseResult::Success(Box::new(move |lhs| { Expression::Member(MemberExpression::Field( lhs.span().joined(&span).expect("In the same file"), Box::new(lhs), text, question, )) })) } Some(token) => { token .span .diagnostic_error("Expected identifier in field get, but no token received.") .emit_to(session); ParseResult::Fail(true) } None => { dot.span .diagnostic_error("Expected identifier in field get, but no token received.") .emit_to(session); ParseResult::Fail(true) } } } }
true
ee7111bc37b03e82496f08ad9909fd4412f6c74e
Rust
isgasho/k9
/tests/e2e/test_utils.rs
UTF-8
4,223
2.65625
3
[ "MIT" ]
permissive
use anyhow::{Context, Result}; use derive_builder::Builder; use rand::prelude::*; use regex::RegexBuilder; use std::collections::BTreeMap; use std::fs; use std::path::PathBuf; use std::process::Command; use std::str::FromStr; const E2E_TEMP_DIR: &str = "e2e_tmp_dir"; const CAPTURE_TEST_RESULT_RE: &str = "^test (?P<test>[:_\\w]+) \\.{3} (?P<result>FAILED|ok)$"; pub const TEST_CARGO_TOML: &str = r#" [package] name = "k9_e2e_test_project" version = "0.1.0" authors = ["Aaron Abramov <[email protected]>"] edition = "2018" [dependencies] k9 = { path = "../../" } [lib] name = "test" path = "lib.rs" "#; #[derive(Builder, Default, Debug)] #[builder(default, setter(into))] pub struct TestRun { update_snapshots: bool, root_dir: PathBuf, } impl TestRun { pub fn run(&self) -> Result<TestRunResult> { let mut cmd = Command::new("cargo"); cmd.current_dir(&self.root_dir).arg("test"); if self.update_snapshots { cmd.env("K9_UPDATE_SNAPSHOTS", "1"); } else { // to make sure that we don't propagate parent process setting cmd.env_remove("K9_UPDATE_SNAPSHOTS"); } let output = cmd.output()?; let exit_code = output.status.code(); let success = output.status.success(); let stdout = String::from_utf8(output.stdout)?; let stderr = String::from_utf8(output.stderr)?; let regex = RegexBuilder::new(CAPTURE_TEST_RESULT_RE) .multi_line(true) .build() .unwrap(); let captures = regex.captures_iter(&stdout); let mut test_cases: BTreeMap<String, TestCaseResult> = BTreeMap::new(); for capture in captures { test_cases.insert( capture["test"].to_string(), TestCaseResult { status: TestCaseStatus::from_str(&capture["result"]) .context("can't parse status")?, }, ); } Ok(TestRunResult { exit_code, stderr, stdout, success, test_cases, }) } } pub struct TestRunResult { pub exit_code: Option<i32>, pub stderr: String, pub stdout: String, pub success: bool, pub test_cases: BTreeMap<String, TestCaseResult>, } #[derive(Debug, PartialEq)] pub struct TestCaseResult { pub status: TestCaseStatus, } // Represent a single test case. e.g. `#[test]\nfn my_test() {}` #[derive(Debug, PartialEq, Clone, Copy)] pub enum TestCaseStatus { Pass, Fail, } impl FromStr for TestCaseStatus { type Err = anyhow::Error; fn from_str(input: &str) -> Result<TestCaseStatus> { match input { "ok" => Ok(TestCaseStatus::Pass), "FAILED" => Ok(TestCaseStatus::Fail), _ => Err(anyhow::anyhow!("Unknown test status: `{}`", input)), } } } pub struct TestProject { pub root_dir: PathBuf, } impl TestProject { pub fn new() -> Self { let mut root_dir = PathBuf::from( std::env::var("CARGO_MANIFEST_DIR").expect("Can't get project root directory"), ); let mut rng = rand::thread_rng(); let r: u64 = rng.gen(); root_dir.push(E2E_TEMP_DIR); root_dir.push(format!("{}", r)); Self { root_dir } } pub fn write_file(&self, path: &str, content: &str) -> Result<()> { let mut absolute_path = self.root_dir.clone(); absolute_path.push(path); let dir = absolute_path.parent().unwrap(); fs::create_dir_all(dir)?; fs::write(absolute_path, content)?; Ok(()) } pub fn read_file(&self, path: &str) -> Result<String> { let mut absolute_path = self.root_dir.clone(); absolute_path.push(path); fs::read_to_string(&absolute_path).context("can't read file") } pub fn run_tests(&self) -> TestRunBuilder { let mut builder = TestRunBuilder::default(); builder.root_dir(self.root_dir.clone()); builder } } impl Drop for TestProject { fn drop(&mut self) { // could have been never cerated. don't care about result // let _result = fs::remove_dir_all(&self.root_dir); } }
true
84f082e0b82cfcc2640e8bb060a2f8fcdd609a65
Rust
dkohlsdorf/audio_pattern_discovery
/src/neural.rs
UTF-8
3,092
2.578125
3
[]
no_license
extern crate bincode; extern crate serde_derive; use crate::error::*; use crate::numerics::*; use crate::discovery::*; use bincode::{deserialize, serialize}; use std::fs::File; use std::io::prelude::*; /// Single layer Autoencoder #[derive(Serialize, Deserialize, Clone)] pub struct AutoEncoder { pub w_encode: Mat, pub w_decode: Mat, pub b_encode: Mat, pub b_decode: Mat, } impl AutoEncoder { pub fn n_latent(&self) -> usize { self.b_encode.cols } pub fn step_decay(epoch: f32, params: &Discovery) -> f32 { params.learning_rate * f32::powf(params.drop, f32::floor((1.0 + epoch) / params.epoch_drop)) } pub fn from_file(file: &str) -> Result<AutoEncoder> { let mut fp = File::open(file)?; let mut buf: Vec<u8> = vec![]; let _ = fp.read_to_end(&mut buf)?; let decoded: AutoEncoder = deserialize(&buf).unwrap(); Ok(decoded) } /// save file pub fn save_file(&self, file: &str) -> Result<()> { let mut fp = File::create(file)?; let encoded: Vec<u8> = serialize(&self).unwrap(); fp.write_all(&encoded)?; Ok(()) } pub fn new(input_dim: usize, latent: usize) -> AutoEncoder { AutoEncoder { w_encode: Mat::seeded(input_dim, latent), w_decode: Mat::seeded(latent, input_dim), b_encode: Mat::seeded(1, latent), b_decode: Mat::seeded(1, input_dim), } } pub fn predict(&self, x: &Mat) -> Mat { let prediction = x .mul(&self.w_encode) .add_col(&self.b_encode) .sigmoid() .scale(255.0); let mu = mean(&prediction.flat); let sigma = f32::max(std(&prediction.flat, mu), 1.0); Mat { flat: prediction .flat .iter() .map(|x| z_score(*x, mu, sigma)) .collect(), cols: prediction.cols, } } /// one sgd step given a learning rate pub fn take_step(&mut self, x: &Mat, alpha: f32) -> f32 { let y = x.norm(); let latent = x.mul(&self.w_encode).add_col(&self.b_encode); let latent_activation = latent.sigmoid(); let output = latent.mul(&self.w_decode).add_col(&self.b_decode); let activation = output.sigmoid(); let delta_out = y .sub_ebe(&activation) .scale(-1.0) .mul_ebe(&activation.delta_sigmoid()); let delta_decode = delta_out .mul(&self.w_decode.transpose()) .mul_ebe(&latent_activation.delta_sigmoid()); let grad_decode = latent.transpose().mul(&delta_out).scale(alpha); let grad_encode = x.transpose().mul(&delta_decode).scale(alpha); self.w_encode = self.w_encode.sub_ebe(&grad_encode); self.w_decode = self.w_decode.sub_ebe(&grad_decode); self.b_encode = self.b_encode.sub_ebe(&delta_decode.scale(alpha)); self.b_decode = self.b_decode.sub_ebe(&delta_out.scale(alpha)); 0.5 * euclidean(&activation.flat, &y.flat) } }
true
ec4355fdb14993154388514c21cebeca5b89fb7e
Rust
arichnad/slsh
/src/main.rs
UTF-8
3,243
2.859375
3
[ "MIT" ]
permissive
use std::io; use nix::{ sys::signal::{self, SigHandler, Signal}, unistd, }; use ::slsh::*; fn main() -> io::Result<()> { let config = get_config(); if let Ok(config) = config { if config.command.is_none() && config.script.is_none() { /* See if we are running interactively. */ let shell_terminal = nix::libc::STDIN_FILENO; if let Ok(true) = unistd::isatty(shell_terminal) { /* Loop until we are in the foreground. */ let mut shell_pgid = unistd::getpgrp(); while unistd::tcgetpgrp(shell_terminal) != Ok(shell_pgid) { //kill (- shell_pgid, SIGTTIN); if let Err(err) = signal::kill(shell_pgid, Signal::SIGTTIN) { eprintln!("Error sending sigttin: {}.", err); } shell_pgid = unistd::getpgrp(); } /* Ignore interactive and job-control signals. */ unsafe { signal::signal(Signal::SIGINT, SigHandler::SigIgn).unwrap(); signal::signal(Signal::SIGQUIT, SigHandler::SigIgn).unwrap(); signal::signal(Signal::SIGTSTP, SigHandler::SigIgn).unwrap(); signal::signal(Signal::SIGTTIN, SigHandler::SigIgn).unwrap(); signal::signal(Signal::SIGTTOU, SigHandler::SigIgn).unwrap(); // Ignoring sigchild will mess up waitpid and cause Command::spawn to panic under some conditions. //signal::signal(Signal::SIGCHLD, SigHandler::SigIgn).unwrap(); } /* Put ourselves in our own process group. */ let pgid = unistd::getpid(); if let Err(err) = unistd::setpgid(pgid, pgid) { match err { nix::Error::Sys(nix::errno::Errno::EPERM) => { /* ignore */ } _ => { eprintln!("Couldn't put the shell in its own process group: {}\n", err) } } } /* Grab control of the terminal. */ if let Err(err) = unistd::tcsetpgrp(shell_terminal, pgid) { let msg = format!("Couldn't grab control of terminal: {}\n", err); eprintln!("{}", msg); return Err(io::Error::new(io::ErrorKind::Other, msg)); } start_interactive(); } else { // No tty, just read stdin and do something with it.. read_stdin(); } } else if config.command.is_some() { let command = config.command.unwrap(); if let Err(err) = run_one_command(&command, &config.args) { eprintln!("Error running {}: {}", command, err); return Err(err); } } else if config.script.is_some() { let script = config.script.unwrap(); if let Err(err) = run_one_script(&script, &config.args) { eprintln!("Error running {}: {}", script, err); return Err(err); } } } Ok(()) }
true
0971b9804d22305e0e4d315e71463fc03f6c161b
Rust
cessen/psychopath
/src/parse/basics.rs
UTF-8
3,798
3.03125
3
[ "GPL-3.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Apache-2.0", "MIT" ]
permissive
//! Some basic nom parsers #![allow(dead_code)] use std::str::{self, FromStr}; use nom::{ character::complete::{digit1, multispace0, one_of}, combinator::{map_res, opt, recognize}, number::complete::float, sequence::{delimited, tuple}, IResult, }; // ======================================================== pub fn ws_f32(input: &str) -> IResult<&str, f32, ()> { delimited(multispace0, float, multispace0)(input) } pub fn ws_u32(input: &str) -> IResult<&str, u32, ()> { map_res(delimited(multispace0, digit1, multispace0), u32::from_str)(input) } pub fn ws_usize(input: &str) -> IResult<&str, usize, ()> { map_res(delimited(multispace0, digit1, multispace0), usize::from_str)(input) } pub fn ws_i32(input: &str) -> IResult<&str, i32, ()> { map_res( delimited( multispace0, recognize(tuple((opt(one_of("-")), digit1))), multispace0, ), i32::from_str, )(input) } // ======================================================== #[cfg(test)] mod test { use super::*; use nom::{combinator::all_consuming, sequence::tuple}; #[test] fn ws_u32_1() { assert_eq!(ws_u32("42"), Ok((&""[..], 42))); assert_eq!(ws_u32(" 42"), Ok((&""[..], 42))); assert_eq!(ws_u32("42 "), Ok((&""[..], 42))); assert_eq!(ws_u32(" 42"), Ok((&""[..], 42))); assert_eq!(ws_u32(" 42 53"), Ok((&"53"[..], 42))); } #[test] fn ws_usize_1() { assert_eq!(ws_usize("42"), Ok((&""[..], 42))); assert_eq!(ws_usize(" 42"), Ok((&""[..], 42))); assert_eq!(ws_usize("42 "), Ok((&""[..], 42))); assert_eq!(ws_usize(" 42"), Ok((&""[..], 42))); assert_eq!(ws_usize(" 42 53"), Ok((&"53"[..], 42))); } #[test] fn ws_i32_1() { assert_eq!(ws_i32("42"), Ok((&""[..], 42))); assert_eq!(ws_i32(" 42"), Ok((&""[..], 42))); assert_eq!(ws_i32("42 "), Ok((&""[..], 42))); assert_eq!(ws_i32(" 42"), Ok((&""[..], 42))); assert_eq!(ws_i32(" 42 53"), Ok((&"53"[..], 42))); } #[test] fn ws_i32_2() { assert_eq!(ws_i32("-42"), Ok((&""[..], -42))); assert_eq!(ws_i32(" -42"), Ok((&""[..], -42))); assert_eq!(ws_i32("-42 "), Ok((&""[..], -42))); assert_eq!(ws_i32(" -42"), Ok((&""[..], -42))); assert_eq!(ws_i32(" -42 53"), Ok((&"53"[..], -42))); assert_eq!(ws_i32("--42").is_err(), true); } #[test] fn ws_f32_1() { assert_eq!(ws_f32("42"), Ok((&""[..], 42.0))); assert_eq!(ws_f32(" 42"), Ok((&""[..], 42.0))); assert_eq!(ws_f32("42 "), Ok((&""[..], 42.0))); assert_eq!(ws_f32(" 42"), Ok((&""[..], 42.0))); assert_eq!(ws_f32(" 42 53"), Ok((&"53"[..], 42.0))); } #[test] fn ws_f32_2() { assert_eq!(ws_f32("42.5"), Ok((&""[..], 42.5))); assert_eq!(ws_f32(" 42.5"), Ok((&""[..], 42.5))); assert_eq!(ws_f32("42.5 "), Ok((&""[..], 42.5))); assert_eq!(ws_f32(" 42.5"), Ok((&""[..], 42.5))); assert_eq!(ws_f32(" 42.5 53"), Ok((&"53"[..], 42.5))); } #[test] fn ws_f32_3() { assert_eq!(ws_f32("-42.5"), Ok((&""[..], -42.5))); assert_eq!(ws_f32(" -42.5"), Ok((&""[..], -42.5))); assert_eq!(ws_f32("-42.5 "), Ok((&""[..], -42.5))); assert_eq!(ws_f32(" -42.5"), Ok((&""[..], -42.5))); assert_eq!(ws_f32(" -42.5 53"), Ok((&"53"[..], -42.5))); } #[test] fn ws_f32_4() { assert_eq!(ws_f32("a1.0").is_err(), true); assert_eq!(all_consuming(ws_f32)("0abc").is_err(), true); assert_eq!(tuple((ws_f32, ws_f32))("0.abc 1.2").is_err(), true); } }
true
b4fba85df4dac643aceac208fcae5c7b6ef57374
Rust
rust-lang/rust
/tests/ui/ptr_ops/issue-80309-safe.rs
UTF-8
296
2.53125
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
// run-pass // compile-flags: -O // Regression test for issue #80309 pub fn zero(x: usize) -> usize { std::ptr::null::<i8>().wrapping_add(x) as usize - x } pub fn qux(x: &[i8]) -> i8 { x[zero(x.as_ptr() as usize)] } fn main() { let z = vec![42, 43]; println!("{}", qux(&z)); }
true
4f0fb4ba81ceee93a5ce33edc069e215141e9c36
Rust
Noble-Mushtak/Advent-of-Code
/2022/day18/src/lib.rs
UTF-8
2,407
2.78125
3
[]
no_license
use std::cmp::{min, max}; use std::collections::{HashSet, VecDeque}; use std::error::Error; use std::fs; peg::parser! { grammar parser() for str { rule isize() -> isize = n:$(['0'..='9']+) { n.parse().unwrap() } rule point() -> (isize, isize, isize) = x:isize() "," y:isize() "," z:isize() { (x, y, z) } pub(crate) rule parse() -> Vec<(isize, isize, isize)> = l:(point()**"\n") "\n"? { l } } } const DIRS: [(isize, isize, isize); 6] = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]; fn surface_area(point_set: &HashSet<(isize, isize, isize)>) -> usize { point_set.iter().map(|(x, y, z)| { DIRS.iter().filter(|(dx, dy, dz)| !point_set.contains(&(x+dx, y+dy, z+dz))).count() }).sum() } pub fn run() -> Result<(), Box<dyn Error>> { let points = parser::parse(&fs::read_to_string("in.txt")?)?; let point_set: HashSet<(isize, isize, isize)> = points.iter().copied().collect(); println!("Part 1: {}", surface_area(&point_set)); let (xmin, xmax, ymin, ymax, zmin, zmax) = points.iter().fold((1000, 0, 1000, 0, 1000, 0), |(xmn, xmx, ymn, ymx, zmn, zmx), &(x, y, z)| { (min(xmn, x-1), max(xmx, x+1), min(ymn, y-1), max(ymx, y+1), min(zmn, z-1), max(zmx, z+1)) }); let mut bfs_q: VecDeque<((isize, isize, isize), (isize, isize, isize))> = VecDeque::new(); bfs_q.push_back(((xmin, ymin, zmin), (0, 0, 0))); let mut vis: HashSet<((isize, isize, isize), (isize, isize, isize))> = HashSet::new(); let mut filtered_point_set: HashSet<((isize, isize, isize), (isize, isize, isize))> = HashSet::new(); while let Some(((cur_x, cur_y, cur_z), dir_tpl)) = bfs_q.pop_front() { if point_set.contains(&(cur_x, cur_y, cur_z)) { filtered_point_set.insert(((cur_x, cur_y, cur_z), dir_tpl)); } else { for (dx, dy, dz) in DIRS { let new_pt = (cur_x+dx, cur_y+dy, cur_z+dz); if !vis.contains(&(new_pt, (dx, dy, dz))) && (xmin..=xmax).contains(&new_pt.0) && (ymin..=ymax).contains(&new_pt.1) && (zmin..=zmax).contains(&new_pt.2) { bfs_q.push_back((new_pt, (dx, dy, dz))); vis.insert((new_pt, (dx, dy, dz))); } } } } println!("Part 2: {}", filtered_point_set.len()); Ok(()) }
true
38028eb820b7a53228ab1e9d46cda190fdef26a8
Rust
timothee-haudebourg/generic-btree
/src/dot.rs
UTF-8
367
3.03125
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pub trait Display { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result; fn dot(&self) -> Displayed<Self> { Displayed(self) } } pub struct Displayed<'a, T: ?Sized>(&'a T); impl<'a, T: Display> std::fmt::Display for Displayed<'a, T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { self.0.fmt(f) } }
true
b29f3d86fe84b02341ed4880361247e5fda0aaf6
Rust
unfo/adventofrust
/src/day1.rs
UTF-8
2,742
3.921875
4
[]
no_license
/* Specifically, they need you to find the two entries that sum to 2020 and then multiply those two numbers together. For example, suppose your expense report contained the following: 1721 979 366 299 675 1456 In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying them together produces 1721 * 299 = 514579, so the correct answer is 514579. Of course, your expense report is much larger. Find the two entries that sum to 2020; what do you get if you multiply them together? */ use std::fs; use crate::aoc; pub fn part_one(input_type: aoc::InputData) -> usize { let mut dir = "data"; if let aoc::InputData::Example = input_type { dir = "example"; } let filename = format!("{}/day1.txt", dir); let data = fs::read_to_string(filename) .expect("Something went wrong reading the file"); let numbers: Vec<usize> = data.split_whitespace() .map(|s| s.parse().expect("parse error")) .collect(); for num in numbers.iter() { let diff = 2020 - num; if numbers.iter().any(|&n| n == diff) { return num * diff; } } return 0; } /* --- Part Two --- The Elves in accounting are thankful for your help; one of them even offers you a starfish coin they had left over from a past vacation. They offer you a second one if you can find three numbers in your expense report that meet the same criteria. Using the above example again, the three entries that sum to 2020 are 979, 366, and 675. Multiplying them together produces the answer, 241861950. In your expense report, what is the product of the three entries that sum to 2020? */ pub fn part_two(input_type: aoc::InputData) -> usize { let mut dir = "data"; if let aoc::InputData::Example = input_type { dir = "example"; } let filename = format!("{}/day1.txt", dir); let data = fs::read_to_string(filename) .expect("Something went wrong reading the file"); let numbers: Vec<usize> = data.split_whitespace() .map(|s| s.parse().expect("parse error")) .collect(); for num in numbers.iter() { let middle_point = 2020 - num; for num2 in numbers.iter() { if *num2 < middle_point { let third = middle_point - num2; if numbers.iter().any(|&n| n == third) { return num * num2 * third; } } } } return 0 } #[cfg(test)] mod tests { use crate::aoc; use crate::day1; #[test] fn example_one() { assert_eq!(day1::part_one(aoc::InputData::Example), 514579); } #[test] fn example_two() { assert_eq!(day1::part_two(aoc::InputData::Example), 241861950); } }
true
e1d26fc66a4dd5a3754784a28e08d19f0841847d
Rust
GrossBetruger/RustPlaygound
/number_cruncher/src/main.rs
UTF-8
929
3.375
3
[]
no_license
extern crate num; use num::{BigInt, BigUint, Zero, One, FromPrimitive}; fn factorial(n: usize) -> BigInt { let mut f: BigInt = One::one(); for i in 1..(n+1) { let bu: BigInt = FromPrimitive::from_usize(i).unwrap(); f = f * bu; } f } fn n_choose_k(n: usize, k: usize) -> BigInt { factorial(n) / (factorial(k) * factorial(n - k)) } fn birthday_probability(days: usize, n: usize) -> BigInt{ // can't mix between BigInt and float types, won't work... :( let mut one: BigInt = One::one(); let day_to_n = num::pow(days, n); println!("day to n: {}", day_to_n); let nom = factorial(n) * n_choose_k(days, n); println!("nom: {}", nom); one - (factorial(n) * n_choose_k(days, n) / num::pow(days, (n))) } fn main(){ println!("fac 10: {}", factorial(4)); println!("n choose k: {}", n_choose_k(255, 19)); println!("birthday: {}", birthday_probability(365, 5)); }
true
af77708ded62e682d671b77f65ef0936d2f14fcd
Rust
smwls/aoc20
/src/day3.rs
UTF-8
2,254
3.546875
4
[]
no_license
use std::iter::successors; use std::ops::Add; #[derive(Debug, Clone, PartialEq)] enum GridCell { Tree, Square } type Row = Vec<GridCell>; type Grid = Vec<Row>; #[derive(Debug, Copy, Clone, PartialEq)] struct Coord { right: usize, down: usize } impl Add for Coord { type Output = Self; fn add(self, other: Self) -> Self::Output { Self { right: self.right + other.right, down: self.down + other.down, } } } type Slope = Coord; fn contents_of_cell_at(grid: &Grid, coord: Coord) -> GridCell { let num_rows = grid.len(); let defined_row_width = grid[(coord.down % num_rows)].len(); let row_position = coord.right % defined_row_width; match grid.get(coord.down) { Some(row) => match row.get(row_position) { Some(cell) => cell.clone(), None => GridCell::Square } None => GridCell::Square } } fn get_num_trees_along_slope(grid: &Grid, slope: Slope) -> usize { let num_traverses = (grid.len() / slope.down) + 1; successors(Some(Coord{right: 0, down: 0}), |crd| Some(*crd + slope)) .map(|crd| contents_of_cell_at(&grid, crd)) .take(num_traverses) .filter(|x| *x == GridCell::Tree) .count() } fn parse_input(input: &str) -> Option<Grid> { input.lines() .map(|char_row| { char_row.chars().map(|char| { match char { '.' => Some(GridCell::Square), '#' => Some(GridCell::Tree), _ => None } }).collect::<Option<Row>>() }).collect::<Option<Grid>>() } pub fn run_a(input: &str) { let grid = parse_input(input).unwrap(); let num_trees = get_num_trees_along_slope(&grid, Slope {right: 3, down: 1}); println!("{}", num_trees); } pub fn run_b(input: &str) { let grid = parse_input(input).unwrap(); let slopes = vec![ Slope {right: 1, down: 1}, Slope {right: 3, down: 1}, Slope {right: 5, down: 1}, Slope {right: 7, down: 1}, Slope {right: 1, down: 2} ].into_iter(); let product = slopes.fold(1, |acc, x| acc*get_num_trees_along_slope(&grid, x)); println!("{}", product); }
true
6a6460e8389000c5d47f34289991afd034eebaf6
Rust
flashbuckets/rustful
/src/file.rs
UTF-8
2,268
3.59375
4
[ "MIT" ]
permissive
//!File related utilities. use std::path::{Path, Component}; use mime::{Mime, TopLevel, SubLevel}; include!(concat!(env!("OUT_DIR"), "/mime.rs")); ///Returns the MIME type from a given file extension, if known. /// ///The file extension to MIME type mapping is based on [data from the Apache ///server][apache]. /// ///``` ///use rustful::file::ext_to_mime; ///use rustful::mime::Mime; ///use rustful::mime::TopLevel::Image; ///use rustful::mime::SubLevel::Jpeg; /// ///let mime = ext_to_mime("jpg"); ///assert_eq!(mime, Some(Mime(Image, Jpeg, vec![]))); ///``` /// ///[apache]: http://svn.apache.org/viewvc/httpd/httpd/trunk/docs/conf/mime.types?view=markup pub fn ext_to_mime(ext: &str) -> Option<Mime> { MIME.get(ext).map(|&(ref top, ref sub)| { Mime(top.into(), sub.into(), vec![]) }) } enum MaybeKnown<T> { Known(T), Unknown(&'static str) } impl<'a> Into<TopLevel> for &'a MaybeKnown<TopLevel> { fn into(self) -> TopLevel { match *self { MaybeKnown::Known(ref t) => t.clone(), MaybeKnown::Unknown(t) => TopLevel::Ext(t.into()) } } } impl<'a> Into<SubLevel> for &'a MaybeKnown<SubLevel> { fn into(self) -> SubLevel { match *self { MaybeKnown::Known(ref s) => s.clone(), MaybeKnown::Unknown(s) => SubLevel::Ext(s.into()) } } } ///Check if a path tries to escape its parent directory. /// ///Forbidden path components: /// /// * Root directory /// * Prefixes (e.g. `C:` on Windows) /// * Parent directory /// ///Allowed path components: /// /// * "Normal" components (e.g. `res/scripts`) /// * Current directory /// ///The first forbidden component is returned if the path is invalid. /// ///``` ///use std::path::Component; ///use rustful::file::check_path; /// ///let bad_path = ".."; /// ///assert_eq!(check_path(bad_path), Err(Component::ParentDir)); ///``` pub fn check_path<P: ?Sized + AsRef<Path>>(path: &P) -> Result<(), Component> { for component in path.as_ref().components() { match component { c @ Component::RootDir | c @ Component::Prefix(_) | c @ Component::ParentDir => return Err(c), Component::Normal(_) | Component::CurDir => {} } } Ok(()) }
true
6f4945f52af8043c9ccda5d67caea9ae581113fd
Rust
juliotpaez/jpar
/src/parsers/helpers.rs
UTF-8
11,060
3.15625
3
[ "MIT" ]
permissive
use crate::result::{ParserResult, ParserResultError}; use crate::{Cursor, ParserInput}; /// Restores the reader when a not found error is returned. pub fn not_found_restore<'a, P, C, R, Err>( mut parser: P, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err> where P: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err>, { move |reader| { let init_cursor = reader.save_cursor(); match parser(reader) { Ok(v) => Ok(v), Err(ParserResultError::NotFound) => { reader.restore(init_cursor); Err(ParserResultError::NotFound) } Err(e) => Err(e), } } } /// Maps the result of a parser into a new value. pub fn map_result<'a, P, M, C, R, Rf, Err>( mut parser: P, mut mapper: M, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<Rf, Err> where P: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err>, M: FnMut(&mut ParserInput<'a, Err, C>, R) -> Rf, { move |reader| { let result = parser(reader)?; Ok(mapper(reader, result)) } } /// Maps the result of a parser into a new `ParserResult`. pub fn and_then<'a, P, M, C, R, Rf, Err>( mut parser: P, mut mapper: M, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<Rf, Err> where P: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err>, M: FnMut(&mut ParserInput<'a, Err, C>, R) -> ParserResult<Rf, Err>, { not_found_restore(move |reader| { let result = parser(reader)?; mapper(reader, result) }) } /// Applies a parser over the result of another one. pub fn map_parser<'a, O, P, C: Clone, R, Err>( mut origin: O, mut parser: P, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err> where O: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<&'a str, Err>, P: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err>, { not_found_restore(move |reader| { let result = origin(reader)?; let mut new_reader = ParserInput::new_with_context_and_error(result, reader.context().clone()); parser(&mut new_reader) }) } /// Applies a parser discarding its result and return the consumed content as result. pub fn consumed<'a, P, C, R, Err>( mut parser: P, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<&'a str, Err> where P: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err>, { move |reader| { let init_cursor = reader.save_cursor(); match parser(reader) { Ok(_) => Ok(reader.substring_to_current(&init_cursor).content()), Err(ParserResultError::NotFound) => { reader.restore(init_cursor); Err(ParserResultError::NotFound) } Err(e) => Err(e), } } } /// Applies a parser discarding its result. pub fn ignore_result<'a, P, C, R, Err>( mut parser: P, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<(), Err> where P: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err>, { not_found_restore(move |reader| { let _ = parser(reader)?; Ok(()) }) } /// Always succeeds with given value without consuming any input. pub fn value<'a, C, R: Clone, Err>( value: R, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err> { move |_| Ok(value.clone()) } /// Always succeeds with given value without consuming any input. /// The value is built dynamically. pub fn value_dyn<'a, C, R, Err, VFn>( mut value_fn: VFn, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err> where VFn: FnMut(&mut ParserInput<'a, Err, C>) -> R, { move |reader| Ok(value_fn(reader)) } /// Always fails with the given error without consuming any input. pub fn error<'a, C, R, Err: Clone>( error: Err, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err> { move |reader| { Err(ParserResultError::Error(( reader.save_cursor(), error.clone(), ))) } } /// Always fails with the given error without consuming any input. /// The error is built dynamically. pub fn error_dyn<'a, C, R, Err, EFn>( mut error_fn: EFn, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err> where EFn: FnMut(&mut ParserInput<'a, Err, C>) -> Err, { move |reader| { Err(ParserResultError::Error(( reader.save_cursor(), error_fn(reader), ))) } } /// Ensures that `parser` always success or returns an error. pub fn ensure<'a, P, C, R, Efn, Err>( mut parser: P, mut error_fn: Efn, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err> where P: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err>, Efn: FnMut(&mut ParserInput<'a, Err, C>) -> Err, { move |reader| match parser(reader) { Ok(v) => Ok(v), Err(ParserResultError::NotFound) => Err(ParserResultError::Error(( reader.save_cursor(), error_fn(reader), ))), Err(e) => Err(e), } } /// Applies a parser but allowing to recover in case of an error. pub fn recover<'a, P, C, R, Rfn, Err>( mut parser: P, mut recover_fn: Rfn, ) -> impl FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err> where P: FnMut(&mut ParserInput<'a, Err, C>) -> ParserResult<R, Err>, Rfn: FnMut(&mut ParserInput<'a, Err, C>, Cursor, Err) -> ParserResult<R, Err>, { not_found_restore(move |reader| match parser(reader) { Ok(v) => Ok(v), Err(ParserResultError::NotFound) => Err(ParserResultError::NotFound), Err(ParserResultError::Error((cursor, e))) => recover_fn(reader, cursor, e), }) } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- #[cfg(test)] mod test { use crate::parsers::characters::{ ascii_alpha1, ascii_alpha_quantified, read_any, read_any_quantified, read_text, }; use crate::parsers::sequence::tuple; use crate::ParserResultError; use super::*; #[test] fn test_not_found_restore() { let mut reader = ParserInput::new("This is a test"); let mut parser = not_found_restore(read_text("This")); let result = parser(&mut reader); assert_eq!(result, Ok("This")); assert_eq!(reader.byte_offset(), 4); let mut parser = not_found_restore(|reader| { read_text(" is ")(reader).unwrap(); read_text("This")(reader) }); let result = parser(&mut reader); assert_eq!(result, Err(ParserResultError::NotFound)); assert_eq!(reader.byte_offset(), 4); } #[test] fn test_map_result() { let mut reader = ParserInput::new("This is a test"); let mut parser = map_result(ascii_alpha1, |_, _| 32); let result = parser(&mut reader); assert_eq!(result, Ok(32)); let result = parser(&mut reader); assert_eq!(result, Err(ParserResultError::NotFound)); } #[test] fn test_and_then() { let mut reader = ParserInput::new("This is a test"); let mut parser = and_then(ascii_alpha1, |_, _| Ok(32)); let result = parser(&mut reader); assert_eq!(result, Ok(32)); let result = parser(&mut reader); assert_eq!(result, Err(ParserResultError::NotFound)); // Case when mapper fails. let mut reader = ParserInput::new("This is a test"); let mut parser = and_then(ascii_alpha_quantified(1), |_, _| -> ParserResult<(), ()> { Err(ParserResultError::NotFound) }); let result = parser(&mut reader); assert_eq!(result, Err(ParserResultError::NotFound)); } #[test] fn test_map_parser() { let mut reader = ParserInput::new("Test 123"); let mut parser = map_parser(read_any_quantified(3), read_any); let result = parser(&mut reader); assert_eq!(result, Ok('T')); let result = parser(&mut reader); assert_eq!(result, Ok('t')); let result = parser(&mut reader); assert_eq!(result, Err(ParserResultError::NotFound)); } #[test] fn test_consumed() { let mut reader = ParserInput::new("Test 123"); let mut parser = consumed(tuple((read_text("Te"), read_text("st")))); let result = parser(&mut reader); assert_eq!(result, Ok("Test")); } #[test] fn test_ignore_result() { let mut reader = ParserInput::new("Test 123"); let mut parser = ignore_result(tuple((read_text("Te"), read_text("st")))); let result = parser(&mut reader); assert_eq!(result, Ok(())); } #[test] fn test_value() { let mut reader = ParserInput::new("This is a test"); let mut parser = value(true); let result = parser(&mut reader); assert_eq!(result, Ok(true)); let result = parser(&mut reader); assert_eq!(result, Ok(true)); } #[test] fn test_value_dyn() { let mut reader = ParserInput::new("This is a test"); let mut parser = value_dyn(|_| true); let result = parser(&mut reader); assert_eq!(result, Ok(true)); let result = parser(&mut reader); assert_eq!(result, Ok(true)); } #[test] fn test_error() { let mut reader = ParserInput::new_with_error("This is a test"); let mut parser = error("test"); let result: ParserResult<(), &str> = parser(&mut reader); match result { Err(ParserResultError::Error((_, e))) => { assert_eq!(e, "test") } _ => unreachable!(), } } #[test] fn test_error_dyn() { let mut reader = ParserInput::new_with_error("This is a test"); let mut parser = error_dyn(|r| format!("test at {}", r.save_cursor().char_offset())); let result: ParserResult<(), String> = parser(&mut reader); match result { Err(ParserResultError::Error((_, e))) => { assert_eq!(e.as_str(), "test at 0") } _ => unreachable!(), } } #[test] fn test_ensure() { let mut reader = ParserInput::new_with_error::<&str>("This is a test"); let mut parser = ensure(read_text("Test"), |_| "test"); let result = parser(&mut reader); match result { Err(ParserResultError::Error((_, e))) => { assert_eq!(e, "test") } _ => unreachable!(), } } #[test] fn test_recover() { let mut reader = ParserInput::new_with_error::<&str>("This is a test"); let mut parser = recover(error("test1"), |_, _, _| Ok("recover")); let result = parser(&mut reader); assert_eq!(result, Ok("recover")); } }
true
5242413bd009bf183503fb77e550deae2035902c
Rust
pelian/bn-api
/db/src/test/builders/settlementtransaction_builder.rs
UTF-8
1,780
2.84375
3
[ "BSD-3-Clause" ]
permissive
use diesel::prelude::*; use prelude::*; use uuid::Uuid; pub struct SettlementtransactionBuilder<'a> { settlement_id: Option<Uuid>, event_id: Uuid, order_item_id: Option<Uuid>, settlement_status: Option<SettlementStatus>, transaction_type: Option<SettlementTransactionType>, value_in_cents: i64, comment: Option<String>, connection: &'a PgConnection, } impl<'a> SettlementtransactionBuilder<'a> { pub fn new(connection: &PgConnection) -> SettlementtransactionBuilder { SettlementtransactionBuilder { settlement_id: None, event_id: Uuid::new_v4(), order_item_id: None, settlement_status: None, transaction_type: None, value_in_cents: 100, comment: Some("test comment".to_string()), connection: connection, } } pub fn with_value_in_cents(mut self, value_in_cents: i64) -> Self { self.value_in_cents = value_in_cents; self } pub fn with_event_id(mut self, event_id: Uuid) -> Self { self.event_id = event_id; self } pub fn with_settlement_id(mut self, settlement_id: Uuid) -> Self { self.settlement_id = Some(settlement_id); self } pub fn finish(&mut self) -> SettlementTransaction { let settlement_trans = NewSettlementTransaction { settlement_id: self.settlement_id, event_id: self.event_id, order_item_id: self.order_item_id, settlement_status: self.settlement_status, transaction_type: self.transaction_type, value_in_cents: self.value_in_cents, comment: self.comment.clone(), }; settlement_trans.commit(self.connection).unwrap() } }
true
de170dcebe363de7d2c1a67007da8db8ec0891cc
Rust
owen8877/leetcode-rs
/src/problem_24.rs
UTF-8
1,436
3.21875
3
[]
no_license
use crate::listnode::*; pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut dummy = Box::new(ListNode::new(0)); dummy.next = head; let mut p = dummy.as_mut(); fn core(p: &mut ListNode) { match p.next.as_ref() { None => {}, Some(n1) => { match n1.next.as_ref() { None => {}, Some(n2) => { let mut m2 = ListNode::new(n1.val); let mut m1 = ListNode::new(n2.val); m2.next = n2.next.as_ref().cloned(); core(&mut m2); m1.next = Some(Box::new(m2)); p.next = Some(Box::new(m1)); }, } } } } core(p); dummy.next } #[test] fn test_swap_pairs() { assert_eq!(swap_pairs(arr_to_list(&[2, 1, 4, 3, 6, 5])), arr_to_list(&[1, 2, 3, 4, 5, 6])); assert_eq!(swap_pairs(arr_to_list(&[2, 1, 4, 3, 5])), arr_to_list(&[1, 2, 3, 4, 5])); assert_eq!(swap_pairs(arr_to_list(&[2, 1, 4, 3])), arr_to_list(&[1, 2, 3, 4])); assert_eq!(swap_pairs(arr_to_list(&[2, 1, 4])), arr_to_list(&[1, 2, 4])); assert_eq!(swap_pairs(arr_to_list(&[2, 1])), arr_to_list(&[1, 2])); assert_eq!(swap_pairs(arr_to_list(&[1])), arr_to_list(&[1])); assert_eq!(swap_pairs(arr_to_list(&[])), arr_to_list(&[])); }
true
9d0e021ba44eda5c905cc77721b0ecf97f892a61
Rust
CStichbury/emosaic
/src/mosaic/image.rs
UTF-8
4,008
2.9375
3
[ "MIT" ]
permissive
use std::fs::{self}; use std::io; use std::path::{Path, PathBuf}; use std::sync::mpsc::channel; use std::thread; use image::{DynamicImage, GenericImage, Pixel, RgbaImage, Rgba}; use super::color::{average_color, QuadRgba}; use crate::{Tile, TileSet}; pub fn fill_rect<T>(img: &mut T, color: &T::Pixel, rect: &(u32, u32, u32, u32)) where T: GenericImage, { let (x, y, width, height) = *rect; for y2 in y..(y + height) { for x2 in x..(x + width) { let mut pixel = img.get_pixel(x2, y2); pixel.blend(color); img.put_pixel(x2, y2, pixel); } } } fn read_dir(dir: &Path) -> io::Result<Vec<PathBuf>> { let mut paths: Vec<PathBuf> = Vec::new(); for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); paths.push(path); } Ok(paths) } pub fn read_images_in_dir(path: &Path) -> Vec<(PathBuf, RgbaImage)> { let mut images = vec![]; for path_buf in read_dir(path).unwrap() { let path = path_buf.as_path(); let img = match image::open(path) { Ok(im) => im, _ => continue, }; let img = match img { DynamicImage::ImageRgba8(im) => im as RgbaImage, DynamicImage::ImageRgb8(_) => img.to_rgba(), _ => continue, }; images.push((path_buf, img)); } images } pub fn analyse(images: Vec<(PathBuf, RgbaImage)>) -> TileSet<Rgba<u8>> { let (tx, rx) = channel(); let mut handles = vec![]; for chunk in images.chunks(500) { let tx = tx.clone(); let owned_chuck = chunk.to_owned(); let handle = thread::spawn(move || { for (path_buf, img) in owned_chuck { let colors = average_color(&img, &(0, 0, img.width(), img.height())); tx.send((path_buf, colors)).unwrap(); } }); handles.push(handle); } let num_images = images.len(); for handle in handles { handle.join().unwrap(); } let mut tile_set = TileSet::new(); for (count, (path_buf, colors)) in rx.iter().enumerate() { let tile = Tile::new(path_buf, colors); tile_set.push(tile); if count == num_images - 1 { break; } } tile_set } pub fn quad_analyse(images: Vec<(PathBuf, RgbaImage)>) -> TileSet<QuadRgba> { let (tx, rx) = channel(); let mut handles = vec![]; for chunk in images.chunks(500) { let tx = tx.clone(); let owned_chuck = chunk.to_owned(); let handle = thread::spawn(move || { for (path_buf, img) in owned_chuck { let half_width = (f64::from(img.width()) * 0.5).floor() as u32; let half_height = (f64::from(img.height()) * 0.5).floor() as u32; let rect_top_left = (0u32, 0u32, half_width, half_height); let rect_top_right = (half_width, 0u32, half_width, half_height); let rect_bottom_right = (half_width, half_height, half_width, half_height); let rect_bottom_left = (0u32, half_height, half_width, half_height); let top_left = average_color(&img, &rect_top_left); let top_right = average_color(&img, &rect_top_right); let bottom_right = average_color(&img, &rect_bottom_right); let bottom_left = average_color(&img, &rect_bottom_left); let colors: QuadRgba = [top_left, top_right, bottom_right, bottom_left]; tx.send((path_buf, colors)).unwrap(); } }); handles.push(handle); } let num_images = images.len(); for handle in handles { handle.join().unwrap(); } let mut tile_set = TileSet::new(); for (count, (path_buf, colors)) in rx.iter().enumerate() { let tile = Tile::new(path_buf, colors); tile_set.push(tile); if count == num_images - 1 { break; } } tile_set }
true
2d7e819f928114e32be3e036a0092ce4fc767276
Rust
serbe/anet
/src/future.rs
UTF-8
647
2.796875
3
[ "MIT" ]
permissive
use super::interval::Interval; use futures::prelude::*; pub struct IntervalFuture { interval: Interval, last: usize, } impl IntervalFuture { pub fn new(interval: Interval) -> IntervalFuture { let last = interval.get_counter(); IntervalFuture { interval, last } } } impl Future for IntervalFuture { type Item = usize; type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let curr = self.interval.get_counter(); if curr == self.last { Ok(Async::NotReady) } else { self.last = curr; Ok(Async::Ready(curr)) } } }
true
89d95e09f55b7bfdf94d9ec5778bda870de95851
Rust
marco-c/gecko-dev-comments-removed
/third_party/rust/bytes/src/buf/buf_mut.rs
UTF-8
15,631
2.703125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use crate::buf::{limit, Chain, Limit, UninitSlice}; #[cfg(feature = "std")] use crate::buf::{writer, Writer}; use core::{cmp, mem, ptr, usize}; use alloc::{boxed::Box, vec::Vec}; pub unsafe trait BufMut { fn remaining_mut(&self) -> usize; unsafe fn advance_mut(&mut self, cnt: usize); fn has_remaining_mut(&self) -> bool { self.remaining_mut() > 0 } #[cfg_attr(docsrs, doc(alias = "bytes_mut"))] fn chunk_mut(&mut self) -> &mut UninitSlice; fn put<T: super::Buf>(&mut self, mut src: T) where Self: Sized, { assert!(self.remaining_mut() >= src.remaining()); while src.has_remaining() { let l; unsafe { let s = src.chunk(); let d = self.chunk_mut(); l = cmp::min(s.len(), d.len()); ptr::copy_nonoverlapping(s.as_ptr(), d.as_mut_ptr() as *mut u8, l); } src.advance(l); unsafe { self.advance_mut(l); } } } fn put_slice(&mut self, src: &[u8]) { let mut off = 0; assert!( self.remaining_mut() >= src.len(), "buffer overflow; remaining = {}; src = {}", self.remaining_mut(), src.len() ); while off < src.len() { let cnt; unsafe { let dst = self.chunk_mut(); cnt = cmp::min(dst.len(), src.len() - off); ptr::copy_nonoverlapping(src[off..].as_ptr(), dst.as_mut_ptr() as *mut u8, cnt); off += cnt; } unsafe { self.advance_mut(cnt); } } } fn put_bytes(&mut self, val: u8, cnt: usize) { for _ in 0..cnt { self.put_u8(val); } } fn put_u8(&mut self, n: u8) { let src = [n]; self.put_slice(&src); } fn put_i8(&mut self, n: i8) { let src = [n as u8]; self.put_slice(&src) } fn put_u16(&mut self, n: u16) { self.put_slice(&n.to_be_bytes()) } fn put_u16_le(&mut self, n: u16) { self.put_slice(&n.to_le_bytes()) } fn put_u16_ne(&mut self, n: u16) { self.put_slice(&n.to_ne_bytes()) } fn put_i16(&mut self, n: i16) { self.put_slice(&n.to_be_bytes()) } fn put_i16_le(&mut self, n: i16) { self.put_slice(&n.to_le_bytes()) } fn put_i16_ne(&mut self, n: i16) { self.put_slice(&n.to_ne_bytes()) } fn put_u32(&mut self, n: u32) { self.put_slice(&n.to_be_bytes()) } fn put_u32_le(&mut self, n: u32) { self.put_slice(&n.to_le_bytes()) } fn put_u32_ne(&mut self, n: u32) { self.put_slice(&n.to_ne_bytes()) } fn put_i32(&mut self, n: i32) { self.put_slice(&n.to_be_bytes()) } fn put_i32_le(&mut self, n: i32) { self.put_slice(&n.to_le_bytes()) } fn put_i32_ne(&mut self, n: i32) { self.put_slice(&n.to_ne_bytes()) } fn put_u64(&mut self, n: u64) { self.put_slice(&n.to_be_bytes()) } fn put_u64_le(&mut self, n: u64) { self.put_slice(&n.to_le_bytes()) } fn put_u64_ne(&mut self, n: u64) { self.put_slice(&n.to_ne_bytes()) } fn put_i64(&mut self, n: i64) { self.put_slice(&n.to_be_bytes()) } fn put_i64_le(&mut self, n: i64) { self.put_slice(&n.to_le_bytes()) } fn put_i64_ne(&mut self, n: i64) { self.put_slice(&n.to_ne_bytes()) } fn put_u128(&mut self, n: u128) { self.put_slice(&n.to_be_bytes()) } fn put_u128_le(&mut self, n: u128) { self.put_slice(&n.to_le_bytes()) } fn put_u128_ne(&mut self, n: u128) { self.put_slice(&n.to_ne_bytes()) } fn put_i128(&mut self, n: i128) { self.put_slice(&n.to_be_bytes()) } fn put_i128_le(&mut self, n: i128) { self.put_slice(&n.to_le_bytes()) } fn put_i128_ne(&mut self, n: i128) { self.put_slice(&n.to_ne_bytes()) } fn put_uint(&mut self, n: u64, nbytes: usize) { self.put_slice(&n.to_be_bytes()[mem::size_of_val(&n) - nbytes..]); } fn put_uint_le(&mut self, n: u64, nbytes: usize) { self.put_slice(&n.to_le_bytes()[0..nbytes]); } fn put_uint_ne(&mut self, n: u64, nbytes: usize) { if cfg!(target_endian = "big") { self.put_uint(n, nbytes) } else { self.put_uint_le(n, nbytes) } } fn put_int(&mut self, n: i64, nbytes: usize) { self.put_slice(&n.to_be_bytes()[mem::size_of_val(&n) - nbytes..]); } fn put_int_le(&mut self, n: i64, nbytes: usize) { self.put_slice(&n.to_le_bytes()[0..nbytes]); } fn put_int_ne(&mut self, n: i64, nbytes: usize) { if cfg!(target_endian = "big") { self.put_int(n, nbytes) } else { self.put_int_le(n, nbytes) } } fn put_f32(&mut self, n: f32) { self.put_u32(n.to_bits()); } fn put_f32_le(&mut self, n: f32) { self.put_u32_le(n.to_bits()); } fn put_f32_ne(&mut self, n: f32) { self.put_u32_ne(n.to_bits()); } fn put_f64(&mut self, n: f64) { self.put_u64(n.to_bits()); } fn put_f64_le(&mut self, n: f64) { self.put_u64_le(n.to_bits()); } fn put_f64_ne(&mut self, n: f64) { self.put_u64_ne(n.to_bits()); } fn limit(self, limit: usize) -> Limit<Self> where Self: Sized, { limit::new(self, limit) } #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] fn writer(self) -> Writer<Self> where Self: Sized, { writer::new(self) } fn chain_mut<U: BufMut>(self, next: U) -> Chain<Self, U> where Self: Sized, { Chain::new(self, next) } } macro_rules! deref_forward_bufmut { () => { fn remaining_mut(&self) -> usize { (**self).remaining_mut() } fn chunk_mut(&mut self) -> &mut UninitSlice { (**self).chunk_mut() } unsafe fn advance_mut(&mut self, cnt: usize) { (**self).advance_mut(cnt) } fn put_slice(&mut self, src: &[u8]) { (**self).put_slice(src) } fn put_u8(&mut self, n: u8) { (**self).put_u8(n) } fn put_i8(&mut self, n: i8) { (**self).put_i8(n) } fn put_u16(&mut self, n: u16) { (**self).put_u16(n) } fn put_u16_le(&mut self, n: u16) { (**self).put_u16_le(n) } fn put_u16_ne(&mut self, n: u16) { (**self).put_u16_ne(n) } fn put_i16(&mut self, n: i16) { (**self).put_i16(n) } fn put_i16_le(&mut self, n: i16) { (**self).put_i16_le(n) } fn put_i16_ne(&mut self, n: i16) { (**self).put_i16_ne(n) } fn put_u32(&mut self, n: u32) { (**self).put_u32(n) } fn put_u32_le(&mut self, n: u32) { (**self).put_u32_le(n) } fn put_u32_ne(&mut self, n: u32) { (**self).put_u32_ne(n) } fn put_i32(&mut self, n: i32) { (**self).put_i32(n) } fn put_i32_le(&mut self, n: i32) { (**self).put_i32_le(n) } fn put_i32_ne(&mut self, n: i32) { (**self).put_i32_ne(n) } fn put_u64(&mut self, n: u64) { (**self).put_u64(n) } fn put_u64_le(&mut self, n: u64) { (**self).put_u64_le(n) } fn put_u64_ne(&mut self, n: u64) { (**self).put_u64_ne(n) } fn put_i64(&mut self, n: i64) { (**self).put_i64(n) } fn put_i64_le(&mut self, n: i64) { (**self).put_i64_le(n) } fn put_i64_ne(&mut self, n: i64) { (**self).put_i64_ne(n) } }; } unsafe impl<T: BufMut + ?Sized> BufMut for &mut T { deref_forward_bufmut!(); } unsafe impl<T: BufMut + ?Sized> BufMut for Box<T> { deref_forward_bufmut!(); } unsafe impl BufMut for &mut [u8] { #[inline] fn remaining_mut(&self) -> usize { self.len() } #[inline] fn chunk_mut(&mut self) -> &mut UninitSlice { unsafe { &mut *(*self as *mut [u8] as *mut _) } } #[inline] unsafe fn advance_mut(&mut self, cnt: usize) { let (_, b) = core::mem::replace(self, &mut []).split_at_mut(cnt); *self = b; } #[inline] fn put_slice(&mut self, src: &[u8]) { self[..src.len()].copy_from_slice(src); unsafe { self.advance_mut(src.len()); } } fn put_bytes(&mut self, val: u8, cnt: usize) { assert!(self.remaining_mut() >= cnt); unsafe { ptr::write_bytes(self.as_mut_ptr(), val, cnt); self.advance_mut(cnt); } } } unsafe impl BufMut for Vec<u8> { #[inline] fn remaining_mut(&self) -> usize { core::isize::MAX as usize - self.len() } #[inline] unsafe fn advance_mut(&mut self, cnt: usize) { let len = self.len(); let remaining = self.capacity() - len; assert!( cnt <= remaining, "cannot advance past `remaining_mut`: {:?} <= {:?}", cnt, remaining ); self.set_len(len + cnt); } #[inline] fn chunk_mut(&mut self) -> &mut UninitSlice { if self.capacity() == self.len() { self.reserve(64); } let cap = self.capacity(); let len = self.len(); let ptr = self.as_mut_ptr(); unsafe { &mut UninitSlice::from_raw_parts_mut(ptr, cap)[len..] } } fn put<T: super::Buf>(&mut self, mut src: T) where Self: Sized, { self.reserve(src.remaining()); while src.has_remaining() { let l; { let s = src.chunk(); l = s.len(); self.extend_from_slice(s); } src.advance(l); } } #[inline] fn put_slice(&mut self, src: &[u8]) { self.extend_from_slice(src); } fn put_bytes(&mut self, val: u8, cnt: usize) { let new_len = self.len().checked_add(cnt).unwrap(); self.resize(new_len, val); } } fn _assert_trait_object(_b: &dyn BufMut) {}
true
904d5932a7c2483ee4d82986d7094e8dc8fb28f6
Rust
mishazawa/monorap
/minifb_utils/src/primitives/mod.rs
UTF-8
3,699
2.9375
3
[]
no_license
use crate::color::Color; use crate::renderer::{Processing, Renderer, ShapeMode}; use crate::util; pub fn dot(renderer: &mut Renderer, x0: i32, y0: i32) -> () { let (x, y) = renderer.apply_translation(x0, y0); match util::coords_to_index(x, y, renderer.width, renderer.height) { Some(index) => { renderer.buffer[index] = renderer.stroke_color; } None => (), } } pub fn line(renderer: &mut Renderer, mut x0: i32, mut y0: i32, mut x1: i32, mut y1: i32) { let color = Color::from(renderer.stroke_color); let steep = (y1 - y0).abs() > (x1 - x0).abs(); let mut temp; if steep { temp = x0; x0 = y0; y0 = temp; temp = x1; x1 = y1; y1 = temp; } if x0 > x1 { temp = x0; x0 = x1; x1 = temp; temp = y0; y0 = y1; y1 = temp; } let from = (x0, y0); let to = (x1, y1); let dx = (to.0 - from.0) as f32; let dy = (to.1 - from.1) as f32; let gradient = match dx { dx if dx == 0.0 => 1., _ => dy / dx, }; let x_pixel_1 = from.0; let x_pixel_2 = to.0; let mut intersect_y = from.1 as f32; for x in x_pixel_1..x_pixel_2 { let (dot_x, dot_y) = match steep { true => (intersect_y.round() as i32, x), false => (x, intersect_y.round() as i32), }; renderer.stroke(Color::from([ color.r, color.g, color.b, (color.a as f32 * (1. - intersect_y.fract())) as u8, ])); dot(renderer, dot_x, dot_y); // TODO: fix proper brightness // renderer.stroke(Color::from([ // color.r, // color.g, // color.b, // (color.a as f32 * intersect_y.fract()) as u8 // ])); // dot(renderer, dot_x - 1, dot_y); intersect_y += gradient; } renderer.stroke(color); } pub fn background(renderer: &mut Renderer, color: Color) -> () { for pixel in renderer.buffer.iter_mut() { *pixel = color.hex; } } pub fn rect(renderer: &mut Renderer, x: i32, y: i32, w: i32, h: i32) { quad(renderer, x, y, x + w, y, x + w, y + h, x, y + h); } fn quad( renderer: &mut Renderer, x1: i32, y1: i32, x2: i32, y2: i32, x3: i32, y3: i32, x4: i32, y4: i32, ) -> () { renderer.begin_shape(renderer.shape_type.clone()); renderer.vertex(x1, y1); renderer.vertex(x2, y2); renderer.vertex(x3, y3); renderer.vertex(x4, y4); renderer.end_shape(); } pub fn draw_shape(renderer: &mut Renderer) -> () { let shape = renderer.shape_to_draw.clone(); for (i, _) in shape.iter().enumerate().step_by(2) { let begin_x = shape.get(i); let begin_y = shape.get(i + 1); let end_x = shape.get(i + 2); let end_y = shape.get(i + 3); match (begin_x, begin_y, end_x, end_y) { (Some(a), Some(b), Some(c), Some(d)) => match renderer.shape_type { ShapeMode::POINTS => { dot(renderer, *a, *b); } ShapeMode::LINES => { line(renderer, *a, *b, *c, *d); } }, (Some(a), Some(b), None, None) => match renderer.shape_type { ShapeMode::POINTS => { dot(renderer, *a, *b); } ShapeMode::LINES => { line(renderer, *a, *b, shape[0], shape[1]); } }, _ => { println!("Wrong shape: {:?}", shape); } } } renderer.shape_to_draw.clear(); }
true
28f1d10cdf3b87248bfb517ff434abbe559a0032
Rust
tiffany352/wasm-rs
/src/reader/names.rs
UTF-8
1,443
3.109375
3
[ "Apache-2.0", "MIT" ]
permissive
use super::*; use std::str::from_utf8; pub struct NameSection<'a> { pub count: u32, pub entries_raw: &'a [u8], } pub struct NameEntryIterator<'a> { count: u32, local_count: u32, iter: &'a [u8] } pub enum NameEntry<'a> { Function(&'a str), Local(&'a str), } impl<'a> NameSection<'a> { pub fn entries(&self) -> NameEntryIterator<'a> { NameEntryIterator { count: self.count, local_count: 0, iter: self.entries_raw } } } impl<'a> Iterator for NameEntryIterator<'a> { type Item = Result<NameEntry<'a>, Error>; fn next(&mut self) -> Option<Self::Item> { if self.count == 0 && self.local_count == 0 { return None } if self.local_count > 0 { self.local_count -= 1; let len = try_opt!(read_varuint(&mut self.iter)) as usize; let name = &self.iter[..len]; self.iter = &self.iter[len..]; let name = try_opt!(from_utf8(name)); return Some(Ok(NameEntry::Local(name))) } self.count -= 1; let len = try_opt!(read_varuint(&mut self.iter)) as usize; let name = &self.iter[..len]; self.iter = &self.iter[len..]; let name = try_opt!(from_utf8(name)); let count = try_opt!(read_varuint(&mut self.iter)) as u32; self.local_count = count; Some(Ok(NameEntry::Function(name))) } }
true
d2e9e070a781514e700c523f41f226143ff772eb
Rust
ericrobolson/Archived_Tremor
/v1/portia_client_server/src/lib.rs
UTF-8
1,592
3.0625
3
[ "MIT" ]
permissive
mod ecs; mod math{ pub use game_math::f32::*; } pub enum MultiplayerMode{ DeterministicRollback, ClientServer } pub type ClientId = u32; pub struct Server { clients: Vec<Client>, max_outgoing_packet_bytes: usize, max_clients: u32, outbound_tick_rate: u32, } impl Server { pub fn main_loop(&mut self) { loop { // Receive network messages self.inbound_network(); // Handle network messages self.tick(); // Send network messages self.outbound_network(); } } pub fn inbound_network(&mut self) { println!("Receive network messages"); } pub fn outbound_network(&mut self) { for client in &self.clients { // Calculate visible entities // Calculate updates // build message // send message } println!("Send network messages"); } pub fn tick(&mut self) { println!("Server tick."); } } pub struct Client { address: Address, max_packet_bytes: usize, outbound_tick_rate: u32, } pub struct Address {} #[cfg(test)] mod tests { macro_rules! count_items{ ($name:ident) => {1}; ($first:ident, $($rest:ident),*) => { 1 + count_items!($($rest),*) } } #[test] fn it_works() { const X: usize = count_items!(a); const Y: usize = count_items!(a, b); const Z: usize = count_items!(a, b, c); assert_eq!(1, X); assert_eq!(2, Y); assert_eq!(3, Z); } }
true
aa685d850694ed7794d5c2154f0f3744b0138a64
Rust
CodeSteak/hs_app
/hs_crawler/src/crawler/canteen_plan.rs
UTF-8
3,080
2.5625
3
[ "MIT" ]
permissive
use super::*; use crate::util::*; use std::io; use std::io::Read; use std::collections::HashMap; use select::document::Document; use select::predicate::*; use chrono::{Date, Local}; use reqwest; type CanteenPlan = HashMap<Date<Local>, Vec<String>>; const URL_THIS_WEEK: &str = "https://www.swfr.de/essen-trinken/speiseplaene/mensa-offenburg/"; //const URL_NEXT_WEEK : &str = "https://www.swfr.de/essen-trinken/speiseplaene/mensa-offenburg/?tx_swfrspeiseplan_pi1[weekToShow]=1"; use std::sync::mpsc::Receiver; pub fn get_async(q: Query) -> Receiver<Result<CanteenPlan, String>> { dirty_err_async(move || get(q)) } #[derive(PartialEq, Copy, Clone, Debug)] pub enum Query { ThisWeek, NextWeek, } fn get_url_next_week() -> Result<String, DirtyError> { let res = reqwest::blocking::get(URL_THIS_WEEK)?; if res.status() != 200 { return Err(io::Error::new(io::ErrorKind::InvalidData, "Didn't get course table.").into()); } let mut html = String::new(); res.take(MAX_RESPONSE_SIZE).read_to_string(&mut html)?; let dom = Document::from(&*html); let menu_url = dom.find(And(Class("next-week"), Class("text-right"))) .next().unwrap() // todo .attr("href").unwrap() .to_owned(); Ok(format!("https://www.swfr.de{}", menu_url)) } pub fn get(q: Query) -> Result<CanteenPlan, DirtyError> { let res = match q { Query::ThisWeek => reqwest::blocking::get(URL_THIS_WEEK)?, Query::NextWeek => reqwest::blocking::get(&get_url_next_week()?)?, }; if res.status() != 200 { return Err(io::Error::new(io::ErrorKind::InvalidData, "Didn't get course table.").into()); } let mut html = String::new(); res.take(MAX_RESPONSE_SIZE).read_to_string(&mut html)?; // Strange workaround. html = html.replace("<br>", "\n"); let dom = Document::from(&*html); let mut date = last_monday_or_next_monday_on_sundays(); if q == Query::NextWeek { for _ in 0..7 { date = date.succ(); } } let menu_plan = dom .find(Class("tab-content")) .flat_map(|maybe_plan| { maybe_plan.find(Class("menu-tagesplan")).map(|day_node| { day_node .find(Class("menu-info")) .map(|menu| { menu.text() .ihh_fix() .lines() .map(|s| s.trim()) .filter(|s| !s.is_empty()) .filter(|l| !l.starts_with("enthält Allergene")) .filter(|l| !l.starts_with("Kennzeichnungen")) .fold(String::new(), |a, b| a + "\n" + &b) }).collect::<Vec<String>>() }) }).collect::<Vec<Vec<String>>>(); let daily_menu_plan: CanteenPlan = menu_plan .into_iter() .map(|d| { let ret = (date.clone(), d); date = date.succ(); ret }).collect(); Ok(daily_menu_plan) }
true
b6d86a4f12b56bb0f04cc8768dba7b8eedf02ceb
Rust
drueck/advent-of-code-2020
/day-07/src/main.rs
UTF-8
1,799
3.40625
3
[]
no_license
// Advent of Code 2020: Day 7 // // We have a list of rules for bags at the airport, specifically a list // of bag types that must contain a specific number of other bag types. // Our challenge for part 1 is to find the number of bags that could // contain a shiny gold bag. Some bags will contain it directly, and other // bags will contain a bag that contains a shiny gold bag. For our test // input the answer is 4, because a shiny gold bag could be contained // directly or nested in a bright white, muted yellow, dark orange, or // light red bag. // // Part 2: // // For part two we are curious how many bags would have to be inside our // shiny gold bag. Sooooo many. // // Usage cargo run <input-file> use std::{env, fs::File, io::BufRead, io::BufReader}; mod bags; use crate::bags::{Bag, BagRules}; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { println!("Usage: cargo run <input-file>"); return; } let input_file = &args[1]; let file = File::open(input_file).expect("no such file"); let buf = BufReader::new(file); let lines: Vec<String> = buf .lines() .map(|l| l.expect("could not parse line")) .collect(); let mut bag_rules = BagRules::new(); for line in lines { bag_rules.add_rule(&line); } let shiny_gold_bag = Bag::new("shiny gold"); let bags_containing_shiny_gold = bag_rules.bags_that_could_contain(&shiny_gold_bag).len(); let bags_inside_shiny_gold = bag_rules.num_bags_inside(&shiny_gold_bag); println!( "The number of bags that could contain a shiny gold bag is: {}", bags_containing_shiny_gold ); println!( "The number of bags inside a shiny gold bag is: {}", bags_inside_shiny_gold ); }
true
ab5666a45ad8e4e12f36be77e7c9a2ea74d85e4b
Rust
thomcc/startup
/testcases/dylib_runner/main.rs
UTF-8
1,555
2.53125
3
[ "Apache-2.0", "MIT", "Zlib" ]
permissive
fn main() { let mut args = std::env::args().skip(1); let path: std::path::PathBuf = args.next().expect("expected target path").into(); let name = args.next().expect("expected lib name"); let sofile = path.join(format!("lib{}.so", name)); let dll = path.join(format!("{}.dll", name)); let dylib = path.join(format!("lib{}.dylib", name)); let file: std::path::PathBuf = if sofile.exists() { sofile } else if dll.exists() { dll } else if dylib.exists() { dylib } else { panic!( "couldnt find a dylib like {:?}, {:?}, or {:?}", sofile, dll, dylib ); }; let r = maybe_catch_unwind(name == "paniclib", || { let lib = libloading::Library::new(&file).unwrap_or_else(|e| { panic!("loading {:?} failed: {:?}", file, e); }); unsafe { let func: libloading::Symbol<unsafe extern "C" fn() -> bool> = lib.get(b"startup_testcase\0").unwrap_or_else(|e| { panic!("couldn't find symbol: {:?} in {:?}", e, file); }); assert!(func()); } lib.close().unwrap_or_else(|e| { panic!("dlclose failed for {:?}: {:?}", file, e); }); }); if r.is_err() { std::process::exit(99); } } fn maybe_catch_unwind(want_catch: bool, f: impl FnOnce()) -> std::thread::Result<()> { if want_catch { std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) } else { f(); Ok(()) } }
true
6ab0ecfc441d11fe121d62ffcbe01cf94ddd7afb
Rust
sector-f/dose-rs
/dose-types/examples/serialize.rs
UTF-8
1,712
2.640625
3
[]
no_license
extern crate serde_json; extern crate dose_types; use dose_types::*; use std::path::PathBuf; fn main() { // Requests let add_request = Request::Add { url: String::from("http://www.example.com"), path: PathBuf::from("/path/to/file") }; println!("Add request:\n{}\n", serde_json::to_string(&add_request).unwrap()); let cancel_request = Request::Cancel { id: 0 }; println!("Cancel request:\n{}\n", serde_json::to_string(&cancel_request).unwrap()); let dl_status_request = Request::DlStatus { id: 0 }; println!("Download status request:\n{}\n", serde_json::to_string(&dl_status_request).unwrap()); let server_status_request = Request::ServerStatus; println!("Server status request:\n{}\n", serde_json::to_string(&server_status_request).unwrap()); // Responses let dlr1 = DlResponse { id: 0, url: String::from("http://www.example.com/foo.jpg"), path: PathBuf::from("/path/to/foo.jpg"), bytes_read: 510, bytes_total: Some(1024), }; let dlr2 = DlResponse { id: 1, url: String::from("http://www.example.com/bar.jpg"), path: PathBuf::from("/path/to/bar.jpg"), bytes_read: 5, bytes_total: Some(10000), }; let status_response = Response::DlStatus(dlr1.clone()); println!("Download status response:\n{}\n", serde_json::to_string(&status_response).unwrap()); let server_status = Response::ServerStatus(vec![dlr1, dlr2]); println!("Server status response:\n{}\n", serde_json::to_string(&server_status).unwrap()); let error = Response::Error(String::from("404 file not found")); println!("Error response:\n{}", serde_json::to_string(&error).unwrap()); }
true
8577c9f380517be083cf87dce1be3be6e140a50d
Rust
66Origin/nitox
/src/protocol/mod.rs
UTF-8
1,887
3.1875
3
[ "MIT", "Apache-2.0" ]
permissive
use bytes::Bytes; /// Trait used to implement a common interface for implementing new commands pub trait Command { /// Command name as a static byte slice const CMD_NAME: &'static [u8]; /// Encodes the command into bytes fn into_vec(self) -> Result<Bytes, CommandError>; /// Tries to parse a buffer into a command fn try_parse(buf: &[u8]) -> Result<Self, CommandError> where Self: Sized; } pub(crate) fn check_command_arg(s: &str) -> Result<(), ArgumentValidationError> { if s.contains(' ') { return Err(ArgumentValidationError::ContainsSpace); } else if s.contains('\t') { return Err(ArgumentValidationError::ContainsTab); } Ok(()) } macro_rules! check_cmd_arg { ($val:ident, $part:expr) => { use protocol::{check_command_arg, ArgumentValidationError}; match check_command_arg($val) { Ok(_) => {} Err(ArgumentValidationError::ContainsSpace) => { return Err(format!("{} contains spaces", $part).into()); } Err(ArgumentValidationError::ContainsTab) => { return Err(format!("{} contains tabs", $part).into()); } } }; } mod error; pub use self::error::*; mod client; mod server; mod op; pub use self::op::*; pub mod commands { pub use super::{ client::{connect::*, pub_cmd::*, sub_cmd::*, unsub_cmd::*}, server::{info::*, message::*, server_error::ServerError}, }; pub use Command; } #[cfg(test)] mod tests { use super::check_command_arg; #[test] #[should_panic] fn it_detects_spaces() { check_command_arg(&"foo bar").unwrap() } #[test] #[should_panic] fn it_detects_tabs() { check_command_arg(&"foo\tbar").unwrap() } #[test] fn it_works() { check_command_arg(&"foo.bar").unwrap() } }
true
712ca1425dd183eed2a97093ad0ccd4290ae9b6c
Rust
maxastyler/Spirograph
/src/main.rs
UTF-8
2,877
2.8125
3
[]
no_license
extern crate image; use std::fs::File; use std::f64::consts::*; // let img = spiro_image((2000, 2000), linspace(-2., 2., 20), path_points(100000), &path, &gen_envelope); // Some path that takes t from 0 -> 1 and should close on itself fn path(t: f64) -> (f64, f64) { let theta = 2.*PI*t; let r = 500.*(1.-theta.cos()*(3.*theta).sin()); (r*theta.cos(), r*theta.sin()) } fn spiral_path(t: f64) -> (f64, f64) { let theta = 4.*PI*t; let r = 250.*(2.+(theta/2.).sin()*theta.cos()); (r*theta.cos(), r*theta.sin()) } fn normal(f: &Fn(f64) -> (f64, f64), dx: f64, t: f64) -> (f64, f64) { let x1 = f(t-(dx/2.)); let x2 = f(t+(dx/2.)); let diff = (x2.0 - x1.0, x2.1 - x1.1); let mag_diff = (diff.0.powf(2.) + diff.1.powf(2.)).sqrt(); (diff.0/mag_diff, -diff.1/mag_diff) } fn envelope(t: f64) -> f64 { (2.*PI*t).cos()*100.+(4.*PI*t).sin()*50. } // Put in a height from -1 -> 1 fn gen_envelope(h: f64) -> Box<Fn(f64) -> f64> { Box::new( move |t: f64| (2.*PI*t).cos()*100.+(4.*PI*t).sin()*50.*h ) } fn double_envelope(h: f64) -> Box<Fn(f64) -> f64> { Box::new( move |t: f64| (2.*PI*t).cos()*600.+(4.*PI*t).sin()*50.*h ) } fn envelope_path<'a>(path: &'a Fn(f64) -> (f64, f64), envelope: Box<Fn(f64) -> f64 + 'a>) -> Box<Fn(f64) -> (f64, f64) + 'a> { let a = move |t: f64| { let base_p = path(t); let norm = normal(path, 0.001, t); let e = envelope(t); (base_p.0 + norm.0*e, base_p.1 + norm.1*e) }; Box::new(a) } fn linspace(a: f64, b: f64, n: u32) -> Vec<f64>{ (0..n).map(|x| { let xf = (x as f64)/(n as f64 -1.) ; a+(b-a)*xf } ).collect() } fn spiro_image(img_res: (u32, u32), path_spread: Vec<f64>, path_points: Vec<f64>, path: & Fn(f64) -> (f64, f64), envelope_generator: &Fn(f64) -> Box<Fn(f64) -> f64>) -> image::ImageBuffer<image::Luma<u8>, std::vec::Vec<u8>> { let mut imgbuf = image::ImageBuffer::new(img_res.0, img_res.1); for s in path_spread.iter() { let env_path = envelope_path(path, envelope_generator(*s)); for t in path_points.iter() { let (mut xf, mut yf) = env_path(*t); xf+=img_res.0 as f64 / 2.0; yf+=img_res.1 as f64 / 2.0; let (x, y) = (xf.round() as u32, yf.round() as u32); if (x<img_res.0) & (y<img_res.1) { let pix = imgbuf.get_pixel_mut(x, y); *pix = image::Luma([255 as u8]); } } } imgbuf } fn path_points(r: u32) -> Vec<f64> { (0..r).map(|i| (i as f64) / (r as f64 - 1.0)).collect() } fn main() { let fout = &mut File::create("double.png").unwrap(); let img = spiro_image((2000, 2000), linspace(-1., 1., 20), path_points(100000), &spiral_path, &gen_envelope); image::ImageLuma8(img).save(fout, image::PNG).unwrap(); }
true
68009e0563d1afe531a5d2e315ec66f9c8236879
Rust
VictorKoenders/pixelflut
/src/mode/async_std.rs
UTF-8
2,271
2.625
3
[]
no_license
use crate::{ client::ClientState, screen::{Screen, ScreenUpdater}, }; use async_std::{ io::{ReadExt, WriteExt}, net::{TcpListener, TcpStream}, }; pub fn start(args: crate::Args, screen: impl Screen, updater: Option<impl ScreenUpdater>) { if let Some(count) = args.core_count { // ASYNC_STD_THREAD_COUNT: The number of threads that the async-std runtime will start. // By default, this is one per logical cpu as reported by the num_cpus crate, which may be different than the number of physical cpus. // Async-std will panic if this is set to any value other than a positive integer. std::env::set_var("ASYNC_STD_THREAD_COUNT", count.to_string()); } let run = move || { async_std::task::block_on(async move { let listener = TcpListener::bind((args.host.as_str(), args.port)) .await .expect("Could not listen on host"); println!("Listening on {:?}", listener.local_addr().unwrap()); while screen.running() { let (client, _addr) = listener .accept() .await .expect("Could not accept new client"); async_std::task::spawn(run_client(client, screen.clone())); } }) }; // if we have an updater, run async_std on a background thread if let Some(mut updater) = updater { println!("Updater detected, running async_std in background thread"); std::thread::spawn(run); while updater.running() { updater.update(); } } else { run(); } } async fn run_client(mut client: TcpStream, screen: impl Screen) { let mut state = ClientState::default(); while let Ok(len) = client.read(state.recv_buffer()).await { if len == 0 { break; } let response = state.parse_buffer(&screen, len); if let Some(response) = response { let bytes = response.as_bytes(); if client.write_all(&bytes).await.is_err() { break; } } if !screen.running() { let _ = client.write_all(b"\r\nServer shutting down\r\n").await; break; } } }
true
2986f11e85be20ef683b3cddbb0b286a6d611e7c
Rust
wibbe/tiny-rts
/src/main.rs
UTF-8
2,855
2.6875
3
[ "MIT" ]
permissive
// Make sure we don't open a console window if we are building on windows and in release mode #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] extern crate tiny; mod cmd; mod game; use tiny::*; use tiny::default_font; use tiny::palette::dawn_bringer as pal; use std::rc::{Rc}; struct App { game: Rc<game::Game>, cmd: Rc<cmd::Cmd>, font: Font, show_console: bool, mouse_pos: (u32, u32), show_performance: cmd::Var, } impl Application for App { fn new(ctx: &mut tiny::Context) -> Result<App, String> { ctx.set_palette(pal::create_palette()); let font = default_font::font_4x10(); // Create command let mut cmd = Rc::new(cmd::Cmd::new(cmd::Config { font: font.clone(), background_color: pal::VALHALLA, foreground_color: pal::WHITE, cursor_color: pal::CORNFLOWER, lines: 10 })); cmd.echo("Welcome to Tiny RTS".to_string()); let mut game = Rc::new(game::Game::new(cmd.clone())); //let show_profiling = cmd.register_var("show-profiling", 0).unwrap(); Ok(App { game: game, cmd: cmd.clone(), font: font, show_console: false, mouse_pos: (0, 0), show_performance: cmd.register_var("show-performance", 0).unwrap(), }) } fn step(&mut self, ctx: &tiny::Context) -> bool { self.mouse_pos = ctx.mouse_position(); self.cmd.step(ctx); if ctx.mouse_pressed(tiny::Mouse::Left) { println!("Left Mouse Clicked"); } if ctx.key_pressed(tiny::Key::Tab) { self.show_console = !self.show_console; } !ctx.key_down(tiny::Key::Escape) } fn paint(&self, ctx: &tiny::Context, painter: &tiny::Painter) { painter.clear(pal::BLACK); let names = pal::names(); let bw = 80; let bh = 25; let mut x = 0; let mut y = 0; for color in 1..33 { let r = Rect::new_size(x, y, bw, bh); let txt = self.font.measure(&names[color]); painter.clip(Some(r)); painter.rect_fill(r, color as u8); let text_color = if color as u8 == pal::WHITE { pal::BLACK } else { pal::WHITE }; let txt_x = r.width() / 2 - txt.width() / 2; let txt_y = r.height() / 2 - txt.height() / 2; painter.text(r.left + txt_x, r.top + txt_y, &names[color], text_color, &self.font); x += bw; if x >= 320 { x = 0; y += bh; } } if self.show_performance.get_bool() { ctx.draw_timing(painter, &self.font, pal::VALHALLA, pal::WHITE); } if self.show_console { self.cmd.paint(painter); } } } fn main() { if let Err(err) = tiny::run::<App>("Tiny RTS", 320, 200, 3) { println!("Error: {}", err); } }
true
92fc976b9b9d6a0ddd127d872253d860dbba2da6
Rust
RustUser/Rust-Switch
/src/main.rs
UTF-8
650
3.53125
4
[]
no_license
mod switch; use switch::*; #[derive(Debug)] struct Point { x: i32, y: i32, } impl Point { fn new(x: i32, y: i32) -> Point { return Point { x, y, }; } } fn main() { let array: [i32; 4] = [5, 4, 3, 2]; let mut output: Vec<Point> = Vec::new(); let mut switch = switch::Switch::new(); for i in 0..array.len() { if switch.get() { output.push(Point::new(array[i - 1], array[i])); } } println!("We took an input (a one dimensional array of integers) of: {:?}.", array); println!("And turned it into an array of points: {:?}.", output); }
true
6796738fedadda3070097f8f7aed6d33565a3efd
Rust
Maaarcocr/TWiS
/src/client.rs
UTF-8
1,140
2.875
3
[]
no_license
use hyper::header::Headers; use hyper::Result; use hyper::client::{Client, Response}; use hyper::net::HttpsConnector; use hyper_native_tls::NativeTlsClient; header!{ (Authorization, "Authorization") => [String] } header!{ (UserAgent, "User-Agent") => [String] } #[derive(Debug)] pub struct Github { client: Client, headers: Headers } fn get_start_headers() -> Headers { let user_agent = UserAgent("GitHub-rs".to_owned()); let mut headers = Headers::new(); headers.set(user_agent); headers } impl Github { pub fn new() -> Github { let ssl = NativeTlsClient::new().unwrap(); let connector = HttpsConnector::new(ssl); let client = Client::with_connector(connector); Github{client: client, headers: get_start_headers()} } pub fn add_auth(mut self, token: String) -> Github { let token_string = format!("token {}", token); let auth = Authorization(token_string); self.headers.set(auth); self } pub fn make_request(&self, url: &str) -> Result<Response> { self.client.get(url).headers(self.headers.clone()).send() } }
true
83b6c90747ebfdd33e9a8126fa60f6ed51ffa02d
Rust
19h/polygon-rs
/src/models/exchange.rs
UTF-8
2,529
2.53125
3
[]
no_license
/* * Polygon API * * The future of fintech. * * OpenAPI spec version: 1.0.1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ #![allow(unused_imports)] use serde_json::Value; use bigdecimal::BigDecimal; use chrono::{NaiveDateTime, DateTime, FixedOffset, Utc}; use crate::models::*; //use crate::date_serializer; //use crate::datetime_serializer; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Exchange { #[serde(rename = "id")] id: f32, // 2.0 #[serde(rename = "type")] _type: String, // exchange #[serde(rename = "market")] market: String, // equities #[serde(rename = "mic")] mic: Option<String>, // XASE #[serde(rename = "name")] name: String, // NYSE American (AMEX) #[serde(rename = "tape")] tape: Option<String> // A } impl Exchange { pub fn new(id: f32, _type: String, market: String, name: String, ) -> Exchange { Exchange { id: id, _type: _type, market: market, mic: None, name: name, tape: None } } pub fn set_id(&mut self, id: f32) { self.id = id; } pub fn with_id(mut self, id: f32) -> Exchange { self.id = id; self } pub fn id(&self) -> &f32 { &self.id } pub fn set__type(&mut self, _type: String) { self._type = _type; } pub fn with__type(mut self, _type: String) -> Exchange { self._type = _type; self } pub fn _type(&self) -> &String { &self._type } pub fn set_market(&mut self, market: String) { self.market = market; } pub fn with_market(mut self, market: String) -> Exchange { self.market = market; self } pub fn market(&self) -> &String { &self.market } pub fn set_mic(&mut self, mic: String) { self.mic = Some(mic); } pub fn with_mic(mut self, mic: String) -> Exchange { self.mic = Some(mic); self } pub fn mic(&self) -> Option<&String> { self.mic.as_ref() } pub fn reset_mic(&mut self) { self.mic = None; } pub fn set_name(&mut self, name: String) { self.name = name; } pub fn with_name(mut self, name: String) -> Exchange { self.name = name; self } pub fn name(&self) -> &String { &self.name } pub fn set_tape(&mut self, tape: String) { self.tape = Some(tape); } pub fn with_tape(mut self, tape: String) -> Exchange { self.tape = Some(tape); self } pub fn tape(&self) -> Option<&String> { self.tape.as_ref() } pub fn reset_tape(&mut self) { self.tape = None; } }
true
36f81e491e64884bcae4eff8b51b5201ae56ad5a
Rust
colin-kiegel/twig-rust
/src/engine/parser/lexer/patterns/verbatim_end.rs
UTF-8
3,218
2.921875
3
[ "BSD-3-Clause" ]
permissive
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! The `verbatim_end` pattern used by the lexer to tokenize the templates. /// /// Written as regular expressions (perl-style). use super::Options; use regex; use regex::Error as regexError; use std::rc::Rc; use api::error::Traced; pub type ExtractIter<'a, 'b> = super::ExtractIter<'a, 'b, Pattern>; pub use super::verbatim_start::Tag; // enum {Raw, Verbatim} #[derive(Debug, PartialEq)] pub struct Pattern { regex: regex::Regex, options: Rc<Options>, } #[derive(Debug, PartialEq)] pub struct ItemData { pub position: (usize, usize), pub whitespace_trim: bool, pub tag: Tag, } impl Pattern { pub fn new(opt: &Rc<Options>) -> Result<Pattern, Traced<regexError>> { Ok(Pattern { regex: try_new_regex!(format!(r"{b0}({ws})?\s*(?:end(raw|verbatim))\s*(?:{ws}{b1}\s*|{b1})", ws = opt.whitespace_trim.quoted(), b0 = opt.tag_block_start.quoted(), b1 = opt.tag_block_end.quoted())), options: opt.clone(), }) } // orig: '/('.$tag_block[0].$whitespace_trim.'|'.$tag_block[0].')\s*(?:end%s)\s*(?:'.$whitespace_trim.$tag_block[1].'\s*|\s*'.$tag_block[1].')/s' } impl<'t> super::Extract<'t> for Pattern { type Item = ItemData; fn regex(&self) -> &regex::Regex { &self.regex } fn item_from_captures(&self, captures: &regex::Captures) -> ItemData { ItemData { position: match captures.pos(0) { Some(position) => position, _ => unreachable!(), }, whitespace_trim: match captures.at(1) { Some(_) => true, None => false, }, tag: match captures.at(2) { Some("raw") => Tag::Raw, Some("verbatim") => Tag::Verbatim, _ => unreachable!(), }, } } } #[cfg(test)] mod test { use super::*; use engine::parser::lexer::patterns::{Options, Extract}; use std::rc::Rc; #[test] pub fn as_str() { let ref options = Rc::<Options>::default(); let pattern = Pattern::new(options).unwrap(); assert_eq!(pattern.as_str(), r"\{%(-)?\s*(?:end(raw|verbatim))\s*(?:-%\}\s*|%\})"); } #[test] pub fn extract() { let ref options = Rc::<Options>::default(); let pattern = Pattern::new(options).unwrap(); assert_eq!(pattern.extract(&r"Lorem Ipsum"), None); assert_eq!(pattern.extract(&r"Lorem Ipsum {% endraw %} dolor").unwrap(), ItemData { position: (12, 24), whitespace_trim: false, tag: Tag::Raw, }); assert_eq!(pattern.extract(&r"And then there was silence {%- endverbatim -%} .") .unwrap(), ItemData { position: (27, 53), whitespace_trim: true, tag: Tag::Verbatim, }); } }
true
5ad6b5645360d9b6821f7ed0c09bd628ccb2bf52
Rust
kimlimjustin/xplorer
/api/web/src/drives.rs
UTF-8
2,581
3.015625
3
[ "Apache-2.0" ]
permissive
use std::process::Command; use sysinfo::{DiskExt, System, SystemExt}; #[derive(serde::Serialize, Debug)] pub struct DriveInformation { name: String, mount_point: String, total_space: u64, available_space: u64, is_removable: bool, disk_type: String, file_system: String, } #[derive(serde::Serialize)] pub struct Drives { array_of_drives: Vec<DriveInformation>, } pub fn get_drives() -> Result<Drives, String> { let sys = System::new_all(); let mut array_of_drives = Vec::new(); for disk in sys.disks() { let mut total_space: u64 = disk.total_space(); let available_space: u64 = disk.available_space(); let mount_point: String = disk.mount_point().to_str().unwrap_or("/").to_string(); let name: String = disk.name().to_str().unwrap_or("Disk").to_string(); let is_removable: bool = disk.is_removable(); let mut caption = mount_point.clone(); let file_system = String::from_utf8(disk.file_system().to_vec()).unwrap_or("Err".to_string()); let disk_type: String; if disk.type_() == sysinfo::DiskType::SSD { disk_type = "SSD".to_string() } else if disk.type_() == sysinfo::DiskType::HDD { disk_type = "HDD".to_string() } else { disk_type = "Removable Disk".to_string() } caption.pop(); if total_space < available_space { if cfg!(target_os = "windows") { let wmic_process = Command::new("cmd") .args([ "/C", &format!( "wmic logicaldisk where Caption='{caption}' get Size", caption = caption ), ]) .output() .expect("failed to execute process"); let wmic_process_output = String::from_utf8(wmic_process.stdout).unwrap(); let parsed_size = wmic_process_output.split("\r\r\n").collect::<Vec<&str>>()[1].to_string(); match parsed_size.trim().parse::<u64>() { Ok(n) => total_space = n, Err(_) => {} } } } array_of_drives.push(DriveInformation { name, mount_point, total_space, available_space, is_removable, disk_type, file_system, }); } Ok(Drives { array_of_drives: array_of_drives, }) }
true
734ef1f33671ba9ee0e9d8a12009340490308900
Rust
mrjones/simcastle
/src/core/gamestate.rs
UTF-8
8,700
2.828125
3
[]
no_license
use super::castle; use super::character; use super::economy; use super::population; use super::statemachine; use super::types; use super::workforce; use log::{info}; use anyhow::Context; use rand::Rng; use serde::{Deserialize, Serialize}; pub struct GameSpec { pub initial_potential_characters: usize, pub initial_characters: usize, } #[derive(Clone, Deserialize, Serialize)] pub struct GameStateT { pub turn: i32, pub food: types::Millis, pub population: population::Population, pub workforce: workforce::Workforce, pub castle: castle::Castle, pub next_valid_cid: character::CharacterId, } #[derive(Clone, Deserialize, Serialize, Debug)] pub enum UserCommand { AssignToTeam{cid: character::CharacterId, job: workforce::Job}, // Unassign{cid: character::CharacterId}, AddCharacter{character: character::Character}, AddToBuildQueue{infra: castle::Infrastructure}, } #[derive(Clone, Serialize, Deserialize)] enum MutationT { EndTurn{builder_accumulation: types::Millis, food: types::Millis}, UserCommand{cmd: UserCommand}, UpdateCharacter{character_delta: character::CharacterDelta}, CompleteInfrastructure{infra: castle::Infrastructure}, } fn apply_mutation(state: &mut GameStateT, m: &MutationT) -> anyhow::Result<()> { match &m { &MutationT::EndTurn{builder_accumulation, food} => { state.turn = state.turn + 1; state.workforce.advance_turn(); for (c1, c2) in state.workforce.farmers().member_pairs() { state.population.mut_rapport_tracker().inc_turns_on_same_team(&c1, &c2); } state.castle.build_queue.progress = *builder_accumulation; state.food = *food; } &MutationT::UserCommand{cmd} => apply_user_command(state, cmd)?, &MutationT::UpdateCharacter{character_delta} => { let character = state.population.mut_character_with_id(character_delta.id) .expect(&format!("no character with id {}", character_delta.id)); for (&t, &new_v) in &character_delta.changed_trait_values { character.mut_trait(t).value = new_v; } }, &MutationT::CompleteInfrastructure{infra} => { match infra { castle::Infrastructure::AcreOfFarmland => { state.castle.food_infrastructure.acres_of_farmland = state.castle.food_infrastructure.acres_of_farmland + 1; } } } } return Ok(()); } fn apply_user_command(state: &mut GameStateT, c: &UserCommand) -> anyhow::Result<()> { match &c { &UserCommand::AssignToTeam{cid, job} => state.workforce.assign(cid.clone(), job.clone())?, // &UserCommand::Unassign{cid} => state.workforce.unassign(*cid)?, &UserCommand::AddCharacter{character} => { if character.id().0 >= state.next_valid_cid.0 { state.next_valid_cid = character::CharacterId(character.id().0 + 1); } state.population.add(character.clone()); state.workforce.add_unassigned(character.id()); }, &UserCommand::AddToBuildQueue{infra} => { state.castle.build_queue.queue.push(*infra); } } return Ok(()); } pub enum Prompt { AsylumSeeker(character::Character), } pub struct GameState { machine: statemachine::PersistentStateMachine<GameStateT, MutationT>, } impl GameState { pub fn init(spec: GameSpec, initial_characters: Vec<character::Character>, save_file: std::fs::File) -> anyhow::Result<GameState> { assert_eq!(initial_characters.len(), spec.initial_characters as usize, "Please pick {} initial characters ({} selected)", spec.initial_characters, initial_characters.len()); return Ok(GameState{ machine: statemachine::PersistentStateMachine::init( GameStateT{ turn: 0, food: types::Millis::from_i32(2 * spec.initial_characters as i32), workforce: workforce::Workforce::new( initial_characters.iter().map(character::Character::id).collect()), next_valid_cid: initial_characters.iter().fold( character::CharacterId(0), |so_far, candidate| character::CharacterId(std::cmp::max(so_far.0, candidate.id().0 + 1))), population: population::Population::new(initial_characters), castle: castle::Castle::init(&spec), }, Box::new(apply_mutation), statemachine::Saver::new(std::rc::Rc::new(std::sync::Mutex::new(save_file))), )?, }); } fn restore_helper<P: AsRef<std::path::Path> + std::fmt::Debug>(filename: &P) -> anyhow::Result<GameStateT> { use std::io::BufRead; let restore_file = std::fs::File::open(filename) .with_context(|| format!("Opening {:?} for restore", *filename))?; let restore_reader = std::io::BufReader::new(restore_file); return Ok(statemachine::PersistentStateMachine::recover( &mut restore_reader.lines().map(|r| r.expect("error reading line")), &apply_mutation)?); } pub fn restore<P: AsRef<std::path::Path> + std::fmt::Debug>(filename: P) -> anyhow::Result<GameState> { let state = GameState::restore_helper(&filename)?; let save_file = std::fs::OpenOptions::new().write(true).append(true).open(&filename) .with_context(|| format!("Opening {:?} for as save_file", &filename))?; return Ok(GameState{ machine: statemachine::PersistentStateMachine::init( state, Box::new(apply_mutation), statemachine::Saver::new(std::rc::Rc::new(std::sync::Mutex::new(save_file))))?, }); } pub fn execute_command(&mut self, command: &UserCommand) -> anyhow::Result<()> { return self.machine.apply(&MutationT::UserCommand{cmd: command.clone()}); } // TODO(mrjones): Make GameState immutable, and make this return a copy? pub fn advance_turn(&mut self) -> anyhow::Result<Vec<Prompt>> { // TODO(mrjones): Starvation let food = std::cmp::min( self.machine.state().castle.food_infrastructure.food_storage, self.machine.state().food + self.food_delta()); for char_delta in self.machine.state().population.compute_end_of_turn_deltas() { self.machine.apply(&MutationT::UpdateCharacter{character_delta: char_delta})?; } let builder_production = self.builder_economy().production.eval(); let build_queue_state = self.machine.state().castle.build_queue.turn_end(builder_production); for infra in build_queue_state.items_completed { self.machine.apply(&MutationT::CompleteInfrastructure{infra: infra})?; info!("Completed infrastructure: {:?}", infra); } // TODO: Need to decide what explicitly gets written down, and what gets // recomputed by the execute_mutation framework... self.machine.apply(&MutationT::EndTurn{ food: food, builder_accumulation: build_queue_state.progress, })?; let mut prompts = vec![]; if rand::thread_rng().gen_bool(0.1) { prompts.push(Prompt::AsylumSeeker(character::Character::new_random( self.machine.state().next_valid_cid))); } return Ok(prompts); } pub fn food_economy(&self) -> economy::FoodEconomy { return economy::food(self.machine.state().workforce.farmers(), &self.machine.state().castle.food_infrastructure, &self.machine.state().population); } pub fn builder_economy(&self) -> economy::BuilderEconomy { return economy::builder_economy(self.machine.state().workforce.builders(), &self.machine.state().population); } pub fn food_delta(&self) -> types::Millis { let food_economy = self.food_economy(); return food_economy.production.eval() - food_economy.consumed_per_turn; } pub fn population(&self) -> &population::Population { return &self.machine.state().population; } pub fn workforce(&self) -> &workforce::Workforce { return &self.machine.state().workforce; } pub fn castle(&self) -> &castle::Castle { return &self.machine.state().castle; } pub fn turn(&self) -> i32 { return self.machine.state().turn; } pub fn food(&self) -> types::Millis { return self.machine.state().food; } }
true
4e8c99e01fd26d809819e42a04ee98a032871e30
Rust
r8d8/u2f-hid-rs
/src/linux/devicemap.rs
UTF-8
1,615
2.875
3
[]
no_license
use rand::{thread_rng, Rng}; use std::collections::hash_map::ValuesMut; use std::collections::HashMap; use std::ffi::OsString; use ::platform::device::Device; use ::platform::monitor::Event; pub struct DeviceMap { map: HashMap<OsString, Device> } impl DeviceMap { pub fn new() -> Self { Self { map: HashMap::new() } } pub fn values_mut(&mut self) -> ValuesMut<OsString, Device> { self.map.values_mut() } pub fn process_event(&mut self, event: Event) { match event { Event::Add(path) => self.add(path), Event::Remove(path) => self.remove(path) } } fn add(&mut self, path: OsString) { if self.map.contains_key(&path) { return; } // Create and try to open the device. if let Ok(mut dev) = Device::new(path.clone()) { if !dev.is_u2f() { return; } // Do a few U2F device checks. let mut nonce = [0u8; 8]; thread_rng().fill_bytes(&mut nonce); if let Err(_) = ::init_device(&mut dev, nonce) { return; } let mut random = [0u8; 8]; thread_rng().fill_bytes(&mut random); if let Err(_) = ::ping_device(&mut dev, random) { return; } if let Err(_) = ::u2f_version_is_v2(&mut dev) { return; } self.map.insert(path, dev); } } fn remove(&mut self, path: OsString) { // Ignore errors. let _ = self.map.remove(&path); } }
true
461f5485b47943e91e8adeed43013bbecfc37d7e
Rust
petitviolet/rsstable
/src/sst/rich_file.rs
UTF-8
1,621
3.078125
3
[]
no_license
use std::{ fs::{File, OpenOptions}, io, ops::Deref, path::{Path, PathBuf}, }; pub(crate) struct RichFile { pub underlying: File, pub dir: String, pub name: String, } #[derive(Debug)] pub(crate) enum FileOption { New, Append, ReadOnly, } impl FileOption { fn open(&self, path: &PathBuf) -> Result<File, io::Error> { let mut option = OpenOptions::new(); match self { FileOption::New => option.read(true).write(true).truncate(true).create(true), FileOption::Append => option.read(true).append(true).truncate(false).create(true), FileOption::ReadOnly => { OpenOptions::new() .create(true) .write(true) .truncate(false) .open(path)?; option.read(true) } } .open(path) } } impl RichFile { pub fn open_file( dir_name: impl Into<String>, file_name: impl Into<String>, option: FileOption, ) -> io::Result<RichFile> { let dir_name = dir_name.into(); let dir = Path::new(&dir_name); let file_name_s: String = file_name.into(); let path = dir.join(&file_name_s); let file = option .open(&path) .expect(format!("failed to open file({:?}), option: {:?}", &path, option).deref()); Ok(RichFile { underlying: file, dir: dir_name, name: file_name_s, }) } pub fn path(&self) -> PathBuf { Path::new(&self.dir).join(&self.name) } }
true
df6c591baa26687c2269a2e2e45b18f1122faa87
Rust
remram44/rpztar
/src/main.rs
UTF-8
7,545
2.828125
3
[]
no_license
use anyhow::{Context, Result as AResult, anyhow}; use flate2::read::GzDecoder; use nix::unistd::{FchownatFlags, Gid, Uid, fchownat}; use tar::{Archive, Entry, EntryType}; use std::collections::HashSet; use std::convert::TryInto; use std::env; use std::ffi::{OsStr, OsString}; use std::fs; use std::io::{BufRead, Read}; use std::os::unix::ffi::OsStringExt; use std::path::{Component, Path, PathBuf}; fn main() -> AResult<()> { // Read arguments let mut args = env::args(); args.next().unwrap(); let tar_filename = match args.next() { Some(v) => v, None => return Err(anyhow!("Missing argument")), }; let list_filename = match args.next() { Some(v) => v, None => return Err(anyhow!("Missing argument")), }; match args.next() { Some(_) => return Err(anyhow!("Too many arguments")), None => {} } // Read file list let files: HashSet<PathBuf> = { let list_file = fs::File::open(list_filename) .with_context(|| "Error opening list file")?; let list_file = std::io::BufReader::new(list_file); let mut files = HashSet::new(); for file in list_file.split(0u8) { let file = file.with_context(|| "Error reading list")?; if file.len() > 0 { let osstr: OsString = OsStringExt::from_vec(file); files.insert(osstr.into()); } } files }; // Open tar let tar_gz = fs::File::open(tar_filename) .with_context(|| "Error opening tar file")?; let tar = GzDecoder::new(tar_gz); let mut archive = Archive::new(tar); let destination = Path::new(""); // Delay directory entries until the end let mut directories = Vec::new(); // Unpack entries (similar to Archive::_unpack()) for entry in archive.entries()? { let entry = entry?; // Check if the file is in our list let path = get_canonical_path(Path::new(""), &entry)?; let path = match path { Some(p) => p, None => continue, }; if !files.contains(&path) { continue; } if entry.header().entry_type() == EntryType::Directory { directories.push(entry); } else { unpack(entry, destination)?; } } for entry in directories { unpack(entry, destination)?; } Ok(()) } fn get_canonical_path<'a, R: Read>( prefix: &Path, entry: &Entry<'a, R>, ) -> AResult<Option<PathBuf>> { let path = entry.path().with_context(|| { format!("invalid path in entry header: {}", String::from_utf8_lossy(&entry.path_bytes())) })?; let mut file_dst = prefix.to_path_buf(); { // Check first component is "DATA" let mut found_prefix = false; for part in path.components() { match part { // Leading '/' characters, root paths, and '.' // components are just ignored and treated as "empty // components" Component::Prefix(..) | Component::RootDir | Component::CurDir => continue, // If any part of the filename is '..', then skip over // unpacking the file to prevent directory traversal // security issues. See, e.g.: CVE-2001-1267, // CVE-2002-0399, CVE-2005-1918, CVE-2007-4131 Component::ParentDir => return Err(anyhow!("invalid path: {:?}", path)), Component::Normal(part) => { if !found_prefix { if part != "DATA".as_ref() as &OsStr { return Ok(None); } found_prefix = true; } else { file_dst.push(part); } } } } } Ok(Some(file_dst)) } fn unpack<'a, R: Read>( mut entry: Entry<'a, R>, dst: &Path, ) -> AResult<()> { // This extends Entry::unpack_in() let file_dst = get_canonical_path(dst, &entry)?; let file_dst = match file_dst { Some(p) => p, None => return Ok(()), }; // Skip cases where only slashes or '.' parts were seen, because // this is effectively an empty filename. if dst == &file_dst { return Ok(()); } // Skip entries without a parent (i.e. outside of FS root) let parent = match file_dst.parent() { Some(p) => p, None => return Ok(()), }; // Create parent directories, removing existing files let mut ancestor = dst.to_path_buf(); for part in parent.components() { match part { Component::Normal(part) => { ancestor.push(part); match fs::symlink_metadata(&ancestor) { // Does not exist: good Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Ok(m) => { if !m.is_dir() { // Exists and is a file: remove fs::remove_file(&ancestor) .with_context(|| format!("Error deleting {:?} to unpack {:?}", ancestor, file_dst))?; } else { // Exists and is a directory: good, we'll restore // permissions later continue; } } Err(e) => return Err(e).with_context(|| format!("Error stat()ing {:?} to unpack {:?}", ancestor, file_dst)), } fs::create_dir(&ancestor) .with_context(|| format!("Error creating directory {:?} to unpack {:?}", ancestor, file_dst))?; } _ => {} } } // Remove existing file or directory at destination match fs::symlink_metadata(&file_dst) { // Does not exist: good Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Ok(m) => { if m.is_dir() { if entry.header().entry_type() == EntryType::Directory { // Is a directory, as expected: ignore // unpack() will restore permissions } else { // Is a directory, where we want a file: remove eprintln!("removing directory {:?}", &file_dst); fs::remove_dir_all(&file_dst) .with_context(|| format!("Error removing directory {:?} to extract file over", file_dst))?; } } else { // Is a file: remove fs::remove_file(&file_dst) .with_context(|| format!("Error removing file {:?} to extract {:?} over", file_dst, entry.header().entry_type()))?; } } Err(e) => return Err(e).with_context(|| format!("Error deleting {:?} to unpack over it", file_dst)), } entry.set_preserve_permissions(true); entry.set_preserve_mtime(true); entry.unpack(&file_dst) .with_context(|| format!("failed to unpack `{:?}`", file_dst))?; // Restore ownership fchownat( None, &file_dst, Some(Uid::from_raw(entry.header().uid()?.try_into()?)), Some(Gid::from_raw(entry.header().gid()?.try_into()?)), FchownatFlags::NoFollowSymlink, ).with_context(|| format!("Error restoring ownership of {:?}", file_dst))?; Ok(()) }
true
c446d197211f9fddece9b19602a5daa33859a3ec
Rust
winding-lines/weaver
/lib-index/src/repo/mod.rs
UTF-8
654
2.546875
3
[]
no_license
use lib_error::*; use std::convert::From; mod config; mod encrypted_repo; pub use self::encrypted_repo::EncryptedRepo; /// Represents a collection in the repo. #[derive(Debug)] pub struct Collection(pub String); impl Collection { fn name(&self) -> &str { &self.0 } } impl From<String> for Collection { fn from(name: String) -> Self { Collection(name) } } impl<'a> From<&'a str> for Collection { fn from(name: &'a str) -> Self { Collection(name.into()) } } /// Trait with document management related api pub trait Repo { fn add(&self, collection: &Collection, content: &[u8]) -> Result<String>; }
true
37c1cbb83c93ea366349890bebd611d7d316dd6e
Rust
soundybot/helium
/src/routes/upload.rs
UTF-8
2,696
2.546875
3
[ "MIT" ]
permissive
use crate::enums::PermissionLvl; use crate::s3::upload::upload_to_s3; use crate::s3::util::get_default_tags; use crate::structs::{HeliumConfig, HeliumConfigWrapper}; use crate::util; use crate::util::build_perm_err; use actix_multipart::Multipart; use actix_web::body::Body; use actix_web::http::Error; use actix_web::{web, HttpRequest, HttpResponse}; use tokio::stream::StreamExt; pub async fn save_file( req: HttpRequest, mut payload: Multipart, config: web::Data<HeliumConfigWrapper>, ) -> Result<HttpResponse, Error> { println!("saving started..."); let config = util::get_config_ownership(&config.config); let tags = get_default_tags(); println!("2"); let perm_lvl = util::permissioncheck( &*match util::get_header(req, "helium_key") { Ok(value) => value, Err(response) => return Ok(response), }, &config, ); if !perm_lvl.eq(&PermissionLvl::ADMIN) { return Ok(build_perm_err(PermissionLvl::ADMIN, perm_lvl)); }; println!("extracting payload"); let mut field = match payload.try_next().await { Ok(field) => match field { Some(field) => field, None => { return Ok(HttpResponse::InternalServerError() .body(Body::from("failed at extracting the field!"))); } }, Err(_) => { return Ok(HttpResponse::BadRequest() .body(Body::from("Invalid file. Was the file renamed or deleted?"))); } }; println!("3"); let content_type = field.content_disposition().unwrap(); let filename = content_type.get_filename().unwrap(); let filename = util::rewrite_filename(filename).clone(); let mut data_arr = Vec::new(); println!("4"); // Field in turn is stream of *Bytes* object while let Some(chunk) = field.next().await { let data: actix_web::web::Bytes = chunk.unwrap(); data_arr.append(&mut data.to_vec()); } println!("5"); let file_ext = match util::get_extension_from_filename(&*filename) { Some(extension) => extension, None => "", }; println!("6"); let returnable = match upload_to_s3( data_arr, (&filename).to_string(), util::get_content_type(file_ext), config, tags, ) .await { Ok(returnable) => returnable, Err(err) => HttpResponse::InternalServerError().body(Body::from(format!( "upload returned an error! \n{:?}", err ))), }; println!("7"); Ok(returnable) }
true
f4637ddd034d78bf8ede1f6273038f77654119fd
Rust
xDerekFoster/cargo-mobile
/src/android/adb/device_name.rs
UTF-8
1,276
2.796875
3
[ "Apache-2.0", "MIT" ]
permissive
use super::adb; use crate::{ android::env::Env, util::cli::{Report, Reportable}, }; use once_cell_regex::regex; use std::str; #[derive(Debug)] pub enum Error { DumpsysFailed(super::RunCheckedError), InvalidUtf8(str::Utf8Error), NotMatched, } impl Reportable for Error { fn report(&self) -> Report { let msg = "Failed to get device name"; match self { Self::DumpsysFailed(err) => { err.report("Failed to run `adb shell dumpsys bluetooth_manager`") } Self::InvalidUtf8(err) => { Report::error(msg, format!("Output contained invalid UTF-8: {}", err)) } Self::NotMatched => Report::error(msg, "Name regex didn't match anything"), } } } pub fn device_name(env: &Env, serial_no: &str) -> Result<String, Error> { let name_re = regex!(r"\bname: (?P<name>.*)"); let output = super::run_checked(&mut adb(env, serial_no).with_args(&[ "shell", "dumpsys", "bluetooth_manager", ])) .map_err(Error::DumpsysFailed)?; let raw = output.stdout_str().map_err(Error::InvalidUtf8)?; name_re .captures(raw) .map(|caps| caps["name"].to_owned()) .ok_or_else(|| Error::NotMatched) }
true
03fa952b8d42a854a083e0fdee4367c1b5c71298
Rust
lineCode/tuix
/widgets/src/inputs/slider.rs
UTF-8
17,696
3.484375
3
[ "MIT" ]
permissive
use crate::common::*; #[derive(Debug, Clone, PartialEq)] pub enum SliderEvent { // TODO - Remove this ValueChanged(f32), SetValue(f32), SetMin(f32), SetMax(f32), } pub struct Slider { // The track that the thumb slides along track: Entity, // An overlay on the track to indicate the value active: Entity, // A marker used to indicate the value by its position along the track thumb: Entity, // Event sent when the slider value has changed on_change: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>, // event sent when the slider value is changing on_changing: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>, // Event sent when the slider reaches the minimum value on_min: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>, // Event sent when the slider reaches the maximum value on_max: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>, // Event sent when the slider is pressed on_press: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>, // Event sent when the slider is released on_release: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>, // Event sent when the mouse cursor enters the slider on_over: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>, // Event sent when the mouse cusor leaves the slider on_out: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>, pub value: f32, prev: f32, min: f32, max: f32, is_min: bool, is_max: bool, } impl Default for Slider { fn default() -> Self { Self { track: Entity::default(), active: Entity::default(), thumb: Entity::default(), on_change: None, on_changing: None, on_min: None, on_max: None, on_press: None, on_release: None, on_over: None, on_out: None, value: 0.0, prev: 0.0, min: 0.0, max: 1.0, is_min: true, is_max: false, } } } impl Slider { /// Create a new slider widget with default values (min: 0.0, max: 1.0, val: 0.0). /// /// # Example /// /// ``` /// Slider::new().build(state, parent, |builder| builder); /// ``` pub fn new() -> Self { Self::default() } /// Set the initial value of the slider. /// /// # Example /// /// ``` /// Slider::new() /// .with_init(0.5) /// .build(state, parent, |builder| builder) /// ``` pub fn with_init(mut self, val: f32) -> Self { self.value = val; self } /// Set the range of the slider. Min and Max values are extracted from the range. /// /// # Example /// /// ``` /// Slider::new() /// .with_range(0.0..5.0) /// .build(state, parent, |builder| builder) /// ``` pub fn with_range(mut self, range: std::ops::Range<f32>) -> Self { self.min = range.start; self.max = range.end; self } /// Set the minimum value of the slider. /// /// # Example /// /// ``` /// Slider::new() /// .with_min(0.2) /// .build(state, parent, |builder| builder) /// ``` pub fn with_min(mut self, val: f32) -> Self { self.min = val; self } /// Set the maximum value of the slider. /// /// # Example /// /// ``` /// Slider::new() /// .with_max() /// .build(state, parent, |builder| builder) /// ``` pub fn with_max(mut self, val: f32) -> Self { self.max = val; self } /// Set the callback triggered when the slider value has changed. /// /// Takes a closure which provides the current value and returns an event to be sent when the slider /// value has changed after releasing the slider. If the slider thumb is pressed but not moved, and thus /// the value is not changed, then the event will not be sent. /// /// # Example /// /// ``` /// Slider::new() /// .on_change(|slider, state, entity| { /// entity.emit(WindowEvent::Debug(format!("Slider on_change: {}", slider.value))); /// }) /// .build(state, parent, |builder| builder); /// ``` pub fn on_change<F>(mut self, callback: F) -> Self where F: 'static + Fn(&mut Self, &mut State, Entity), { self.on_change = Some(Box::new(callback)); self } /// Set the callback triggered when the slider value is changing (dragging). /// /// Takes a closure which triggers when the slider value is changing, /// either by pressing the track or dragging the thumb along the track. /// /// # Example /// /// ``` /// Slider::new() /// .on_changing(|slider, state, entity| { /// entity.emit(WindowEvent::Debug(format!("Slider on_changing: {}", slider.value))); /// }) /// .build(state, parent, |builder| builder); /// ``` pub fn on_changing<F>(mut self, callback: F) -> Self where F: 'static + Fn(&mut Self, &mut State, Entity), { self.on_changing = Some(Box::new(callback)); self } /// Set the callback triggered when the slider value reaches the minimum. /// /// Takes a closure which triggers when the slider reaches the minimum value, /// either by pressing the track at the start or dragging the thumb to the start /// of the track. The event is sent once for each time the value reaches the minimum. /// /// # Example /// /// ``` /// Slider::new() /// .on_min(|slider, state, entity| { /// entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value))); /// }) /// .build(state, parent, |builder| builder); /// ``` pub fn on_min<F>(mut self, callback: F) -> Self where F: 'static + Fn(&mut Self, &mut State, Entity), { self.on_min = Some(Box::new(callback)); self } /// Set the callback triggered when the slider value reaches the maximum. /// /// Takes a closure which triggers when the slider reaches the maximum value, /// either by pressing the track at the end or dragging the thumb to the end /// of the track. The event is sent once for each time the value reaches the maximum. /// /// # Example /// /// ``` /// Slider::new() /// .on_max(|slider, state, entity| { /// entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value))); /// }) /// .build(state, parent, |builder| builder); /// ``` pub fn on_max<F>(mut self, callback: F) -> Self where F: 'static + Fn(&mut Self, &mut State, Entity), { self.on_max = Some(Box::new(callback)); self } /// Set the event sent when the slider is pressed. /// /// The event is sent when the left mouse button is pressed on any part of the slider. /// /// # Example /// /// ``` /// Slider::new() /// .on_max(|slider, state, entity| { /// entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value))); /// }) /// .build(state, parent, |builder| builder); /// ``` // pub fn on_press<F>(mut self, callback: F) -> Self // where // F: 'static + Fn(&mut Self, &mut State, Entity), // { // self.on_press = Some(Box::new(callback)); // self // } /// Set the event sent when the slider is released. /// /// The event is sent when the left mouse button is released after being pressed on any part of the slider. /// /// # Example /// /// ``` /// Slider::new() /// .on_max(|slider, state, entity| { /// entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value))); /// }) /// .build(state, parent, |builder| builder); /// ``` pub fn on_release<F>(mut self, callback: F) -> Self where F: 'static + Fn(&mut Self, &mut State, Entity), { self.on_release = Some(Box::new(callback)); self } /// Set the event sent when the mouse cursor enters the slider. /// /// The event is sent when the mouse cursor enters the bounding box of the slider. /// /// # Example /// /// ``` /// Slider::new() /// .on_max(|slider, state, entity| { /// entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value))); /// }) /// .build(state, parent, |builder| builder); /// ``` pub fn on_over<F>(mut self, callback: F) -> Self where F: 'static + Fn(&mut Self, &mut State, Entity), { self.on_over = Some(Box::new(callback)); self } /// Set the event sent when the mouse cursor leaves the slider /// /// The event is sent when the mouse cursor leaves the bounding box of the slider. /// /// # Example /// /// ``` /// Slider::new() /// .on_max(|slider, state, entity| { /// entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value))); /// }) /// .build(state, parent, |builder| builder); /// ``` pub fn on_out<F>(mut self, callback: F) -> Self where F: 'static + Fn(&mut Self, &mut State, Entity), { self.on_out = Some(Box::new(callback)); self } // Private helper functions // Update the active size and thumb position fn update_value(&mut self, state: &mut State, entity: Entity, mut dx: f32) { let width = state.data.get_width(entity); let thumb_width = state.data.get_width(self.thumb); if dx <= thumb_width / 2.0 { dx = thumb_width / 2.0; } if dx >= width - thumb_width / 2.0 { dx = width - thumb_width / 2.0; } let nx = (dx - thumb_width / 2.0) / (width - thumb_width); self.thumb .set_left(state, Units::Percentage(100.0 * (dx - thumb_width / 2.0) / width)); self.active.set_width(state, Units::Percentage(nx * 100.0)); self.value = self.min + nx * (self.max - self.min); if self.value == self.min { if !self.is_min { self.is_min = true; //self.send_value_event(state, entity, &self.on_min); if let Some(callback) = self.on_min.take() { (callback)(self, state, entity); self.on_min = Some(callback); } } } else { self.is_min = false; } if self.value == self.max { if !self.is_max { self.is_max = true; if let Some(callback) = self.on_max.take() { (callback)(self, state, entity); self.on_max = Some(callback); } } } else { self.is_max = false; } } fn update_visuals(&mut self, state: &mut State, entity: Entity) { let normalised_value = (self.value - self.min) / (self.max - self.min); let width = state.data.get_width(entity); let thumb_width = state.data.get_width(self.thumb); let dx = normalised_value * (width - thumb_width) + thumb_width / 2.0; self.update_value(state, entity, dx); } fn clamp_value(&mut self) { self.value = self.value.clamp(self.min, self.max); } } impl Widget for Slider { type Ret = Entity; type Data = f32; fn on_build(&mut self, state: &mut State, entity: Entity) -> Self::Ret { if self.min > self.max { panic!("minimum value must be less than maximum value") } self.clamp_value(); self.is_min = self.value == self.min; self.is_max = self.value == self.max; entity .set_layout_type(state, LayoutType::Row) .set_child_top(state, Stretch(1.0)) .set_child_bottom(state, Stretch(1.0)); // Track self.track = Element::new().build(state, entity, |builder| { builder .set_width(Stretch(1.0)) // .set_height(Pixels(4.0)) .set_bottom(Auto) .set_hoverable(false) .class("track") }); // Active self.active = Element::new().build(state, self.track, |builder| { builder .set_width(Percentage(0.0)) .set_height(Stretch(1.0)) .set_hoverable(false) .class("active") }); // Thumb self.thumb = Element::new().build(state, entity, |builder| { builder .set_position_type(PositionType::SelfDirected) .set_hoverable(false) .class("thumb") }); entity.set_element(state, "slider") } fn on_event(&mut self, state: &mut State, entity: Entity, event: &mut Event) { // Handle window events if let Some(window_event) = event.message.downcast() { match window_event { //TODO // WindowEvent::GeometryChanged(_) if event.target == entity => { // self.update_visuals(state, entity); // } WindowEvent::MouseOver if event.target == entity => { if let Some(callback) = self.on_over.take() { (callback)(self, state, entity); self.on_over = Some(callback); } } WindowEvent::MouseOut if event.target == entity => { if let Some(callback) = self.on_out.take() { (callback)(self, state, entity); self.on_out = Some(callback); } } WindowEvent::MouseDown(button) if event.target == entity => { if *button == MouseButton::Left { state.capture(entity); self.prev = self.value; entity.set_active(state, true); if let Some(callback) = self.on_press.take() { (callback)(self, state, entity); self.on_press = Some(callback); } let dx = state.mouse.left.pos_down.0 - state.data.get_posx(entity); self.update_value(state, entity, dx); if let Some(callback) = self.on_changing.take() { (callback)(self, state, entity); self.on_changing = Some(callback); } state.insert_event( Event::new(SliderEvent::ValueChanged(self.value)).target(entity), ); } } WindowEvent::MouseUp(button) if event.target == entity => { if *button == MouseButton::Left { state.release(entity); entity.set_active(state, false); if self.prev != self.value { //self.send_value_event(state, entity, &self.on_change); if let Some(callback) = self.on_change.take() { (callback)(self, state, entity); self.on_change = Some(callback); } } if let Some(callback) = self.on_release.take() { (callback)(self, state, entity); self.on_release = Some(callback); } } } WindowEvent::MouseMove(x, _) if event.target == entity => { if entity.is_active(state) { let dx = *x - state.data.get_posx(entity); self.update_value(state, entity, dx); if let Some(callback) = self.on_changing.take() { (callback)(self, state, entity); self.on_changing = Some(callback); } } } // TODO - Add keyboard control _ => {} } } // Handle slider events if let Some(slider_event) = event.message.downcast() { match slider_event { SliderEvent::SetMin(val) => { self.min = *val; self.min = self.min.min(self.max); self.clamp_value(); self.update_visuals(state, entity); } SliderEvent::SetMax(val) => { self.max = *val; self.max = self.max.max(self.min); self.clamp_value(); self.update_visuals(state, entity); } SliderEvent::SetValue(val) => { self.value = *val; self.clamp_value(); self.update_visuals(state, entity); } _ => {} } } } fn on_update(&mut self, state: &mut State, entity: Entity, data: &Self::Data) { self.value = *data; self.update_visuals(state, entity); } }
true
559188a66f369418b1082e6b10da18f973d61080
Rust
drconopoima/quick-sort-rust
/src/random_generator.rs
UTF-8
1,451
3.28125
3
[ "Apache-2.0" ]
permissive
use std::num::Wrapping; /// Pseudo-random number generator based on Lehmer algorithm /// Source https://lemire.me/blog/2019/03/19/the-fastest-conventional-random-number-generator-that-can-pass-big-crush/ use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; lazy_static::lazy_static! { static ref RG: Mutex<RandGen> = Mutex::new(RandGen::new(SystemTime::now().duration_since(UNIX_EPOCH) .expect("Error: Failed to get current time as duration from epoch.").as_millis() as usize)); } pub fn rand(max: usize) -> usize { RG.lock().unwrap().lehmer(max) } pub struct RandGen { current: usize, multiplier: Wrapping<u128>, big_int: Wrapping<u128>, } impl RandGen { pub fn new(current: usize) -> Self { RandGen { current, multiplier: Wrapping(0xa3b195354a39b70du128), big_int: Wrapping(0xda942042e4dd58b5u128), } } pub fn lehmer(&mut self, max_value: usize) -> usize { self.big_int = self.big_int * self.multiplier; self.current = (self.big_int.0 >> 64) as usize; self.current % max_value } } #[cfg(test)] mod tests { #[test] fn test_rands_printout() { use super::*; let mut rand_gen = RandGen::new(12); let mut value; for _ in 0..100 { value = rand_gen.lehmer(100); // println!("{:?}", value); assert!(value < 100) } // panic!() } }
true
2c3a9c380020b72c6ddef6a7604aa39c2cd7a0bb
Rust
bmac/ggj-2019-kaiju
/src/main.rs
UTF-8
5,939
2.734375
3
[]
no_license
// Draw an image to the screen extern crate quicksilver; use quicksilver::{ geom::{Rectangle, Shape, Transform, Vector}, graphics::{Background::Img, Color, Image}, // We need Image and image backgrounds input::{Key, ButtonState}, lifecycle::{run, Asset, Settings, State, Window, Event}, // To load anything, we need Asset Result, }; mod building; mod monster; mod util; use building::Building; use monster::{Monster, MonsterState}; use util::create_animation_asset; struct KaijuEngine { sky_background: Asset<Image>, city_background: Asset<Image>, buildings: Vec<Building>, monster: Monster, mouse_down: bool, } impl KaijuEngine { fn render_buildings(&mut self, window: &mut Window) -> Result<()> { for building in &mut self.buildings { let building_position = building.position; let pos_y = building.position.y; let frequency = 0.5; let start_height = building.start_position.y; let rotate = ((pos_y - start_height) * frequency).sin() * 2.0; building.image.execute(|image| { window.draw_ex( &image.area().with_center(building_position), Img(&image), Transform::rotate(rotate), 10, ); Ok(()) })?; } Ok(()) } fn render_background(&mut self, window: &mut Window) -> Result<()> { self.sky_background.execute(|bg_image| { window.draw(&bg_image.area().with_center((400, 300)), Img(&bg_image)); Ok(()) })?; self.city_background.execute(|bg_image| { window.draw(&bg_image.area().with_center((400, 300)), Img(&bg_image)); Ok(()) })?; Ok(()) } } impl State for KaijuEngine { fn new() -> Result<KaijuEngine> { let monster = Monster { walking_animation: create_animation_asset("monster_2_youngster_green_walk.png", 3), idle_animation: create_animation_asset("monster_2_youngster_green_idle.png", 5), attack_animation: create_animation_asset("monster_2_youngster_green_attack.png", 3), state: MonsterState::Idle, position: Vector::new(50, 520), facing: 1.0, }; let sky_background = Asset::new(Image::load("sky.png")); let city_background = Asset::new(Image::load("city_background.png")); let buildings = vec![ Building::new("building_1.png", (200, 450)), Building::new("building_2.png", (280, 525)), Building::new("building_3.png", (360, 500)), Building::new("building_4.png", (440, 510)), Building::new("building_5.png", (520, 550)), Building::new("building_6.png", (600, 570)), Building::new("building_7.png", (680, 550)), Building::new("building_8.png", (760, 560)), Building::new("building_9.png", (840, 500)), ]; Ok(KaijuEngine { city_background, sky_background, monster, buildings, mouse_down: false, }) } fn event(&mut self, event: &Event, _window: &mut Window) -> Result<()> { if let Event::MouseButton(_button, ButtonState::Pressed) = event { self.mouse_down = true; } if let Event::MouseButton(_button, ButtonState::Released) = event { self.mouse_down = false; } Ok(()) } fn update(&mut self, window: &mut Window) -> Result<()> { if self.mouse_down { let direction = self.monster.mouse_direction(window.mouse().pos()); if direction == 1 { self.monster.position.x += 2.5; self.monster.facing = -1.0; self.monster.state = MonsterState::Walking; } else if direction == -1 { self.monster.position.x -= 2.5; self.monster.facing = 1.0; self.monster.state = MonsterState::Walking; } else { let monster_rect = Rectangle::new_sized((249, 200)).with_center(self.monster.position); // maybe just use contains? for building in &mut self.buildings { if building.splash_area.overlaps(&monster_rect) { building.position.y += 1.5; } } self.monster.state = MonsterState::Attack; } } else if window.keyboard()[Key::Right].is_down() { self.monster.position.x += 2.5; self.monster.facing = -1.0; self.monster.state = MonsterState::Walking; } else if window.keyboard()[Key::Left].is_down() { self.monster.position.x -= 2.5; self.monster.facing = 1.0; self.monster.state = MonsterState::Walking; } else if window.keyboard()[Key::Space].is_down() { let monster_rect = Rectangle::new_sized((249, 200)).with_center(self.monster.position); // maybe just use contains? for building in &mut self.buildings { if building.splash_area.overlaps(&monster_rect) { building.position.y += 1.5; } } self.monster.state = MonsterState::Attack; } else { self.monster.state = MonsterState::Idle; } Ok(()) } fn draw(&mut self, window: &mut Window) -> Result<()> { window.clear(Color::WHITE)?; self.render_background(window)?; self.render_buildings(window)?; self.monster.render(window) } } fn main() { run::<KaijuEngine>( "Kaiju Homes", Vector::new(800, 600), Settings { icon_path: Some("favicon.png"), ..Settings::default() }, ); }
true
05d10de8995bb07f8533b552c6c41ab4ff8711e3
Rust
binh-vu/semantic-modeling
/algorithm/src/data_structure/unique_array.rs
UTF-8
1,455
3.25
3
[ "MIT" ]
permissive
use std::collections::HashSet; use std::ops::Index; use std::process::id; use std::hash::Hash; pub struct UniqueArray<V, K: Hash + Eq + PartialEq + Clone=String> { data: Vec<V>, id: HashSet<K> } impl<V, K: Hash + Eq + PartialEq + Clone> UniqueArray<V, K> { pub fn new() -> UniqueArray<V, K> { UniqueArray { data: Vec::new(), id: HashSet::new() } } pub fn with_capacity(capacity: usize) -> UniqueArray<V, K> { UniqueArray { data: Vec::with_capacity(capacity), id: HashSet::with_capacity(capacity) } } pub fn push_borrow(&mut self, id: &K, value: V) -> bool { if !self.id.contains(id) { self.id.insert(id.clone()); self.data.push(value); return true; } return false; } pub fn push(&mut self, id: K, value: V) -> bool { if !self.id.contains(&id) { self.id.insert(id); self.data.push(value); return true; } return false; } pub fn get_ref_value(&self) -> &Vec<V> { &self.data } pub fn get_value(self) -> Vec<V> { self.data } #[inline] pub fn len(&self) -> usize { self.data.len() } } impl<V, K: Hash + Eq + PartialEq + Clone> Index<usize> for UniqueArray<V, K> { type Output = V; fn index(&self, idx: usize)-> &V { &self.data[idx] } }
true
38e23148c94406360e227f3eaa308697769390b8
Rust
gitter-badger/tmpo
/src/error/mod.rs
UTF-8
818
2.90625
3
[ "MIT" ]
permissive
use std::fmt; use std::fmt::{Formatter, Display}; #[derive(Debug)] pub enum RunError { Config(String), IO(std::io::Error), Input(String), Repository(String), Template(String), Update(String), } impl Display for RunError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::Config(e) => write!(f, "Failed to load Config! Error: {}", e), Self::IO(e) => write!(f, "{}", e), Self::Input(e) => write!(f, "{}", e), Self::Repository(e) => write!(f, "Unable to load repository! Error: {}", e), Self::Template(e) => write!(f, "Unable to load template! Error: {}", e), Self::Update(e) => write!(f, "Unable to update! Error: {}", e), } } } impl From<std::io::Error> for RunError { fn from(e: std::io::Error) -> Self { RunError::IO(e) } }
true
9cdcfda6219fb094564a79e6f4f1dbd67ccc63cd
Rust
YewoMhango/cli_calc
/src/token.rs
UTF-8
3,476
4.03125
4
[]
no_license
#[derive(Debug, Clone, Copy, PartialEq)] pub enum Token { Plus, Minus, Multiplication, Division, Modulo, Power, SquareRoot, Combination, Permutation, Logarithm, NaturalLogarithm, ArcTan, ArcCos, ArcSin, Tan, Sin, Cos, Factorial, Negation, Number(f64), OpeningParentheses, ClosingParentheses, } impl Token { /// Returns true if `self` is an instance of a unary operator /// /// # Example ///``` /// let open_bracket = Token::OpeningParentheses; /// let factorial = Token::Factorial; /// /// assert(factorial.is_operator()); /// assert(!open_bracket.is_operator()); ///``` pub fn is_operator(&self) -> bool { match self { Token::Number(_) => false, Token::ClosingParentheses => false, Token::OpeningParentheses => false, _ => true, } } /// Returns true if `self` is an instance of a unary operator /// /// # Example ///``` /// let plus = Token::Plus; /// let factorial = Token::Factorial; /// /// assert(factorial.is_unary_operator()); /// assert(!plus.is_unary_operator()); ///``` pub fn is_unary_operator(&self) -> bool { use Token::*; const UNARY_OPERATORS: [Token; 11] = [ Negation, Factorial, Cos, Sin, Tan, ArcCos, ArcSin, ArcTan, Logarithm, NaturalLogarithm, SquareRoot, ]; UNARY_OPERATORS.contains(&self) } /// Returns true if `self` is an instance of `Token::Number` /// /// # Example ///``` /// let three = Token::Number(3); /// let plus = Token::Plus; /// /// assert!(three.is_number()); /// assert!(!plus.is_number()); ///``` pub fn is_number(&self) -> bool { match self { Token::Number(_) => true, _ => false, } } /// Returns true if `self` has higher precedence than `other` /// /// # Example ///``` /// use Token::*; /// /// assert(SquareRoot.has_higher_precedence_than(Plus)); /// assert(!Tan.has_higher_precedence_than(Negation)); ///``` pub fn has_higher_precedence_than(&self, other: Token) -> bool { use Token::*; const ORDER: [Token; 19] = [ Negation, Factorial, Cos, Sin, Tan, ArcCos, ArcSin, ArcTan, NaturalLogarithm, Logarithm, Permutation, Combination, SquareRoot, Power, Division, Multiplication, Modulo, Plus, Minus, ]; let index_of = |token: Token| { for (i, val) in ORDER.iter().enumerate() { if val == &token { return i as i32; } } return -1; }; if !ORDER.contains(&self) { panic!("Invalid operator: {:?}", self); } if !ORDER.contains(&other) { panic!("Invalid operator: {:?}", other); } index_of(*self) < index_of(other) } }
true
9e2778d9961cbd5235979231d5dc3a6f3f707491
Rust
dumpstr/looper
/src/main.rs
UTF-8
549
4.3125
4
[]
no_license
fn main() { //this just prints "AGANE!!" until stopped /* loop{ println!("AGANE!!"); } */ //counts down from 5 using while loop /* let mut number = 5; while number != 0 { println!("{}!", number); number -= 1; } println!("B L A S T O F F !"); */ //for loop through an array let a = [11, 22, 33, 44, 55]; let mut counter = 0; for element in a.iter() { println!("the value in position {} is: {}", counter, element); counter += 1; } }
true
017842c23fb91d4247c6037eaefad519eb9e2fa6
Rust
royswale/leetcode
/src/bin/maximum-depth-of-binary-tree.rs
UTF-8
891
3.421875
3
[ "MIT" ]
permissive
fn main() {} struct Solution; // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { if root.is_none() { return 0; } let root = root.unwrap(); let left = 1 + Self::max_depth(Rc::clone(&root).borrow_mut().left.take()); let right = 1 + Self::max_depth(Rc::clone(&root).borrow_mut().right.take()); if left > right { left } else { right } } }
true
1bc73d946a8baf97f6bcbecbdac4d31ed01a4876
Rust
Techcable/gc-arena
/src/gc-sequence/src/then.rs
UTF-8
2,484
2.828125
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
use gc_arena::{Collect, MutationContext, StaticCollect}; use crate::Sequence; #[must_use = "sequences do nothing unless stepped"] #[derive(Debug, Collect)] #[collect(no_drop)] pub enum Then<'gc, S, F> where S: Sequence<'gc>, { First(S, Option<StaticCollect<F>>), Second(Option<(S::Output, StaticCollect<F>)>), } impl<'gc, S, F> Then<'gc, S, F> where S: Sequence<'gc>, { pub fn new(s: S, f: F) -> Then<'gc, S, F> { Then::First(s, Some(StaticCollect(f))) } } impl<'gc, S, F, R> Sequence<'gc> for Then<'gc, S, F> where S: Sequence<'gc>, S::Output: Collect, F: 'static + FnOnce(MutationContext<'gc, '_>, S::Output) -> R, { type Output = R; fn step(&mut self, mc: MutationContext<'gc, '_>) -> Option<R> { match self { Then::First(seq, f) => match seq.step(mc) { Some(res) => { *self = Then::Second(Some((res, f.take().unwrap()))); None } None => None, }, Then::Second(sec) => { let (res, f) = sec.take().expect("cannot step a finished sequence"); Some(f.0(mc, res)) } } } } #[must_use = "sequences do nothing unless stepped"] #[derive(Debug, Collect)] #[collect(no_drop)] pub enum ThenWith<'gc, S, C, F> where S: Sequence<'gc>, { First(S, Option<(C, StaticCollect<F>)>), Second(Option<(C, S::Output, StaticCollect<F>)>), } impl<'gc, S, C, F> ThenWith<'gc, S, C, F> where S: Sequence<'gc>, { pub fn new(s: S, c: C, f: F) -> ThenWith<'gc, S, C, F> { ThenWith::First(s, Some((c, StaticCollect(f)))) } } impl<'gc, S, C, F, R> Sequence<'gc> for ThenWith<'gc, S, C, F> where S: Sequence<'gc>, S::Output: Collect, C: Collect, F: 'static + FnOnce(MutationContext<'gc, '_>, C, S::Output) -> R, { type Output = R; fn step(&mut self, mc: MutationContext<'gc, '_>) -> Option<R> { match self { ThenWith::First(seq, cf) => match seq.step(mc) { Some(res) => { let (c, f) = cf.take().unwrap(); *self = ThenWith::Second(Some((c, res, f))); None } None => None, }, ThenWith::Second(sec) => { let (c, res, f) = sec.take().expect("cannot step a finished sequence"); Some(f.0(mc, c, res)) } } } }
true
46161defd25510999ca5c9d3f08ea1244246e58d
Rust
nimiq/core-rs-albatross
/zkp/examples/prover/setup.rs
UTF-8
750
2.546875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::{path::PathBuf, time::Instant}; use nimiq_primitives::networks::NetworkId; use nimiq_zkp_circuits::setup::setup; use rand::thread_rng; /// Generates the parameters (proving and verifying keys) for the entire zkp circuit. /// This function will store the parameters in file. /// Run this example with `cargo run --all-features --release --example setup`. fn main() { println!("====== Parameter generation for ZKP Circuit initiated ======"); let start = Instant::now(); // use the current directory setup(thread_rng(), &PathBuf::new(), NetworkId::DevAlbatross, true).unwrap(); println!("====== Parameter generation for ZKP Circuit finished ======"); println!("Total time elapsed: {:?} seconds", start.elapsed()); }
true
72ef829f6005940dc764d8cfec6d472cb9582fdb
Rust
tyrchen/rust-training
/live_coding/training_code/src/actor.rs
UTF-8
2,204
3.375
3
[]
no_license
use anyhow::Result; use tokio::sync::{mpsc, oneshot}; pub struct Actor<State, Request, Reply> { // receiver side mpsc receiver: mpsc::Receiver<ActorMessage<Request, Reply>>, state: State, } impl<State, Request, Reply> Actor<State, Request, Reply> where State: Default + Send + 'static, Request: HandlCall<Reply = Reply, State = State> + Send + 'static, Reply: Send + 'static, { pub fn spawn(mailbox: usize) -> Pid<Request, Reply> { let (sender, receiver) = mpsc::channel(mailbox); let mut actor: Actor<State, Request, Reply> = Actor { receiver, state: State::default(), }; tokio::spawn(async move { while let Some(msg) = actor.receiver.recv().await { let reply = msg.data.handle_call(&mut actor.state).unwrap(); let _ = msg.sender.send(reply); } }); Pid { sender } } } pub struct ActorMessage<Request, Reply> { data: Request, sender: oneshot::Sender<Reply>, } pub trait HandlCall { type State; type Reply; fn handle_call(&self, state: &mut Self::State) -> Result<Self::Reply>; } #[derive(Debug, Clone)] pub struct Pid<Request, Reply> { sender: mpsc::Sender<ActorMessage<Request, Reply>>, } impl<Request, Reply> Pid<Request, Reply> { pub async fn send(&self, data: Request) -> Result<Reply> { let (sender, receiver) = oneshot::channel(); let msg = ActorMessage { sender, data }; let _ = self.sender.send(msg).await; Ok(receiver.await?) } } #[cfg(test)] mod tests { use super::*; impl HandlCall for usize { type State = usize; type Reply = usize; fn handle_call(&self, state: &mut Self::State) -> Result<Self::Reply> { *state += 1; println!("state: {:?}", *state); Ok(self + 1) } } #[tokio::test] async fn it_works() { let pid: Pid<usize, usize> = Actor::spawn(20); let result = pid.send(42).await.unwrap(); assert_eq!(result, 43); let pid1 = pid.clone(); let result = pid1.send(100).await.unwrap(); assert_eq!(result, 101); } }
true
3f0011ceefafff916f9c2182ceb64120976f4a1f
Rust
eHammarstrom/advent-of-code-2020
/day3/src/main.rs
UTF-8
2,366
3.21875
3
[]
no_license
use std::io::prelude::*; use std::io; fn input_to_string<R: Read>(r: R) -> io::Result<String> { let mut reader = io::BufReader::new(r); let mut data = String::new(); reader.read_to_string(&mut data)?; Ok(data) } fn input_to_matrix(input: &str, (col_len, row_len): (usize, usize)) -> Vec<Vec<bool>> { let mut mat: Vec<Vec<bool>> = vec![Vec::new(); col_len]; let mut input_index = 0; for c in input.chars() { if c == '\n' { continue; } let tree = c == '#'; let col: &mut Vec<bool> = &mut mat[input_index % col_len]; input_index += 1; col.push(tree) } println!("col {}, row {}", mat.len(), mat[0].len()); assert_eq!(mat.len(), col_len); assert_eq!(mat[0].len(), row_len); mat } fn count_row_len(input: &str) -> (usize, usize) { let mut row_len = 0; let mut col_len = 0; for c in input.chars() { if c != '\n' { row_len += 1; } else if col_len == 0 { col_len = row_len; } } (col_len, row_len / col_len) } fn traverse_matrix((col_move, row_move): (usize, usize), matrix: &mut Vec<Vec<bool>>) -> u32 { let bottom = matrix.len(); let mut level = 0; let mut encountered_trees = 0; let mut matrix_expand_index = 0; while level != bottom { /* Grow matrix if needed */ if let None = matrix.get(col_move * level) { for _ in 0..=col_move { let expansion = matrix[matrix_expand_index].to_owned(); matrix.push(expansion); matrix_expand_index += 1; } continue; } println!("pos ({}, {})", col_move * level, row_move * level); let col = &matrix[col_move * level]; let row = col[row_move * level]; if row { encountered_trees += 1; } level += row_move; } encountered_trees } fn main() -> io::Result<()> { let mut input = input_to_string(io::stdin())?; let (col_len, row_len) = count_row_len(&input); println!("col_len {} row_len {}", col_len, row_len); let mut mat = input_to_matrix(&mut input, (col_len, row_len)); let (right, down) = (3, 1); let encountered_trees = traverse_matrix((right, down), &mut mat); println!("Solution A: {}", encountered_trees); Ok(()) }
true
8ccf38a44939fdc92fb3c3b67b258cd6cf7c03cf
Rust
maudnals/wasm-image-operations
/lib-img-operations/src/lib.rs
UTF-8
2,158
2.609375
3
[]
no_license
#![feature(use_extern_macros)] #[macro_use] extern crate stdweb; use stdweb::{ Array, js_export, }; use stdweb::web::{ TypedArray }; #[js_export] fn reduce_sum_u8(arr: TypedArray<u8>) -> u32 { // need vec to iter() (there is no iter() on TypedArray) let vec: Vec<u8> = arr.to_vec(); // need u32 since sum > max(u16) = 65536 // so x needs to be casted // but only primitive types can be cast into each other, so x needs to be dereferenced let sum: u32 = vec.iter().fold(0, |sum, &x| sum as u32 + x as u32); // alternative if no need to cast: vec.iter().sum() return sum; } #[js_export] fn reduce_sum_u8_vec(vec: Vec<u8>) -> u32 { let sum: u32 = vec.iter().fold(0, |sum, &x| sum as u32 + x as u32); return sum; } #[js_export] fn rgbas_to_rgbs(arr: TypedArray<u8>) -> Vec<u8> { let vec: Vec<u8> = arr.to_vec(); let rgbs: Vec<u8> = vec.iter().enumerate().filter(|&(i, _)| (i == 0 || (i + 1) % 4 != 0)).map(|(_, &v)| v).collect::<Vec<_>>(); // .filter(|&(i, _)| (i == 0 || (i + 1) % 4 != 0)).collect::<Vec<u8>>(); return rgbs; } #[js_export] fn avg_vec_f64(vec: Vec<u8>) -> f64 { let len: u32 = vec.len() as u32; let sum: u32 = reduce_sum_u8_vec(vec); let avg: f64 = sum as f64 / len as f64; return avg as f64; } #[js_export] fn avg_rgb_f64(arr: TypedArray<u8>) -> f64 { let rgbs: Vec<u8> = rgbas_to_rgbs(arr); return avg_vec_f64(rgbs); } // #[js_export] // fn avg(arr: TypedArray<u8>) -> u8 { // // gotcha: ownership // // v1 // // let length: u32 = arr.len() as u32; // // let sum: u32 = reduce_sum_u8(arr); // let sum: u32 = reduce_sum_u8_vec(arr.to_vec()); // let len: u32 = arr.len() as u32; // let avg: u32 = sum.wrapping_div(len); // return avg as u8; // } // #[js_export] // fn avg_vec_u8(vec: Vec<u8>) -> u8 { // let len: u32 = vec.len() as u32; // let sum: u32 = reduce_sum_u8_vec(vec); // let avg: u32 = sum.wrapping_div(len); // return avg as u8; // } // #[js_export] // fn avg_rgb_u8(arr: TypedArray<u8>) -> u8 { // let rgbs: Vec<u8> = rgbas_to_rgbs(arr); // return avg_vec_u8(rgbs); // }
true
1b8cbf25994bb459e2428070f21d416a0f260f40
Rust
AndrewMendezLacambra/rust-programming-contest-solutions
/atcoder/abc144_f.rs
UTF-8
2,351
3
3
[]
no_license
fn main() { let s = std::io::stdin(); let mut sc = Scanner { stdin: s.lock() }; let n: usize = sc.read(); let m: usize = sc.read(); let mut graph = vec![vec![]; n]; let mut inverse = vec![vec![]; n]; for _ in 0..m { let a = sc.read::<usize>() - 1; let b = sc.read::<usize>() - 1; graph[a].push(b); inverse[b].push(a); } let probability = calc_probability(&graph, &inverse, (n, n)); let mut ans = probability[0]; for from in 0..n { if graph[from].len() == 1 { continue; } if let Some(&next) = graph[from] .iter() .max_by(|&&next1, &&next2| probability[next1].partial_cmp(&probability[next2]).unwrap()) { let p = calc_probability(&graph, &inverse, (from, next)); if p[0] < ans { ans = p[0]; } } } println!("{}", ans); } fn calc_probability( graph: &Vec<Vec<usize>>, inverse: &Vec<Vec<usize>>, prohibited: (usize, usize), ) -> Vec<f64> { let n = inverse.len(); let mut dp = vec![0.0; n]; for next in (0..n).rev() { for &from in inverse[next].iter() { if (from, next) == prohibited { continue; } let s = if from == prohibited.0 { graph[from].len() as f64 - 1.0 } else { graph[from].len() as f64 }; dp[from] += (dp[next] + 1.0) / s; } } // println!("{:?} dp={:?}", prohibited, dp); dp } pub struct Scanner<R> { stdin: R, } impl<R: std::io::Read> Scanner<R> { pub fn read<T: std::str::FromStr>(&mut self) -> T { use std::io::Read; let buf = self .stdin .by_ref() .bytes() .map(|b| b.unwrap()) .skip_while(|&b| b == b' ' || b == b'\n') .take_while(|&b| b != b' ' && b != b'\n') .collect::<Vec<_>>(); unsafe { std::str::from_utf8_unchecked(&buf) } .parse() .ok() .expect("Parse error.") } pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> { (0..n).map(|_| self.read()).collect() } pub fn chars(&mut self) -> Vec<char> { self.read::<String>().chars().collect() } }
true
7b82c1033dd3e3b757acabf63ab2bd1e8bd2e492
Rust
lavriv92/rust-example
/src/modules/structs.rs
UTF-8
1,376
3.53125
4
[]
no_license
extern crate std; use std::f64::consts::PI; use super::traits::HasArea; pub struct Circle { x: f64, y: f64, radius: f64, } impl Circle { pub fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius } } } pub struct Square { x: f64, y: f64, side: f64, } impl Square { pub fn new(x: f64, y: f64, side: f64) -> Square { Square { x: x, y: y, side: side } } } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } impl HasArea for Square { fn area(&self) -> f64 { self.side * self.side } } pub struct CircleBuilder { x: f64, y: f64, radius: f64, } impl CircleBuilder { pub fn new() -> CircleBuilder { CircleBuilder{x: 0.0, y: 0.0, radius: 1.0} } pub fn x(&mut self, coordinate: f64) -> &mut CircleBuilder { self.x = coordinate; self } pub fn y(&mut self, coordinate: f64) -> &mut CircleBuilder { self.y = coordinate; self } pub fn radius(&mut self, radius: f64) -> &mut CircleBuilder { self.radius = radius; self } pub fn finalize(&self) -> Circle { Circle::new(self.x, self.y, self.radius) } }
true
c24b58cdeba972ac1eb1e14ee5cd1a604a42903d
Rust
jsim2010/market
/src/error.rs
UTF-8
21,673
3.40625
3
[]
no_license
//! Defines the errors that can be thrown by an [`Agent`]. #[cfg(doc)] use crate::{Agent, Consumer, Producer}; use { alloc::string::{String, ToString}, core::{ convert::TryFrom, fmt::{self, Debug, Display, Formatter}, marker::PhantomData, }, fehler::{throw, throws}, never::Never, }; /// Characterizes the kinds of errors that can cause the action of an [`Agent`] to fail. pub trait Flaws { /// Specifies the error caused by the lack of a resource such as a good or stock. /// /// An insufficiency shall be a temporary error; i.e. given that the market is operating under normal conditions, an insufficiency shall eventually be resolved without requiring any extra manipulation of the market. /// /// **NOTE** If implementing [`Display`] for this type, this will generally be displayed as part of [`Fault::Insufficiency`], which will prepend "insufficient " to the display from this type. type Insufficiency; /// Specifies the error caused by an invalid outcome during the action. /// /// A defect is a semi-permanent error; i.e. it shall not be resolved without extra manipulation of the market, if resolution is possible. It is possible that resolution is not possible for a defect. type Defect; } /// Characterizes converting an item into a `T`. /// /// This is functionally the same as [`Into`], but does not include a generic implementation of `T: Blame<T>`. This allows more specific implementations without conflicts. This will be deprecated when specialization is stabilized. pub trait Blame<T> { /// Converts `self` into a `T`. fn blame(self) -> T; } /// Characterizes attempting to convert an item into a `T`. /// /// This is functionally the same as [`core::convert::TryInto`], but does not include a generic implementation of `T: TryBlame<T>`. This allows more specific implementations without conflicts. This will be deprecated when specialization is stabilized. pub trait TryBlame<T> { /// Specifies the error thrown if conversion fails. type Error; /// Attempts to convert `self` into a `T`. #[throws(Self::Error)] fn try_blame(self) -> T; } /// The cause of an [`Agent`] failing to successfully complete an action upon a market. #[non_exhaustive] pub enum Fault<F> where F: Flaws, { /// The action failed due to an insufficiency. Insufficiency(F::Insufficiency), /// The action failed due to a defect. Defect(F::Defect), } impl<F> Fault<F> where F: Flaws, { /// Returns if `self` is a defect. fn is_defect(&self) -> bool { matches!(*self, Self::Defect(_)) } /// If `self` is a defect, converts the defect into `W::Defect`; otherwise returns `self`. fn map_defect<M, W>(self, mut m: M) -> Fault<W> where M: FnMut(F::Defect) -> W::Defect, W: Flaws<Insufficiency = F::Insufficiency>, { match self { Self::Insufficiency(insufficiency) => Fault::Insufficiency(insufficiency), Self::Defect(defect) => Fault::Defect(m(defect)), } } } impl<F, W> Blame<Fault<W>> for Fault<F> where F: Flaws, W: Flaws, W::Insufficiency: From<F::Insufficiency>, W::Defect: From<F::Defect>, { fn blame(self) -> Fault<W> { match self { Fault::Insufficiency(insufficiency) => { Fault::Insufficiency(W::Insufficiency::from(insufficiency)) } Fault::Defect(defect) => Fault::Defect(W::Defect::from(defect)), } } } impl<F> Clone for Fault<F> where F: Flaws, F::Insufficiency: Clone, F::Defect: Clone, { fn clone(&self) -> Self { match *self { Self::Insufficiency(ref insufficiency) => Self::Insufficiency(insufficiency.clone()), Self::Defect(ref defect) => Self::Defect(defect.clone()), } } } impl<F> Copy for Fault<F> where F: Flaws, F::Insufficiency: Copy, F::Defect: Copy, { } impl<F> Debug for Fault<F> where F: Flaws, F::Insufficiency: Debug, F::Defect: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match *self { Self::Insufficiency(ref insufficiency) => { write!(f, "Fault::Insufficiency({:?})", insufficiency) } Self::Defect(ref defect) => write!(f, "Fault::Defect({:?})", defect), } } } impl<F> Display for Fault<F> where F: Flaws, F::Insufficiency: Display, F::Defect: Display, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match *self { Self::Insufficiency(ref insufficiency) => write!(f, "insufficient {}", insufficiency), Self::Defect(ref defect) => write!(f, "{}", defect), } } } impl<F> PartialEq for Fault<F> where F: Flaws, F::Insufficiency: PartialEq, F::Defect: PartialEq, { fn eq(&self, other: &Self) -> bool { match *self { Fault::Insufficiency(ref insufficiency) => { if let Fault::Insufficiency(ref other_insufficiency) = *other { insufficiency == other_insufficiency } else { false } } Fault::Defect(ref defect) => { if let Fault::Defect(ref other_defect) = *other { defect == other_defect } else { false } } } } } impl<F, W> TryBlame<Fault<W>> for Fault<F> where F: Flaws, W: Flaws, W::Insufficiency: TryFrom<F::Insufficiency>, W::Defect: TryFrom<F::Defect>, { type Error = FaultConversionError<W, F>; #[throws(Self::Error)] fn try_blame(self) -> Fault<W> { match self { Fault::Insufficiency(insufficiency) => Fault::Insufficiency( W::Insufficiency::try_from(insufficiency) .map_err(FaultConversionError::Insufficiency)?, ), Fault::Defect(defect) => { Fault::Defect(W::Defect::try_from(defect).map_err(FaultConversionError::Defect)?) } } } } /// The error thrown when the action of an [`Agent`] fails. pub struct Failure<F: Flaws> { /// The description of the [`Agent`]. agent_description: String, /// The cause of the failure. fault: Fault<F>, } impl<F> Failure<F> where F: Flaws, { /// Creates a new [`Failure`] with the description of `agent`and `fault` that caused the failure. pub(crate) fn new<A>(agent: &A, fault: Fault<F>) -> Self where A: Display, { Self { agent_description: agent.to_string(), fault, } } /// Returns if `self` was caused by a defect. pub fn is_defect(&self) -> bool { self.fault.is_defect() } /// If `self` is a defect, converts the defect into `W::Defect`; otherwise returns `self`. pub fn map_defect<M, W>(self, m: M) -> Failure<W> where M: FnMut(F::Defect) -> W::Defect, W: Flaws<Insufficiency = F::Insufficiency>, { Failure { agent_description: self.agent_description, fault: self.fault.map_defect(m), } } } impl<F, W> Blame<Failure<W>> for Failure<F> where F: Flaws, W: Flaws, W::Insufficiency: From<F::Insufficiency>, W::Defect: From<F::Defect>, { fn blame(self) -> Failure<W> { Failure { agent_description: self.agent_description, fault: self.fault.blame(), } } } impl<F: Flaws> Debug for Failure<F> where F::Insufficiency: Debug, F::Defect: Debug, { /// Writes the default debug format for `self`. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("Failure") .field("agent_description", &self.agent_description) .field("fault", &self.fault) .finish() } } impl<F: Flaws> Display for Failure<F> where F::Insufficiency: Display, F::Defect: Display, { /// Writes "{name}: {fault}". fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}: {}", self.agent_description, self.fault) } } #[cfg(feature = "std")] #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "std")))] impl<F: Flaws> std::error::Error for Failure<F> where F::Insufficiency: Debug + Display, F::Defect: Debug + Display, { } impl<F: Flaws> PartialEq for Failure<F> where F::Insufficiency: PartialEq, F::Defect: PartialEq, { fn eq(&self, other: &Self) -> bool { self.agent_description == other.agent_description && self.fault == other.fault } } impl<F: Flaws, W: Flaws> TryBlame<Failure<W>> for Failure<F> where W::Insufficiency: TryFrom<F::Insufficiency>, W::Defect: TryFrom<F::Defect>, { type Error = FailureConversionError<W, F>; #[throws(Self::Error)] fn try_blame(self) -> Failure<W> { match self.fault.try_blame() { Ok(fault) => Failure { agent_description: self.agent_description, fault, }, Err(error) => throw!(FailureConversionError { error, agent_description: self.agent_description }), } } } /// The error thrown when a [`Producer`] fails to produce a good. pub struct Recall<F: Flaws, G> { /// The good that was not produced. good: G, /// The failure. failure: Failure<F>, } impl<F: Flaws, G> Recall<F, G> { /// Creates a new [`Recall`] with the `failure` and `good` that was not produced. pub(crate) fn new(failure: Failure<F>, good: G) -> Self { Self { good, failure } } } impl<F: Flaws, G, W: Flaws, T> Blame<Recall<W, T>> for Recall<F, G> where T: From<G>, W::Insufficiency: From<F::Insufficiency>, W::Defect: From<F::Defect>, { fn blame(self) -> Recall<W, T> { Recall::new(self.failure.blame(), T::from(self.good)) } } impl<F: Flaws, G: Debug> Debug for Recall<F, G> where F::Insufficiency: Debug, F::Defect: Debug, { /// Writes the default debug format for `self`. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("Recall") .field("good", &self.good) .field("failure", &self.failure) .finish() } } impl<F: Flaws, G> Display for Recall<F, G> where F::Insufficiency: Display, F::Defect: Display, G: Display, { /// Writes "`{}` caused recall of goods [{goods}]". fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "`{}` caused recall of good {}", self.failure, self.good) } } #[cfg(feature = "std")] #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "std")))] impl<F: Flaws, G> std::error::Error for Recall<F, G> where F::Insufficiency: Debug + Display, F::Defect: Debug + Display, G: Debug + Display, { } impl<F: Flaws, G> PartialEq for Recall<F, G> where F::Insufficiency: PartialEq, F::Defect: PartialEq, G: PartialEq, { fn eq(&self, other: &Self) -> bool { self.failure == other.failure && self.good == other.good } } impl<F: Flaws, G, W: Flaws, T> TryBlame<Recall<W, T>> for Recall<F, G> where W::Insufficiency: TryFrom<F::Insufficiency>, W::Defect: TryFrom<F::Defect>, T: From<G>, { type Error = RecallConversionError<W, F, G>; #[throws(Self::Error)] fn try_blame(self) -> Recall<W, T> { match self.failure.try_blame() { Ok(failure) => Recall::new(failure, T::from(self.good)), Err(error) => throw!(RecallConversionError { error, good: self.good, }), } } } /// The error thrown when a chain from a [`Consumer`] to a [`Producer`] fails to produce a good. #[non_exhaustive] pub enum Blockage<C, P, G> where C: Flaws, P: Flaws, { /// The action failed due to a failure during consumption. Consumption(Failure<C>), /// The action failed due to a failure during production. Production(Recall<P, G>), } impl<C, P, G> Debug for Blockage<C, P, G> where C: Flaws, C::Insufficiency: Debug, C::Defect: Debug, P: Flaws, P::Insufficiency: Debug, P::Defect: Debug, G: Debug, { /// Writes the default debug format for `self`. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match *self { Self::Consumption(ref failure) => { write!(f, "Blockage::Consumption({:?})", failure) } Self::Production(ref recall) => write!(f, "Blockage::Production({:?})", recall), } } } impl<C, P, G> From<Failure<C>> for Blockage<C, P, G> where C: Flaws, P: Flaws, { fn from(failure: Failure<C>) -> Self { Self::Consumption(failure) } } impl<C, P, G> From<Recall<P, G>> for Blockage<C, P, G> where C: Flaws, P: Flaws, { fn from(recall: Recall<P, G>) -> Self { Self::Production(recall) } } impl<C, P, G> PartialEq for Blockage<C, P, G> where C: Flaws, C::Insufficiency: PartialEq, C::Defect: PartialEq, P: Flaws, P::Insufficiency: PartialEq, P::Defect: PartialEq, G: PartialEq, { fn eq(&self, other: &Self) -> bool { match *self { Self::Consumption(ref my_failure) => { if let Blockage::Consumption(ref their_failure) = *other { my_failure == their_failure } else { false } } Self::Production(ref my_recall) => { if let Blockage::Production(ref their_recall) = *other { my_recall == their_recall } else { false } } } } } /// The error thrown when `Fault::blame()` fails. #[non_exhaustive] pub enum FaultConversionError<F: Flaws, W: Flaws> where F::Insufficiency: TryFrom<W::Insufficiency>, F::Defect: TryFrom<W::Defect>, { /// The failure to convert the insufficiency of `W` to that of `F`. Insufficiency(<F::Insufficiency as TryFrom<W::Insufficiency>>::Error), /// The failure to convert the defect of `W` to that of `F`. Defect(<F::Defect as TryFrom<W::Defect>>::Error), } impl<F: Flaws, W: Flaws> Debug for FaultConversionError<F, W> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Debug, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match *self { Self::Insufficiency(ref insufficiency_error) => { write!(f, "FaultConversionError({:?})", insufficiency_error) } Self::Defect(ref defect_error) => write!(f, "FaultConversionError({:?})", defect_error), } } } impl<F: Flaws, W: Flaws> Display for FaultConversionError<F, W> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Display, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Display, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match *self { Self::Insufficiency(ref insufficiency_error) => { write!(f, "insufficiency conversion - {}", insufficiency_error) } Self::Defect(ref defect_error) => { write!(f, "defect conversion - {}", defect_error) } } } } #[cfg(feature = "std")] #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "std")))] impl<F: Flaws, W: Flaws> std::error::Error for FaultConversionError<F, W> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Debug + Display, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Debug + Display, { } /// The error thrown when `Failure::blame()` fails. pub struct FailureConversionError<F: Flaws, W: Flaws> where F::Insufficiency: TryFrom<W::Insufficiency>, F::Defect: TryFrom<W::Defect>, { /// The error that caused the failure. error: FaultConversionError<F, W>, /// The name of the [`Agent`] that experienced the failure. agent_description: String, } impl<F: Flaws, W: Flaws> Debug for FailureConversionError<F, W> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Debug, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("FailureConversionError") .field("error", &self.error) .field("agent_description", &self.agent_description) .finish() } } impl<F: Flaws, W: Flaws> Display for FailureConversionError<F, W> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Display, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Display, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "in `{}`: {}", self.agent_description, self.error) } } #[cfg(feature = "std")] #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "std")))] impl<F: Flaws, W: Flaws> std::error::Error for FailureConversionError<F, W> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Debug + Display, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Debug + Display, { } /// The error thrown when `Recall::blame()` fails. pub struct RecallConversionError<F: Flaws, W: Flaws, G> where F::Insufficiency: TryFrom<W::Insufficiency>, F::Defect: TryFrom<W::Defect>, { /// The error when converting the [`Failure`]. error: FailureConversionError<F, W>, /// The good in the recall. good: G, } impl<F: Flaws, W: Flaws, G> RecallConversionError<F, W, G> where F::Insufficiency: TryFrom<W::Insufficiency>, F::Defect: TryFrom<W::Defect>, { /// Converts `self` into a `G`. pub fn into_good(self) -> G { self.good } } impl<F: Flaws, W: Flaws, G: Debug> Debug for RecallConversionError<F, W, G> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Debug, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("RecallConversionError") .field("good", &self.good) .field("error", &self.error) .finish() } } impl<F: Flaws, W: Flaws, G> Display for RecallConversionError<F, W, G> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Display, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Display, G: Display, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( f, "{} while converting recall with good {}", self.error, self.good ) } } #[cfg(feature = "std")] #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "std")))] impl<F: Flaws, W: Flaws, G> std::error::Error for RecallConversionError<F, W, G> where F::Insufficiency: TryFrom<W::Insufficiency>, <F::Insufficiency as TryFrom<W::Insufficiency>>::Error: Debug + Display, F::Defect: TryFrom<W::Defect>, <F::Defect as TryFrom<W::Defect>>::Error: Debug + Display, G: Debug + Display, { } /// Signifies a fault that can never occur. pub type Flawless = Never; /// The insufficiency thrown when a [`Producer`] attempts to produce to a market that has no stock available. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] pub struct FullStock; impl Display for FullStock { /// Writes "stock". fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "stock") } } impl Flaws for FullStock { type Insufficiency = Self; type Defect = Flawless; } /// The insufficiency thrown when a [`Consumer`] attempts to consume from a market that has no goods available. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] pub struct EmptyStock; impl Display for EmptyStock { /// Writes "goods". fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "goods") } } impl Flaws for EmptyStock { type Insufficiency = Self; type Defect = Flawless; } /// Specifies the [`Flaws`] of a [`Producer`] producing to a finite market with defects of type `D`. #[derive(Debug)] pub struct ProductionFlaws<D> { /// The type of the defect. defect: PhantomData<D>, } impl<D> Flaws for ProductionFlaws<D> { type Insufficiency = FullStock; type Defect = D; } /// Specifies the [`Flaws`] of a [`Consumer`] consuming from a market with defects of type `D`. #[derive(Debug)] pub struct ConsumptionFlaws<D> { /// The type of the defect. defect: PhantomData<D>, } impl<D> Flaws for ConsumptionFlaws<D> { type Insufficiency = EmptyStock; type Defect = D; } impl Flaws for Flawless { type Insufficiency = Self; type Defect = Self; } impl TryFrom<EmptyStock> for Flawless { type Error = (); fn try_from(_: EmptyStock) -> Result<Self, Self::Error> { Err(()) } } impl TryFrom<FullStock> for Flawless { type Error = (); fn try_from(_: FullStock) -> Result<Self, Self::Error> { Err(()) } }
true
4e9ae7ea47d768bebf98b594934239ddb2520e68
Rust
m9s/xmc1000
/xmc1000/src/port0/phcr1/mod.rs
UTF-8
13,417
2.828125
3
[]
no_license
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::PHCR1 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct PH8R { bits: bool, } impl PH8R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct PH9R { bits: bool, } impl PH9R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct PH10R { bits: bool, } impl PH10R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct PH11R { bits: bool, } impl PH11R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct PH12R { bits: bool, } impl PH12R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct PH13R { bits: bool, } impl PH13R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct PH14R { bits: bool, } impl PH14R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct PH15R { bits: bool, } impl PH15R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _PH8W<'a> { w: &'a mut W, } impl<'a> _PH8W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PH9W<'a> { w: &'a mut W, } impl<'a> _PH9W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PH10W<'a> { w: &'a mut W, } impl<'a> _PH10W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PH11W<'a> { w: &'a mut W, } impl<'a> _PH11W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PH12W<'a> { w: &'a mut W, } impl<'a> _PH12W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PH13W<'a> { w: &'a mut W, } impl<'a> _PH13W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 22; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PH14W<'a> { w: &'a mut W, } impl<'a> _PH14W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 26; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PH15W<'a> { w: &'a mut W, } impl<'a> _PH15W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 30; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 2 - Pad Hysteresis for P0.8"] #[inline] pub fn ph8(&self) -> PH8R { let bits = { const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PH8R { bits } } #[doc = "Bit 6 - Pad Hysteresis for P0.9"] #[inline] pub fn ph9(&self) -> PH9R { let bits = { const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PH9R { bits } } #[doc = "Bit 10 - Pad Hysteresis for P0.10"] #[inline] pub fn ph10(&self) -> PH10R { let bits = { const MASK: bool = true; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PH10R { bits } } #[doc = "Bit 14 - Pad Hysteresis for P0.11"] #[inline] pub fn ph11(&self) -> PH11R { let bits = { const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PH11R { bits } } #[doc = "Bit 18 - Pad Hysteresis for P0.12"] #[inline] pub fn ph12(&self) -> PH12R { let bits = { const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PH12R { bits } } #[doc = "Bit 22 - Pad Hysteresis for P0.13"] #[inline] pub fn ph13(&self) -> PH13R { let bits = { const MASK: bool = true; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PH13R { bits } } #[doc = "Bit 26 - Pad Hysteresis for P0.14"] #[inline] pub fn ph14(&self) -> PH14R { let bits = { const MASK: bool = true; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PH14R { bits } } #[doc = "Bit 30 - Pad Hysteresis for P0.15"] #[inline] pub fn ph15(&self) -> PH15R { let bits = { const MASK: bool = true; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PH15R { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 2 - Pad Hysteresis for P0.8"] #[inline] pub fn ph8(&mut self) -> _PH8W { _PH8W { w: self } } #[doc = "Bit 6 - Pad Hysteresis for P0.9"] #[inline] pub fn ph9(&mut self) -> _PH9W { _PH9W { w: self } } #[doc = "Bit 10 - Pad Hysteresis for P0.10"] #[inline] pub fn ph10(&mut self) -> _PH10W { _PH10W { w: self } } #[doc = "Bit 14 - Pad Hysteresis for P0.11"] #[inline] pub fn ph11(&mut self) -> _PH11W { _PH11W { w: self } } #[doc = "Bit 18 - Pad Hysteresis for P0.12"] #[inline] pub fn ph12(&mut self) -> _PH12W { _PH12W { w: self } } #[doc = "Bit 22 - Pad Hysteresis for P0.13"] #[inline] pub fn ph13(&mut self) -> _PH13W { _PH13W { w: self } } #[doc = "Bit 26 - Pad Hysteresis for P0.14"] #[inline] pub fn ph14(&mut self) -> _PH14W { _PH14W { w: self } } #[doc = "Bit 30 - Pad Hysteresis for P0.15"] #[inline] pub fn ph15(&mut self) -> _PH15W { _PH15W { w: self } } }
true
c16a3ca34ee6d3139af390490132e2c9e2b7f3c8
Rust
PatrickMcSweeny/exercism_solutions
/rust/grains/src/lib.rs
UTF-8
256
3.34375
3
[]
no_license
const SQUARES: u32 = 64; pub fn square(s: u32) -> u64 { if s < 1 || s > SQUARES { panic!("Square must be between 1 and {}", SQUARES); } 2_u64.pow(s - 1) } pub fn total() -> u64 { (1..=SQUARES).map(|number| square(number)).sum() }
true
6f701516bf64bc071a5c7fd3facd3c5dfcc72cda
Rust
briansunter/Rust-webapp-starter
/src/utils/error.rs
UTF-8
3,019
3.109375
3
[ "Apache-2.0" ]
permissive
use std::result; use std::io; use std::fmt; use std::error; use std::num; use utils::jwt; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub enum Error { IoError(io::Error), CodedError(ErrorCode), TokenError(jwt::Error), ParseIntError(num::ParseIntError), Message(String) } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IoError(err) } } impl From<ErrorCode> for Error { fn from(err: ErrorCode) -> Error { Error::CodedError(err) } } impl From<jwt::Error> for Error { fn from(err: jwt::Error) -> Error { Error::TokenError(err) } } impl From<num::ParseIntError> for Error { fn from(err: num::ParseIntError) -> Error { Error::ParseIntError(err) } } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Error::IoError(ref inner) => inner.fmt(fmt), Error::CodedError(ref inner) => inner.fmt(fmt), Error::TokenError(ref inner) => inner.fmt(fmt), Error::ParseIntError(ref inner) => inner.fmt(fmt), Error::Message(ref inner) => inner.fmt(fmt) } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::IoError(ref err) => err.description(), Error::CodedError(ref err) => err.to_str(), Error::TokenError(ref err) => err.description(), Error::ParseIntError(ref err) => err.description(), Error::Message(ref err) => err } } fn cause(&self) -> Option<&error::Error> { match *self { Error::IoError(ref err) => Some(err), Error::CodedError(_) => None, Error::TokenError(ref err) => Some(err), Error::ParseIntError(ref err) => Some(err), Error::Message(_) => None } } } #[derive(Eq, PartialEq, Clone, Debug, Ord, PartialOrd)] pub struct ErrorCode(pub u16); impl ErrorCode { pub fn to_str(&self) -> &str { match self.0 { 10004 => "No resources", 10005 => "No auth", 20001 => "Login time over", 20002 => "Erroe username or password", 20003 => "No user", 30001 => "No article", _ => "Error Unknow" } } pub fn to_code(&self) -> u16 { self.0 } } impl From<i16> for ErrorCode { fn from(in_code: i16) -> ErrorCode { ErrorCode(in_code as u16) } } impl From<u16> for ErrorCode { fn from(in_code: u16) -> ErrorCode { ErrorCode(in_code) } } impl From<i32> for ErrorCode { fn from(in_code: i32) -> ErrorCode { ErrorCode(in_code as u16) } } impl From<u32> for ErrorCode { fn from(in_code: u32) -> ErrorCode { ErrorCode(in_code as u16) } } impl fmt::Display for ErrorCode { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(self.to_str()) } }
true
7cd6f534e6813139bac61e2400d4d23bae9e7790
Rust
Vrixyz/rusttd
/src/math_utils.rs
UTF-8
892
3.453125
3
[ "MIT" ]
permissive
use bevy::math::Vec3; pub fn move_towards(current: Vec3, target: Vec3, max_distance_delta: f32) -> Vec3 { let to_vector = target - current; let sqdist = target.distance_squared(current); if sqdist == 0.0 || (max_distance_delta >= 0.0 && sqdist <= max_distance_delta.powf(2.0)) { return target; } let dist = sqdist.sqrt(); current + to_vector / dist * max_distance_delta } #[cfg(test)] mod test { use super::*; #[test] fn move_towards_done() { let dest = Vec3::new(1.0, 0.0, 0.0); assert_eq!(move_towards(Vec3::new(0.0, 0.0, 0.0), dest, 1.0), dest); } #[test] fn move_towards_not_done() { let target = Vec3::new(3.0, 0.0, 0.0); let actual_dest = Vec3::new(2.0, 0.0, 0.0); assert_eq!( move_towards(Vec3::new(0.0, 0.0, 0.0), target, 2.0), actual_dest ); } }
true
1aec046c8a915b7fc4ff8cc32b61ec6e5e360f65
Rust
iotaledger/bee
/bee-protocol/bee-protocol/src/peer/packet_handler.rs
UTF-8
12,628
3.015625
3
[ "Apache-2.0" ]
permissive
// Copyright 2020-2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use bee_gossip::Multiaddr; use futures::{ channel::oneshot, future::{self, FutureExt}, stream::StreamExt, }; use log::trace; use tokio::select; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::packets::{HeaderPacket, HEADER_SIZE}; type EventRecv = UnboundedReceiverStream<Vec<u8>>; type ShutdownRecv = future::Fuse<oneshot::Receiver<()>>; /// The read state of the packet handler. /// /// This type is used by `PacketHandler` to decide what should be read next when handling an /// event. enum ReadState { /// `PacketHandler` should read a header. Header, /// `PacketHandler` should read a payload based on a header. Payload(HeaderPacket), } /// A packet handler. /// /// It takes care of processing events into packets that can be processed by the workers. pub(super) struct PacketHandler { events: EventHandler, // FIXME: see if we can implement `Stream` for the `PacketHandler` and use the // `ShutdownStream` type instead. shutdown: ShutdownRecv, state: ReadState, /// The address of the peer. This field is only here for logging purposes. address: Multiaddr, } impl PacketHandler { /// Create a new packet handler from an event receiver, a shutdown receiver and the peer's /// address. pub(super) fn new(receiver: EventRecv, shutdown: ShutdownRecv, address: Multiaddr) -> Self { Self { events: EventHandler::new(receiver), shutdown, // The handler should read a header first. state: ReadState::Header, address, } } /// Fetch the header and payload of a packet. /// /// This method only returns `None` if a shutdown signal is received. pub(super) async fn fetch_packet(&mut self) -> Option<(HeaderPacket, &[u8])> { // loop until we can return the header and payload loop { match &self.state { // Read a header. ReadState::Header => { // We need `HEADER_SIZE` bytes to read a header. let bytes = self .events .fetch_bytes_or_shutdown(&mut self.shutdown, HEADER_SIZE) .await?; trace!("[{}] Reading Header...", self.address); // This never panics because we fetch exactly `HEADER_SIZE` bytes. let header = HeaderPacket::from_bytes(bytes.try_into().unwrap()); // Now we are ready to read a payload. self.state = ReadState::Payload(header); } // Read a payload. ReadState::Payload(header) => { // We read the quantity of bytes stated by the header. let bytes = self .events .fetch_bytes_or_shutdown(&mut self.shutdown, header.packet_length.into()) .await?; // FIXME: Avoid this clone let header = header.clone(); // Now we are ready to read the next packet's header. self.state = ReadState::Header; // We return the current packet's header and payload. return Some((header, bytes)); } } } } } // An event handler. // // This type takes care of actually receiving the events and appending them to an inner buffer so // they can be used seamlessly by the `PacketHandler`. struct EventHandler { receiver: EventRecv, buffer: Vec<u8>, offset: usize, } impl EventHandler { /// Create a new event handler from an event receiver. fn new(receiver: EventRecv) -> Self { Self { receiver, buffer: vec![], offset: 0, } } /// Push a new event into the buffer. /// /// This method also removes the `..self.offset` range from the buffer and sets the offset back /// to zero. Which means that this should only be called when the buffer is empty or when there /// are not enough bytes to read a new header or payload. fn push_event(&mut self, mut bytes: Vec<u8>) { // Remove the already read bytes from the buffer. self.buffer = self.buffer.split_off(self.offset); // Reset the offset. self.offset = 0; // Append the bytes of the new event self.buffer.append(&mut bytes); } /// Fetch a slice of bytes of a determined length. /// /// The future returned by this method will be ready until there are enough bytes to fulfill /// the request. async fn fetch_bytes(&mut self, len: usize) -> &[u8] { // We need to be sure that we have enough bytes in the buffer. while self.offset + len > self.buffer.len() { // If there are not enough bytes in the buffer, we must receive new events if let Some(event) = self.receiver.next().await { // If we received an event, we push it to the buffer. self.push_event(event); } } // Get the requested bytes. This will not panic because the loop above only exists if we // have enough bytes to do this step. let bytes = &self.buffer[self.offset..][..len]; // Increase the offset by the length of the byte slice. self.offset += len; bytes } /// Helper method to be able to shutdown when fetching bytes for a packet. /// /// This method returns `None` if a shutdown signal is received, otherwise it returns the /// requested bytes. async fn fetch_bytes_or_shutdown(&mut self, shutdown: &mut ShutdownRecv, len: usize) -> Option<&'_ [u8]> { select! { // Always select `shutdown` first, otherwise you can end with an infinite loop. _ = shutdown => None, bytes = self.fetch_bytes(len).fuse() => Some(bytes), } } } #[cfg(test)] mod tests { use std::time::Duration; use futures::{channel::oneshot, future::FutureExt}; use tokio::{spawn, sync::mpsc, time::sleep}; use tokio_stream::wrappers::UnboundedReceiverStream; use super::*; /// Generate a vector of events filled with packets of a desired length. fn gen_events(event_len: usize, msg_size: usize, n_msg: usize) -> Vec<Vec<u8>> { // Bytes of all the packets. let mut msgs = vec![0u8; msg_size * n_msg]; // We need 3 bytes for the header. Thus the packet length stored in the header should be 3 // bytes shorter. let msg_len = ((msg_size - 3) as u16).to_le_bytes(); // We write the bytes that correspond to the packet length in the header. for i in (0..n_msg).map(|i| i * msg_size + 1) { msgs[i] = msg_len[0]; msgs[i + 1] = msg_len[1]; } // Finally, we split all the bytes into events. msgs.chunks(event_len).map(Vec::from).collect() } /// Test if the `PacketHandler` can produce an exact number of packets of a desired length, /// divided in events of an specified length. This test checks that: /// - The header and payload of all the packets have the right content. /// - The number of produced packets is the desired one. async fn test(event_size: usize, msg_size: usize, msg_count: usize) { let msg_len = msg_size - 3; // Produce the events let events = gen_events(event_size, msg_size, msg_count); // Create a new packet handler let (sender_shutdown, receiver_shutdown) = oneshot::channel::<()>(); let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>(); let mut msg_handler = PacketHandler::new( UnboundedReceiverStream::new(receiver), receiver_shutdown.fuse(), "/ip4/0.0.0.0/tcp/8080".parse().unwrap(), ); // Create the task that does the checks of the test. let handle = spawn(async move { // The packets are expected to be filled with zeroes except for the packet length // field of the header. let expected_bytes = vec![0u8; msg_len]; let expected_msg = ( HeaderPacket { packet_type: 0, packet_length: msg_len as u16, }, expected_bytes.as_slice(), ); // Count how many packets can be fetched. let mut counter = 0; while let Some(msg) = msg_handler.fetch_packet().await { // Assert that the packets' content is correct. assert_eq!(msg, expected_msg); counter += 1; } // Assert that the number of packets is correct. assert_eq!(msg_count, counter); // Return back the packet handler to avoid dropping the channels. msg_handler }); // Send all the events to the packet handler. for event in events { sender.send(event).unwrap(); sleep(Duration::from_millis(1)).await; } // Sleep to be sure the handler had time to produce all the packets. sleep(Duration::from_millis(1)).await; // Send a shutdown signal. sender_shutdown.send(()).unwrap(); // Await for the task with the checks to be completed. assert!(handle.await.is_ok()); } /// Test that packets are produced correctly when they are divided into one byte events. #[tokio::test] async fn one_byte_events() { test(1, 5, 10).await; } /// Test that packets are produced correctly when each mes// let peer_id: PeerId = /// Url::from_url_str("tcp://[::1]:16000").await.unwrap().into();sage fits exactly into an event. #[tokio::test] async fn one_packet_per_event() { test(5, 5, 10).await; } /// Test that packets are produced correctly when two packets fit exactly into an event. #[tokio::test] async fn two_packets_per_event() { test(10, 5, 10).await; } /// Test that packets are produced correctly when a packet fits exactly into two events. #[tokio::test] async fn two_events_per_packet() { test(5, 10, 10).await; } /// Test that packets are produced correctly when a packet does not fit in a single event and /// it is not aligned either. #[tokio::test] async fn misaligned_packets() { test(3, 5, 10).await; } /// Test that the handler stops producing packets after receiving the shutdown signal. /// /// This test is basically the same as the `one_packet_per_event` test. But the last event is /// sent after the shutdown signal. As a consequence, the last packet is not produced by the /// packet handler. #[tokio::test] async fn shutdown() { let event_size = 5; let msg_size = event_size; let msg_count = 10; let msg_len = msg_size - 3; let mut events = gen_events(event_size, msg_size, msg_count); // Put the last event into its own variable. let last_event = events.pop().unwrap(); let (sender_shutdown, receiver_shutdown) = oneshot::channel::<()>(); let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>(); let mut msg_handler = PacketHandler::new( UnboundedReceiverStream::new(receiver), receiver_shutdown.fuse(), "/ip4/0.0.0.0/tcp/8080".parse().unwrap(), ); let handle = spawn(async move { let expected_bytes = vec![0u8; msg_len]; let expected_msg = ( HeaderPacket { packet_type: 0, packet_length: msg_len as u16, }, expected_bytes.as_slice(), ); let mut counter = 0; while let Some(msg) = msg_handler.fetch_packet().await { assert_eq!(msg, expected_msg); counter += 1; } // Assert that we are missing one packet. assert_eq!(msg_count - 1, counter); msg_handler }); for event in events { sender.send(event).unwrap(); sleep(Duration::from_millis(1)).await; } sender_shutdown.send(()).unwrap(); sleep(Duration::from_millis(1)).await; // Send the last event after the shutdown signal sender.send(last_event).unwrap(); assert!(handle.await.is_ok()); } }
true
38278499fdc999354eb81889cb1b830dd3f00342
Rust
LinAGKar/advent-of-code-2018-rust
/day21b-hardcode/src/main.rs
UTF-8
936
2.96875
3
[ "MIT" ]
permissive
use std::collections::HashSet; use std::io::Read; fn main() { let mut input = String::new(); std::io::stdin().read_to_string(&mut input).unwrap(); let mut constants = input.lines().skip(1).map(|line| line.split_whitespace()); let val_start: u64 = constants.nth(7).unwrap().nth(1).unwrap().parse().unwrap(); let factor: u64 = constants.nth(3).unwrap().nth(2).unwrap().parse().unwrap(); let mut val = 0; let mut last_new = 0; let mut seen = HashSet::new(); loop { let mut val2 = val | 0x10000; val = val_start; loop { val = (val + (val2 & 0xFF) & 0xFFFFFF) * factor & 0xFFFFFF; if 0x100 > val2 { break; } val2 >>= 8; } if seen.contains(&val) { println!("{}", last_new); break; } else { last_new = val; seen.insert(val); } } }
true
5664b0d8ec99fa5d0351c35db4c0873f166c29d0
Rust
y-yagi/til
/leetcode/sort-integers-by-the-number-of-1-bits/rust/src/lib.rs
UTF-8
446
3.484375
3
[]
no_license
#[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!( Solution::sort_by_bits(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]), vec![0, 1, 2, 4, 8, 3, 5, 6, 7] ); } } struct Solution {} impl Solution { pub fn sort_by_bits(arr: Vec<i32>) -> Vec<i32> { let mut arr = arr; arr.sort_by(|a, b| a.count_ones().cmp(&b.count_ones()).then(a.cmp(&b))); arr } }
true
3cf944b11bd0aa9b2614fde0e31731d8ca63ae5d
Rust
lemonrock/file-descriptors
/src/posix_message_queues/OpenOrCreatePosixMessageQueue.rs
UTF-8
4,163
2.625
3
[ "MIT" ]
permissive
// This file is part of file-descriptors. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/file-descriptors/master/COPYRIGHT. No part of file-descriptors, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2018-2019 The developers of file-descriptors. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/file-descriptors/master/COPYRIGHT. /// How to open or create (or both) a message queue. #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] pub enum OpenOrCreatePosixMessageQueue { /// Opens the queue if it already exists; fails if it does not. OpenIfAlreadyExistsOrFail, /// Opens the queue if it already exists; creates (and implicitly opens) it is it does not. OpenOrCreateIfDoesNotExist(PosixMessageQueueCreateSettings), /// Creates (and implicitly opens) the queue if it does not already exist; fails if it does exist. CreateIfItDoesNotExistOrFail(PosixMessageQueueCreateSettings), } impl OpenOrCreatePosixMessageQueue { #[inline(always)] pub(crate) fn invoke_mq_open(&self, send_or_receive: PosixMessageQueueCreateSendOrReceive, name: &CStr) -> Result<PosixMessageQueueFileDescriptor, CreationError> { PosixMessageQueueFileDescriptor::guard_name(name); use self::OpenOrCreatePosixMessageQueue::*; let oflag = send_or_receive as i32; let name_pointer = name.as_ptr(); use self::CreationError::*; match self { &OpenIfAlreadyExistsOrFail => { let result = unsafe { mq_open(name_pointer, oflag) }; if likely!(result >= 0) { Ok(PosixMessageQueueFileDescriptor(result)) } else if likely!(result == 0) { Err ( match errno().0 { EACCES => PermissionDenied, EMFILE => PerProcessLimitOnNumberOfFileDescriptorsWouldBeExceeded, ENFILE | ENOSPC => SystemWideLimitOnTotalNumberOfFileDescriptorsWouldBeExceeded, ENOMEM => KernelWouldBeOutOfMemory, ENOENT => panic!("No queue with this name exists"), ENAMETOOLONG => panic!("`name` is too long"), EINVAL => panic!("`name` is invalid in some way"), _ => unreachable!(), } ) } else { unreachable!(); } } &OpenOrCreateIfDoesNotExist(ref create_settings) => { let result = create_settings.invoke_mq_open(name_pointer, oflag | O_CREAT); if likely!(result >= 0) { Ok(PosixMessageQueueFileDescriptor(result)) } else if likely!(result == 0) { Err ( match errno().0 { EACCES => PermissionDenied, EMFILE => PerProcessLimitOnNumberOfFileDescriptorsWouldBeExceeded, ENFILE | ENOSPC => SystemWideLimitOnTotalNumberOfFileDescriptorsWouldBeExceeded, ENOMEM => KernelWouldBeOutOfMemory, EINVAL => PermissionDenied, ENOENT => panic!("`name` was just \"/\" followed by no other characters"), ENAMETOOLONG => panic!("`name` is too long"), _ => unreachable!(), } ) } else { unreachable!(); } } &CreateIfItDoesNotExistOrFail(ref create_settings) => { let result = create_settings.invoke_mq_open(name_pointer, oflag | O_CREAT | O_EXCL); if likely!(result >= 0) { Ok(PosixMessageQueueFileDescriptor(result)) } else if likely!(result == 0) { Err ( match errno().0 { EACCES => PermissionDenied, EMFILE => PerProcessLimitOnNumberOfFileDescriptorsWouldBeExceeded, ENFILE | ENOSPC => SystemWideLimitOnTotalNumberOfFileDescriptorsWouldBeExceeded, ENOMEM => KernelWouldBeOutOfMemory, EINVAL => PermissionDenied, ENOENT => panic!("`name` was just \"/\" followed by no other characters"), ENAMETOOLONG => panic!("`name` is too long"), EEXIST => panic!("queue already exists"), _ => unreachable!(), } ) } else { unreachable!(); } } } } }
true
1a5473e4b08ff80250c59ab817fe6837c4896c41
Rust
ymgyt/kvsd
/src/core/principal/mod.rs
UTF-8
248
2.640625
3
[ "MIT" ]
permissive
mod user; pub(crate) use user::User; #[derive(Debug, Clone)] pub(crate) enum Principal { AnonymousUser, User(User), } impl Principal { pub(crate) fn is_authenticated(&self) -> bool { matches!(self, Principal::User(_)) } }
true
3d3af12ba055277cc7a9728f3e52781633f45fc2
Rust
mbacch/max31855
/examples/linux_raspi.rs
UTF-8
956
2.625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
extern crate linux_embedded_hal as hal; extern crate max31855; use std::thread; use std::time::Duration; use max31855::{Max31855, Units}; use hal::spidev::{self, SpidevOptions}; use hal::{Pin, Spidev}; use hal::sysfs_gpio::Direction; fn main() { /* Configure SPI */ let mut spi = Spidev::open("/dev/spidev0.0").unwrap(); let options = SpidevOptions::new() .bits_per_word(8) .max_speed_hz(1_000_000) .mode(spidev::SPI_MODE_0) .build(); spi.configure(&options).unwrap(); /* Configure Digital I/O Pin to be used as Chip Select */ let cs = Pin::new(4); cs.export().unwrap(); while !cs.is_exported() {} cs.set_direction(Direction::Out).unwrap(); cs.set_value(1).unwrap(); let mut max31855 = Max31855::new(spi, cs).unwrap(); loop { println!("{:?}", max31855.read_thermocouple(Units::Fahrenheit).unwrap()); thread::sleep(Duration::from_millis(1000)); } }
true
5747f231766920cdf696ac237920cbce1639c6ee
Rust
arti4109-arquitectura-de-software/g2-reto1-2020-01-mati-g2
/src/engine/mod.rs
UTF-8
5,506
2.765625
3
[]
no_license
pub mod engine_bheap; pub mod engine_btree; pub mod engine_keyedheap; pub mod offer_ord; use crate::offers::{Offer, OfferEvent, OfferEventKeyed, OfferKey, Side}; use crossbeam_channel::{self, Receiver, Sender}; #[derive(Debug)] pub enum MatchResult { Complete, Partial { offer: Offer, to_substract: u64 }, None, } #[derive(Debug)] pub struct Matches { pub result: MatchResult, pub completed: Vec<Offer>, } pub trait EngineDataStruct : Sized{ fn match_offer( &mut self, matches: &mut Vec<Offer>, offer: Offer, other: &mut Self, ) -> MatchResult; fn delete_key(&mut self, key: &OfferKey) -> bool; fn with_capacity(capacity: usize) -> Self; } pub struct Engine<T> where T: EngineDataStruct, { sell_offers: T, // market_sell_offers: Vec<MarketEngineOffer>, buy_offers: T, // market_buy_offers: Vec<MarketEngineOffer>, matches: Vec<Offer>, receiver: Receiver<OfferEventKeyed>, sender: Sender<Matches>, } impl<T> Engine<T> where T: EngineDataStruct, { pub fn new(receiver: Receiver<OfferEventKeyed>, sender: Sender<Matches>) -> Self { Engine { sell_offers: T::with_capacity(24), // market_sell_offers: Vec::with_capacity(24), buy_offers: T::with_capacity(24), // market_buy_offers: Vec::with_capacity(24), matches: Vec::with_capacity(24), sender, receiver, } } pub fn start(&mut self, count : usize) { let mut counter = 0; while let Ok(offer) = self.receiver.recv() { match offer{ OfferEventKeyed::Add(key, value)=>{ let offer = Offer{ key, value }; let matches = self.process_offer(offer); if let MatchResult::None = matches.result { println!("{}", counter); continue; } self.sender.send(matches).unwrap(); counter += 1; if counter % 50 == 0 { println!("{}", counter); } if count == counter { self.sender .send(Matches { completed: Vec::new(), result: MatchResult::None, }) .unwrap(); return; } }, OfferEventKeyed::Delete(_, k)=>{ self.delete_offer(&k); } } } } pub fn process_offer(&mut self, offer: Offer) -> Matches { let (same_offers, opposite_offers) = match offer.value.side { Side::Buy => (&mut self.buy_offers, &mut self.sell_offers), Side::Sell => (&mut self.sell_offers, &mut self.buy_offers), }; let result = opposite_offers.match_offer(&mut self.matches, offer, same_offers); let completed: Vec<_> = self.matches.drain(..self.matches.len()).collect(); Matches { completed, result } } pub fn delete_offer(&mut self, key: &OfferKey){ let c = self.buy_offers.delete_key(key); } } // #[derive(Clone, Debug)] // pub struct EngineOffer { // side: Side, // price: Option<u64>, // key: u64, // amount: u64, // } // // pub struct MarketEngineOffer { // // key: u64, // // amount: u64, // // } // impl From<Offer> for EngineOffer { // fn from(offer: Offer) -> Self { // EngineOffer { // side: offer.value.side, // price: offer.value.price, // .and_then(|v| Some(f64_to_u64(v))), // amount: offer.value.amount, //f64_to_u64(offer.value.amount.abs()), // key: u64::from_be_bytes(*offer.key.as_ref()), // } // } // } // impl Eq for EngineOffer {} // impl PartialEq for EngineOffer { // fn eq(&self, other: &Self) -> bool { // self.key == other.key // } // } // impl PartialOrd for EngineOffer { // fn partial_cmp(&self, other: &Self) -> Option<Ordering> { // Some(self.cmp(other)) // } // } // impl Ord for EngineOffer { // fn cmp(&self, other: &Self) -> std::cmp::Ordering { // match self.side { // Side::Buy => match self.price { // Some(price) => match other.price { // Some(price_other) => price // .cmp(&price_other) // .then_with(|| self.key.cmp(&other.key)), // None => Greater, // }, // None => match other.price { // Some(_price_other) => Less, // None => self.key.cmp(&other.key), // }, // }, // Side::Sell => match self.price { // Some(price) => match other.price { // Some(price_other) => price_other // .cmp(&price) // .then_with(|| self.key.cmp(&other.key)), // None => Greater, // }, // None => match other.price { // Some(_price_other) => Less, // None => self.key.cmp(&other.key), // }, // }, // } // } // }
true
0657dfb0b4c1357c16f41fe014c0584d2512a77d
Rust
NjinN/Mo
/src/lang/msolver.rs
UTF-8
6,917
2.59375
3
[]
no_license
use std::collections::HashSet; use std::sync::{Arc, RwLock}; use std::time::{Duration, SystemTime}; use crate::*; use crate::lang::*; pub fn bind_ctx(list: &mut Vec<PMtoken>, ctx: PMctx){ bind_ctx_raw(list, ctx.clone(), HashSet::new()) } pub fn bind_ctx_local(list: &mut Vec<PMtoken>, ctx: PMctx, local: HashSet<String>){ bind_ctx_raw(list, ctx.clone(), local) } pub fn bind_ctx_raw(list: &mut Vec<PMtoken>, ctx: PMctx, local: HashSet<String>){ let mut put_word_set = local; for item in list.iter() { match &mut *raw_mut!(item) { Mtoken::Word{v} | Mtoken::SetWord{v} => { let bind = ctx.get_with_ctx(v.k.clone()); if bind.0.is_nil(){ if put_word_set.contains(&(v.k.clone())){ v.c = None; }else{ v.c = Some(ctx.clone()); } }else{ v.c = Some(bind.1.clone()) } }, Mtoken::Call{v} => { let bind = ctx.get_with_ctx(v.callee.clone()); if bind.0.is_nil() { if put_word_set.contains(&(v.callee.clone())){ v.ctx = None; }else{ v.ctx = Some(ctx.clone()); } }else{ v.ctx = Some(ctx.clone()); } }, _ => {}, } } } pub struct Msolver { pub inp: Vec<PMtoken>, pub inp_len: usize, pub idx: usize, pub now_tk: PMtoken, pub next_tk: PMtoken, } impl Msolver { pub fn solver_eval_str(code: String, ctx: PMctx)-> PMtoken{ let inp = to_tokens(code, ctx.clone()); Msolver::new(inp).eval_blk(ctx) } pub fn solver_eval(inp: Vec<PMtoken>, ctx: PMctx)-> PMtoken{ Msolver::new(inp).eval_blk(ctx) } pub fn solver_reduce_str(code: String, ctx: PMctx)-> Vec<PMtoken>{ let inp = to_tokens(code, ctx.clone()); Msolver::new(inp).reduce_blk(ctx) } pub fn solver_reduce(inp: Vec<PMtoken>, ctx: PMctx)-> Vec<PMtoken>{ Msolver::new(inp).reduce_blk(ctx) } pub fn new(inp: Vec<PMtoken>)-> Msolver{ let inp_len = inp.len(); Msolver{ inp: inp, inp_len: inp_len, idx: 0, now_tk: PMtoken::new_nil(), next_tk: PMtoken::new_nil(), } } pub fn pre_read(&mut self, ctx: PMctx){ if self.idx >= self.inp_len { return } if !self.next_tk.is_nil() { self.now_tk = self.next_tk.clone(); }else{ self.now_tk = self.inp.get(self.idx).unwrap().clone().get_val(ctx.clone()); // now_tk.echo(); } if self.idx < self.inp_len - 1 { self.next_tk = self.inp.get(self.idx+1).unwrap().clone().get_val(ctx.clone()); // next_tk.echo(); } self.idx += 1 } pub fn eval_blk(&mut self, ctx: PMctx)-> PMtoken{ let mut temp = PMtoken::new_nil(); while self.idx < self.inp_len { temp = self.eval_one(ctx.clone(), true) } return temp } pub fn reduce_blk(&mut self, ctx: PMctx)-> Vec<PMtoken>{ let mut result: Vec<PMtoken> = Vec::new(); while self.idx < self.inp_len { result.push(self.eval_one(ctx.clone(), true)) } return result } pub fn eval_one(&mut self, ctx: PMctx, pre_read: bool)-> PMtoken{ if pre_read { self.pre_read(ctx.clone()); } if self.now_tk.is_set_word(){ let k = raw_set_word!(self.now_tk).k.clone(); let v = self.eval_one(ctx.clone(), true); ctx.clone().put(k, v.clone()); self.pre_read(ctx.clone()); return v }else if self.now_tk.is_set_func(){ let set_func = raw_set_func!(self.now_tk.clone()); self.pre_read(ctx.clone()); return set_func.dim_func(self.now_tk.clone(), ctx.clone()) }else if self.next_tk.is_op(){ let arg_l = self.now_tk.clone(); let op = self.next_tk.clone(); self.pre_read(ctx.clone()); self.pre_read(ctx.clone()); let arg_r = self.now_tk.clone(); let op_args = vec![arg_l, arg_r]; let temp: PMtoken; match &mut *raw_mut!(op){ Mtoken::Op{v} => { v.paren = PMtoken::new_paren(op_args); temp = v.run(ctx.clone()) }, _ => return PMtoken::new_err("Error grammar!".to_string()), } if self.next_tk.is_op(){ self.now_tk = temp; return self.eval_one(ctx.clone(), false) }else{ return temp } } let result = self.now_tk.clone(); // self.pre_read(ctx.clone()); return result } } // pub fn eval_str(code: String, ctx: PMctx)-> PMtoken{ // eval_blk(to_tokens(code, ctx.clone()), ctx) // } // pub fn eval_blk(inp: Vec<PMtoken>, ctx: PMctx)-> PMtoken{ // let mut now_tk = PMtoken::new_nil(); // let mut next_tk = PMtoken::new_nil(); // let mut i = 0; // while i < inp.len() { // if !next_tk.is_nil() { // now_tk = next_tk.clone(); // // if now_tk.is_word(){ // // // now_tk.echo(); // // now_tk = now_tk.get_word_val(ctx.clone()); // // } // }else{ // now_tk = inp.get(i).unwrap().clone().get_val(ctx.clone()); // // now_tk.echo(); // } // if i < inp.len() - 1 { // next_tk = inp.get(i+1).unwrap().clone().get_val(ctx.clone()); // // next_tk.echo(); // } // } // PMtoken::new_nil() // } // pub fn eval_one(inp: &Vec<PMtoken>, ctx: PMctx, idx: &mut i32, now_tk: PMtoken, next_tk: PMtoken)-> PMtoken{ // if now_tk.is_set_word() { // } // if next_tk.is_op(){ // } // PMtoken::new_nil() // } // pub fn eval_op(inp: &Vec<PMtoken>, ctx: PMctx, idx: &mut i32, op: PMtoken, op_l: PMtoken)-> PMtoken{ // let mut now_tk = PMtoken::new_nil(); // let mut next_tk = PMtoken::new_nil(); // let inp_len = inp.len() as i32; // *idx += 1; // if *idx < inp_len { // now_tk = inp.get(*idx as usize).unwrap().clone().get_val(ctx.clone()); // }else{ // return PMtoken::new_err("Incomplete Op Expr".to_string()) // } // if *idx < inp_len - 1 { // next_tk = inp.get((*idx + 1) as usize).unwrap().clone().get_val(ctx.clone()); // } // if next_tk.is_op(){ // }else{ // } // PMtoken::new_nil() // }
true
0d75326378625eeb2578c8c5dee9b77bbd432d69
Rust
ray33ee/Native-Regex
/src/main.rs
UTF-8
3,770
2.953125
3
[ "MIT" ]
permissive
use clap::{Arg, App, crate_version, crate_authors}; use std::fs::OpenOptions; use std::io::Write; use native_regex_lib::rust_translate; fn main() -> Result<(), String> { let matches = App::new("Native Regex") .version(crate_version!()) .author(crate_authors!()) .about("Tool for converting regexes into source code") .arg(Arg::with_name("file") .short("f") .long("file") .help("File to output source code to") .required(false) .validator(|file_name| { if file_name.is_empty() { Err(String::from("Please enter a valid file name")) } else { Ok(()) } }) .takes_value(true)) .arg(Arg::with_name("regex") .short("r").long("regex") .help("The regex to convert into source") .validator(|regex| { match regex::Regex::new(&regex) { Ok(_) => Ok(()), Err(e) => Err(format!("'{}' is not a valid regex - {}", regex, e)) } }) .required(true) .takes_value(true)) .arg(Arg::with_name("function name") .short("n") .long("name") .help("Name of the function in output source") .required(true) .takes_value(true) .validator(|_function_name| { Ok(()) })) .arg(Arg::with_name("language") .short("l") .long("language") .help("The programming language of the output source") .required(true) .takes_value(true) .possible_values(&["Rust"])) .arg(Arg::with_name("verbosity") .short("v") .long("verbose") .help("Show extra information") .required(false) .takes_value(false)) .get_matches(); let regex = matches.value_of("regex").unwrap(); let function_name = matches.value_of("function name").unwrap(); let verbosity = matches.is_present("verbosity"); let translation_result = match matches.value_of("language").unwrap() { "Rust" => { rust_translate::translate(regex, function_name) } _ => { unreachable!() } }; match translation_result { Ok(code) => { if verbosity { eprintln!("----- SOURCE ----- \n{}", code); eprintln!("----- END -----"); } if matches.is_present("file") { let file_name = matches.value_of("file").unwrap(); let file_result = OpenOptions::new() .read(false) .write(true) .create(true) .truncate(true) .open(file_name); match file_result { Ok(mut handle) => { match handle.write_all(code.as_bytes()) { Ok(_) => { Ok(()) } Err(e) => { Err(format!("Could not save source code to file '{}' - {}", file_name, e)) } } } Err(e) => { Err(format!("Could not save source code to file '{}' - {}", file_name, e)) } } } else { println!("{}", code); Ok(()) } } Err(e) => { Err(format!("Could not translate regex - {}", e)) } } }
true
42ef1c4da1908e0faf332b33270b2bca8a727edf
Rust
SUSF-Robotics-and-Software/AutonomyControl
/src/tc_constructor.rs
UTF-8
2,178
2.90625
3
[]
no_license
// --------------------------------------------------------------------------- // TELECOMMAND CONSTRUCTOR // // Provides a single interface to the GUI for building telecommands which will // be sent to the Rover via the TmTcInterface module. // // Diferent types of telecommand are defined as structs here. // --------------------------------------------------------------------------- use serde::{Serialize, Deserialize}; use chrono::{DateTime, Utc}; use crate::tm_tc_interface::{TmTcIf, TmTcData}; // --------------------------------------------------------------------------- // TC CONSTRUCTOR // --------------------------------------------------------------------------- pub struct TcConstructor<'a> { tm_tc_if: &'a mut TmTcIf, } impl<'a> TcConstructor<'a> { // Instantiate a new `TcConstructor` - used to build and send TCs to the // TmTcIf. pub fn new(tm_tc_if: &'a mut TmTcIf) -> Self { TcConstructor { tm_tc_if: tm_tc_if } } // Take a piece of TC data, generally a `TcXxx` object, and send it to the // interface. pub fn build_and_send<T>(&mut self, data: T) -> Result<(), String> where T: TmTcData { self.tm_tc_if.add_pending_tc(data) } } // --------------------------------------------------------------------------- // TC TYPES // --------------------------------------------------------------------------- // HEARTBEAT // // Contains the current time to be sent to the Rover #[derive(Serialize, Deserialize, Debug)] pub struct TcHeartbeat { current_time_utc: DateTime<Utc> } impl TcHeartbeat { pub fn new() -> Self { TcHeartbeat { current_time_utc: chrono::Utc::now() } } } impl TmTcData for TcHeartbeat { fn type_id(&self) -> String { String::from("TcHeartbeat") } } // DISCONNECT // // Instructs the rover to disconnect from the control GUI #[derive(Serialize, Deserialize, Debug)] pub struct TcDisconnect {} impl TcDisconnect { pub fn new() -> Self { TcDisconnect {} } } impl TmTcData for TcDisconnect { fn type_id(&self) -> String { String::from("TcDisconnect") } }
true
6d06c67fe7bae988674f101765942865cb27a6a2
Rust
krzysz00/rust-kernel
/kernel/console.rs
UTF-8
831
2.765625
3
[ "MIT" ]
permissive
use machine; use mutex::Mutex; use core::fmt::{Write,Error}; use core::result::Result; const PORT: u16 = 0x3F8; pub struct Console; static CONSOLE_LOCK: Mutex<()> = Mutex::new(()); impl Console { pub fn write_bytes(&self, bytes: &[u8]) { let _lock = CONSOLE_LOCK.lock(); for b in bytes { while machine::inb(PORT + 5) & 0x20 == 0 {}; machine::outb(PORT, *b); } } } impl Write for Console { #[inline] fn write_str(&mut self, data: &str) -> Result<(), Error> { self.write_bytes(data.as_bytes()); Result::Ok(()) } } pub fn puts(string: &str) { let _ = Console.write_str(string); } #[macro_export] macro_rules! log { ($($arg:tt)*) => ({ use ::core::fmt::Write; let _ = write!($crate::console::Console, $($arg)*); }) }
true
ba35abeb0f839a64be1b4e81c285663e7d4e4aac
Rust
lnds/desafios-programando.org
/2019-12-08/brute-force-sha512/src/main.rs
UTF-8
469
2.75
3
[]
no_license
#[macro_use] extern crate itertools; use sha2::{Digest, Sha512}; fn main() { let target = Sha512::new().chain(b"help").result(); let alpha = "abcdefghijklmnopqrstuvwxyz"; let col = iproduct!(alpha.chars(), alpha.chars(), alpha.chars(), alpha.chars()) .map(|(a, b, c, d)| format!("{}{}{}{}", a, b, c, d)) .filter(|candidate| Sha512::new().chain(&candidate).result() == target) .collect::<Vec<String>>(); println!("{:?}", col); }
true
9fd608ffeec0fd44866eaa7c8369fc7835052aa0
Rust
nicholastmosher/atsam4s16b-rs
/src/matrix/ccfg_smcnfcs/mod.rs
UTF-8
7,776
2.5625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CCFG_SMCNFCS { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct SMC_NFCS0R { bits: bool, } impl SMC_NFCS0R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct SMC_NFCS1R { bits: bool, } impl SMC_NFCS1R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct SMC_NFCS2R { bits: bool, } impl SMC_NFCS2R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct SMC_NFCS3R { bits: bool, } impl SMC_NFCS3R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _SMC_NFCS0W<'a> { w: &'a mut W, } impl<'a> _SMC_NFCS0W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SMC_NFCS1W<'a> { w: &'a mut W, } impl<'a> _SMC_NFCS1W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SMC_NFCS2W<'a> { w: &'a mut W, } impl<'a> _SMC_NFCS2W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SMC_NFCS3W<'a> { w: &'a mut W, } impl<'a> _SMC_NFCS3W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - SMC NAND Flash Chip Select 0 Assignment"] #[inline] pub fn smc_nfcs0(&self) -> SMC_NFCS0R { let bits = { const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }; SMC_NFCS0R { bits } } #[doc = "Bit 1 - SMC NAND Flash Chip Select 1 Assignment"] #[inline] pub fn smc_nfcs1(&self) -> SMC_NFCS1R { let bits = { const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }; SMC_NFCS1R { bits } } #[doc = "Bit 2 - SMC NAND Flash Chip Select 2 Assignment"] #[inline] pub fn smc_nfcs2(&self) -> SMC_NFCS2R { let bits = { const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }; SMC_NFCS2R { bits } } #[doc = "Bit 3 - SMC NAND Flash Chip Select 3 Assignment"] #[inline] pub fn smc_nfcs3(&self) -> SMC_NFCS3R { let bits = { const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }; SMC_NFCS3R { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - SMC NAND Flash Chip Select 0 Assignment"] #[inline] pub fn smc_nfcs0(&mut self) -> _SMC_NFCS0W { _SMC_NFCS0W { w: self } } #[doc = "Bit 1 - SMC NAND Flash Chip Select 1 Assignment"] #[inline] pub fn smc_nfcs1(&mut self) -> _SMC_NFCS1W { _SMC_NFCS1W { w: self } } #[doc = "Bit 2 - SMC NAND Flash Chip Select 2 Assignment"] #[inline] pub fn smc_nfcs2(&mut self) -> _SMC_NFCS2W { _SMC_NFCS2W { w: self } } #[doc = "Bit 3 - SMC NAND Flash Chip Select 3 Assignment"] #[inline] pub fn smc_nfcs3(&mut self) -> _SMC_NFCS3W { _SMC_NFCS3W { w: self } } }
true
6b153dfb4818df77793081645ac06f67ce5c389e
Rust
onnovalkering/brane
/brane-dsl/src/errors.rs
UTF-8
8,118
2.625
3
[ "Apache-2.0" ]
permissive
use crate::scanner::{Span, Tokens}; use nom::error::{VerboseError, VerboseErrorKind}; pub fn convert_parser_error( input: Tokens, e: VerboseError<Tokens>, ) -> String { use std::fmt::Write; let mut result = String::new(); for (i, (tokens, kind)) in e.errors.iter().enumerate() { match kind { VerboseErrorKind::Char(c) => { if tokens.tok.is_empty() { if let Some(mismatch) = input.tok.last() { let mismatch = mismatch.inner(); let line = String::from_utf8(mismatch.get_line_beginning().to_vec()).unwrap(); let line_number = mismatch.location_line(); let column_number = mismatch.get_column() + 1; write!( &mut result, "{i}: at line {line_number}:\n\n\ {line}\n\ {caret:>column$}\n\ expected '{expected}', but encountered EOF\n\n", i = i, line_number = line_number, line = line, caret = '^', column = column_number, expected = c, ) .unwrap(); } else { write!( &mut result, "{i}: expected '{expected}', but EOF\n\n", i = i, expected = c, ) .unwrap(); } } else { let mismatch = tokens.tok[0].inner(); let line = String::from_utf8(mismatch.get_line_beginning().to_vec()).unwrap(); let line_number = mismatch.location_line(); let column_number = mismatch.get_column(); let actual = mismatch.fragment(); write!( &mut result, "{i}: at line {line_number}:\n\n\ {line}\n\ {caret:>column$}\n\ expected '{expected}', found '{actual}'\n\n", i = i, line_number = line_number, line = line, caret = '^', column = column_number, expected = c, actual = actual, ) .unwrap(); } } VerboseErrorKind::Nom(nom::error::ErrorKind::Tag) => { let mismatch = tokens.tok[0].inner(); let line = String::from_utf8(mismatch.get_line_beginning().to_vec()).unwrap(); let line_number = mismatch.location_line(); let column_number = mismatch.get_column(); let actual = mismatch.fragment(); write!( &mut result, "{i}: at line {line_number}:\n\ {line}\n\ {caret:>column$}\n\ unexpected token '{actual}'\n\n", i = i, line_number = line_number, line = line, caret = '^', column = column_number, actual = actual, ) .unwrap(); } VerboseErrorKind::Context(s) => { let mismatch = tokens.tok[0].inner(); let line = String::from_utf8(mismatch.get_line_beginning().to_vec()).unwrap(); writeln!(result, "{} in section '{}', at: {}", i, s, line).unwrap() } e => { writeln!(result, "Compiler error: unkown error from parser: {:?}", e).unwrap(); } } } result } pub fn convert_scanner_error( input: Span, e: VerboseError<Span>, ) -> String { use nom::Offset; use std::fmt::Write; let mut result = String::new(); for (i, (substring, kind)) in e.errors.iter().enumerate() { let offset = input.offset(substring); if input.is_empty() { match kind { VerboseErrorKind::Char(c) => write!(&mut result, "{}: expected '{}', got empty input\n\n", i, c), VerboseErrorKind::Context(s) => write!(&mut result, "{}: in {}, got empty input\n\n", i, s), VerboseErrorKind::Nom(e) => write!(&mut result, "{}: in {:?}, got empty input\n\n", i, e), } } else { let prefix = &input.as_bytes()[..offset]; // Count the number of newlines in the first `offset` bytes of input let line_number = prefix.iter().filter(|&&b| b == b'\n').count() + 1; // Find the line that includes the subslice: // Find the *last* newline before the substring starts let line_begin = prefix .iter() .rev() .position(|&b| b == b'\n') .map(|pos| offset - pos) .unwrap_or(0); // Find the full line after that newline let line = input[line_begin..] .lines() .next() .unwrap_or(&input[line_begin..]) .trim_end(); // The (1-indexed) column number is the offset of our substring into that line let column_number = line.offset(substring) + 1; match kind { VerboseErrorKind::Char(c) => { if let Some(actual) = substring.chars().next() { write!( &mut result, "{i}: at line {line_number}:\n\ {line}\n\ {caret:>column$}\n\ expected '{expected}', found {actual}\n\n", i = i, line_number = line_number, line = line, caret = '^', column = column_number, expected = c, actual = actual, ) } else { write!( &mut result, "{i}: at line {line_number}:\n\ {line}\n\ {caret:>column$}\n\ expected '{expected}', got end of input\n\n", i = i, line_number = line_number, line = line, caret = '^', column = column_number, expected = c, ) } } VerboseErrorKind::Context(s) => write!( &mut result, "{i}: at line {line_number}, in {context}:\n\ {line}\n\ {caret:>column$}\n\n", i = i, line_number = line_number, context = s, line = line, caret = '^', column = column_number, ), VerboseErrorKind::Nom(e) => write!( &mut result, "{i}: at line {line_number}, in {nom_err:?}:\n\ {line}\n\ {caret:>column$}\n\n", i = i, line_number = line_number, nom_err = e, line = line, caret = '^', column = column_number, ), } } // Because `write!` to a `String` is infallible, this `unwrap` is fine. .unwrap(); } result }
true
afad660855542850819b8ada3bcc2669d15d9b2f
Rust
helloooooo/prac-algo
/atcoder/src/29.rs
UTF-8
1,224
3.15625
3
[]
no_license
use std::collections::BTreeSet; fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() } fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> { (0..n).map(|_| read_vec()).collect() } fn main(){ let s = read::<String>(); let kk = read::<i32>(); let cp = s.clone().chars().collect::<Vec<char>>(); let mut len = cp.len(); let mut ans:BTreeSet<String>= BTreeSet::new(); let mut ss = Vec::new(); for i in 0..len{ for j in 1..len+1{ for k in 0..len+1{ // ans.insert(s.get(k..j+i).unwrap_or("").to_string()); println!("[{}:{}]",k,j+i); println!("{}",s.chars().skip(k).take(j+i).collect::<String>()); ans.insert(s.chars().skip(k).take(j+i).collect::<String>()); } } } for x in ans{ ss.push(x); } ss.sort(); ss.reverse(); ss.pop(); let anslen = ss.len(); println!("{}",ss[(anslen as i32 -kk) as usize]); }
true
e331078c8164008b5ce8236fde20154826361ed4
Rust
alexisfontaine/ocean
/components/router.rs
UTF-8
2,805
2.765625
3
[]
no_license
use yew::prelude::*; use yew_router::agent::RouteRequest; use yew_router::prelude::*; use super::components::anchor::{render, Kind, AnchorModifier, ButtonModifier}; use super::utils::ne_assign; pub enum Message<STATE> { Navigate, Navigation(Route<STATE>), } pub struct Anchor<SWITCH, STATE = ()> where STATE: RouteState, SWITCH: Clone { handle_click: Callback<MouseEvent>, properties: Properties<SWITCH>, route: Option<SWITCH>, router: RouteAgentBridge<STATE>, } #[derive(Clone, Debug, PartialEq, Properties)] pub struct Properties<SWITCH> where SWITCH: Clone { pub children: Children, #[prop_or_default] pub class: String, #[prop_or_default] pub disabled: bool, #[prop_or(Kind::Anchor(AnchorModifier::Standalone))] pub kind: Kind, #[prop_or_default] pub loading: bool, pub route: SWITCH, } #[allow(non_upper_case_globals)] impl<SWITCH, STATE> Anchor<SWITCH, STATE> where STATE: RouteState, SWITCH: Clone { pub const Button: Kind = Kind::Button(ButtonModifier::Default); pub const ButtonDanger: Kind = Kind::Button(ButtonModifier::Danger); pub const ButtonPrimary: Kind = Kind::Button(ButtonModifier::Primary); pub const ButtonSecondary: Kind = Kind::Button(ButtonModifier::Secondary); pub const Inline: Kind = Kind::Anchor(AnchorModifier::Inline); pub const Standalone: Kind = Kind::Anchor(AnchorModifier::Standalone); } impl<SWITCH, STATE> Component for Anchor<SWITCH, STATE> where STATE: RouteState + PartialEq, SWITCH: Clone + PartialEq + Switch + 'static { type Message = Message<STATE>; type Properties = Properties<SWITCH>; fn create (properties: Self::Properties, link: ComponentLink<Self>) -> Self { let mut router = RouteAgentBridge::new(link.callback(Self::Message::Navigation)); router.send(RouteRequest::GetCurrentRoute); Self { properties, route: None, router, handle_click: link.callback(|event: MouseEvent| { event.prevent_default(); Self::Message::Navigate }), } } fn change (&mut self, properties: Self::Properties) -> ShouldRender { ne_assign(&mut self.properties, properties) } fn update (&mut self, message: Self::Message) -> ShouldRender { match message { Self::Message::Navigate => self.router.send(RouteRequest::ChangeRoute(self.properties.route.clone().into())), Self::Message::Navigation(route) => { let route = SWITCH::switch(route); if route != self.route { self.route = route; return true } } } false } fn view (&self) -> Html { let properties = &self.properties; let route: Route<STATE> = properties.route.clone().into(); render(route.as_str(), properties.kind, properties.class.clone(), Some(&self.handle_click), properties.children.clone(), self.route.contains(&properties.route), properties.disabled, properties.loading, false) } }
true
620c2bd5a679efeb2c46eadfef7a173d9a031ba0
Rust
ThomasZumsteg/exercism-rust
/custom-set/src/lib.rs
UTF-8
1,668
3.65625
4
[]
no_license
#[derive(Debug)] pub struct CustomSet<T: PartialEq + Clone> { set: Vec<T> } impl<T: PartialEq + Clone> CustomSet<T>{ pub fn new(items: Vec<T>) -> CustomSet<T> { let mut set = CustomSet { set: vec![] }; for item in items { set.add(item) } set } pub fn is_empty(&self) -> bool { self.set.is_empty() } pub fn add(&mut self, item: T) { if !self.contains(&item) { self.set.push(item) } } pub fn contains(&self, item: &T) -> bool { self.set.contains(item) } pub fn is_disjoint(&self, other: &CustomSet<T>) -> bool { !self.set.iter().any(|i| other.contains(i)) } pub fn is_subset(&self, other: &CustomSet<T>) -> bool { self.set.iter().all(|i| other.contains(i)) } pub fn intersection(&self, other: &CustomSet<T>) -> CustomSet<T> { let mut result = Self::new(vec![]); for item in self.set.iter().cloned() { if other.contains(&item) { result.add(item) } } result } pub fn union(&self, other: &CustomSet<T>) -> CustomSet<T> { let mut union = Self::new(vec![]); for item in self.set.iter().chain(other.set.iter()).cloned() { union.add(item); } union } pub fn difference(&self, other: &CustomSet<T>) -> CustomSet<T> { let mut difference = Self::new(vec![]); for item in self.set.iter().cloned() { if !other.contains(&item) { difference.add(item); } } difference } } impl<T: Clone> PartialEq for CustomSet<T> where T: PartialEq { fn eq(&self, other: &CustomSet<T>) -> bool { self.is_subset(other) && other.is_subset(self) } }
true
1b56d55947d9c97b39d0a6c3ea4f42ddbd88ddee
Rust
gvanderest/adventofcode
/2021/day6/src/main.rs
UTF-8
4,320
3.515625
4
[]
no_license
use rayon::prelude::*; use std::collections::HashMap; use std::fs; fn step_lanternfish( current_fish: Vec<usize>, reset_fish_value: usize, new_fish_value: usize, ) -> Vec<usize> { current_fish .par_iter() .flat_map(|days| -> Vec<usize> { match days { 0 => [reset_fish_value, new_fish_value].to_vec(), _ => [days - 1].to_vec(), } }) .collect() } fn parse_initial_fish(input: &String) -> Vec<usize> { input .trim() .split(",") .map(|n| -> usize { n.parse::<usize>().unwrap() }) .collect() } fn process(input: &String, days: usize) -> usize { let mut current_fish = parse_initial_fish(&input); for day in 0..days { println!("Processing day {}", day); current_fish = step_lanternfish(current_fish, 6, 8); println!("It was {} fish!", current_fish.len()); } current_fish.len() } const FISH_RESET_VALUE: usize = 6; const NEW_FISH_VALUE: usize = 8; fn process2(input: &String, days: usize, reporting: bool) -> usize { let initial_fish = parse_initial_fish(input); // Setup container for fish counts and prime values to zero let mut fish_counts: HashMap<usize, usize> = HashMap::new(); for x in 0..=NEW_FISH_VALUE { fish_counts.insert(x, 0); } // Count initial fish for days_until_birth in initial_fish { let existing_value = fish_counts.get(&days_until_birth).unwrap(); let new_value = existing_value + 1; fish_counts.insert(days_until_birth, new_value); } // For each day, shift fish down.. taking those that are zero and re-injecting them in two spots for current_day in 0..days { if reporting { println!("Day {}", current_day); } let quantity_birthing = *fish_counts.get(&0).unwrap(); for day_to_move_from in 1..=NEW_FISH_VALUE { let today_value = *fish_counts.get(&day_to_move_from).unwrap(); let day_to_move_to = day_to_move_from - 1; fish_counts.insert(day_to_move_to, today_value); } fish_counts.insert(NEW_FISH_VALUE, 0); // One spot, for the initial fish resetting their timers let old_reset_count = *fish_counts.get(&FISH_RESET_VALUE).unwrap(); let new_reset_count = old_reset_count + quantity_birthing; fish_counts.insert(FISH_RESET_VALUE, new_reset_count); // Second spot, for their children let old_created_count = *fish_counts.get(&NEW_FISH_VALUE).unwrap(); let new_created_count = old_created_count + quantity_birthing; fish_counts.insert(NEW_FISH_VALUE, new_created_count); if reporting { let mut report = String::from("|"); for day in 0..=NEW_FISH_VALUE { report.push_str(fish_counts.get(&day).unwrap().to_string().as_str()); report.push_str("|"); } println!("{}", report); } } // At end, sum up total counts let mut count = 0; for x in 0..=NEW_FISH_VALUE { count += *fish_counts.get(&x).unwrap_or(&0); } count } fn main() { let input = fs::read_to_string("input.txt").expect("Unable to open example text."); //println!("Part 1: {}", process(&input, 80)); -- turns out process 2 is way faster println!("Part 1: {}", process2(&input, 80, false)); println!("Part 2: {}", process2(&input, 256, false)); } #[cfg(test)] mod tests { use super::*; #[test] fn part1_computes_properly() { let input = fs::read_to_string("example.txt").expect("Unable to read example file."); assert_eq!(26, process(&input, 18)); assert_eq!(5934, process(&input, 80)); } #[test] fn part2_computes_properly() { let input = fs::read_to_string("example.txt").expect("Unable to read example file."); // Basic tests assert_eq!(1, process2(&String::from("1"), 1, true)); assert_eq!(2, process2(&String::from("1"), 2, true)); assert_eq!(3, process2(&String::from("1"), 9, true)); // Real tests assert_eq!(26, process2(&input, 18, true)); assert_eq!(5934, process2(&input, 80, true)); assert_eq!(26984457539, process2(&input, 256, true)); } }
true
654135aa84945b1c24116d7b46dba36464487346
Rust
arendjr/ts-rs
/example/src/lib.rs
UTF-8
2,414
2.9375
3
[ "MIT" ]
permissive
#![allow(dead_code)] use serde::Serialize; use std::collections::BTreeSet; use std::rc::Rc; use ts_rs::{export, TS}; #[derive(Serialize, TS)] #[ts(rename_all = "lowercase")] enum Role { User, #[ts(rename = "administrator")] Admin, } #[derive(Serialize, TS)] // when 'serde-compat' is enabled, ts-rs tries to use supported serde attributes. #[serde(rename_all = "UPPERCASE")] enum Gender { Male, Female, Other, } #[derive(Serialize, TS)] struct User { user_id: i32, first_name: String, last_name: String, role: Role, family: Vec<User>, gender: Gender, } #[derive(Serialize, TS)] #[serde(tag = "type", rename_all = "snake_case")] enum Vehicle { Bicycle { color: String }, Car { brand: String, color: String }, } #[derive(Serialize, TS)] struct Point<T> where T: TS, { time: u64, value: T, } #[derive(Serialize, TS)] struct Series { points: Vec<Point<u64>>, } #[derive(Serialize, TS)] #[serde(tag = "kind", content = "d")] enum SimpleEnum { A, B, } #[derive(Serialize, TS)] #[serde(tag = "kind", content = "data")] enum ComplexEnum { A, B { foo: String, bar: f64 }, W(SimpleEnum), F { nested: SimpleEnum }, V(Vec<Series>), U(Box<User>), } #[derive(Serialize, TS)] #[serde(tag = "kind")] enum InlineComplexEnum { A, B { foo: String, bar: f64 }, W(SimpleEnum), F { nested: SimpleEnum }, V(Vec<Series>), U(Box<User>), } #[derive(Serialize, TS)] #[serde(rename_all = "camelCase")] struct ComplexStruct { #[serde(skip_serializing_if = "Option::is_none")] pub string_tree: Option<Rc<BTreeSet<String>>>, } // this will export [Role] to `role.ts` and [User] to `user.ts` when running `cargo test`. // `export!` will also take care of including imports in typescript files. export! { Role => "role.ts", User => "user.ts", // any type can be used here in place of the generic, but it has to match the one used // in other structs to generate the dependencies correctly: Point<u64> => "point.ts", Series => "series.ts", Vehicle => "vehicle.ts", ComplexEnum => "complex_enum.ts", InlineComplexEnum => "inline_complex_enum.ts", SimpleEnum => "simple_enum.ts", ComplexStruct => "complex_struct.ts", // this exports an ambient declaration (`declare interface`) instead of an `export interface`. (declare) Gender => "gender.d.ts", }
true
3cfcb7468f5508dce5fc3b4b4834f8ad55439782
Rust
ytyaru/Rust.Advanced.Function.Closure.20190708174220
/src/2/main.rs
UTF-8
364
2.890625
3
[ "CC0-1.0" ]
permissive
/* * Rustの高度な機能(関数、クロージャ)。 * CreatedAt: 2019-07-08 */ fn main() { } /* // error[E0277]: the size for values of type `(dyn std::ops::Fn(i32) -> i32 + 'static)` cannot be known at compilation time fn returns_closure() -> Fn(i32) -> i32 { |x| x + 1 } */ fn returns_closure() -> Box<Fn(i32) -> i32> { Box::new(|x| x + 1) }
true
f40512b96ce9cd00ddff6276ac7daaf36e415a57
Rust
hamishgibbs/rust_dsa
/src/bin/edit_distance.rs
UTF-8
2,009
3.78125
4
[]
no_license
/* How it works: Calculates the edit distance (a string distance metric) for two strings. Edit distance is the number of changes needed to make two strings equal. i.e. (test, tset) has an edit distance of one. */ use std::cmp::min; pub fn edit_distance(str_a: &str, str_b: &str) -> u32 { // Initialize a vector of distances [i][j] for a[..i] & b[..i] let mut distances = vec![vec![0; str_b.len() + 1]; str_a.len() + 1]; // Initialise top row and left column of matrix with ascending integers for j in 0..=str_b.len() { distances[0][j] = j as u32; } for (i, item) in distances.iter_mut().enumerate() { item[0] = i as u32; } // Progressively fill matrix by comparing strings. for i in 1..=str_a.len() { for j in 1..=str_b.len() { distances[i][j] = min(distances[i - 1][j] + 1, distances[i][j - 1] + 1); if str_a.as_bytes()[i - 1] == str_b.as_bytes()[j - 1] { distances[i][j] = min(distances[i][j], distances[i - 1][j - 1]); } else { distances[i][j] = min(distances[i][j], distances[i - 1][j - 1] + 1); } } } // The final value of th matrix is the edit distance distances[str_a.len()][str_b.len()] } #[cfg(test)] mod tests { use super::*; #[test] fn equal_strings() { assert_eq!(0, edit_distance("Hello, world!", "Hello, world!")); assert_eq!(0, edit_distance("Test_Case_#1", "Test_Case_#1")); } #[test] fn one_edit_difference() { assert_eq!(1, edit_distance("Hello, world!", "Hell, world!")); assert_eq!(1, edit_distance("Test_Case_#1", "Test_Case_#2")); assert_eq!(1, edit_distance("Test_Case_#1", "Test_Case_#10")); } #[test] fn several_differences() { assert_eq!(2, edit_distance("My Cat", "My Case")); assert_eq!(7, edit_distance("Hello, world!", "Goodbye, world!")); assert_eq!(6, edit_distance("Test_Case_#3", "Case #3")); } }
true
e821f12a6541d1eca6ab0d2e9d710f15889be27a
Rust
MattiasBuelens/advent-of-code-2019
/src/bin/day7/main.rs
UTF-8
3,543
3.03125
3
[ "MIT" ]
permissive
use std::cmp::max; use std::collections::VecDeque; use permutohedron::Heap; use advent_of_code_2019::input::parse_list; use advent_of_code_2019::intcode::*; fn main() { let input: Vec<i64> = parse_list(include_str!("input"), ','); println!("Answer to part 1: {}", part1(&input)); println!("Answer to part 2: {}", part2(&input)); } fn run_chain(program: &Vec<i64>, phase_settings: &Vec<i64>) -> i64 { let mut signal = 0; for &phase_setting in phase_settings { let mut machine = ProgramMachine::new(program.clone(), vec![phase_setting]); machine.add_input(signal); let output = machine.run_to_output(); signal = output.expect("expected an output"); } signal } fn part1(program: &Vec<i64>) -> i64 { let mut max_signal = 0; let mut settings: Vec<i64> = (0..=4).collect(); for permutation in Heap::new(&mut settings) { max_signal = max(max_signal, run_chain(program, &permutation)); } max_signal } fn run_feedback_loop(program: &Vec<i64>, phase_settings: &Vec<i64>) -> i64 { let machines: Vec<Box<dyn Machine>> = phase_settings .iter() .map(|&setting| { let machine = ProgramMachine::new(program.clone(), vec![setting]); Box::new(machine) as Box<dyn Machine> }) .collect(); let mut chain = make_chain(VecDeque::from(machines)); // To start the process, a 0 signal is sent to amplifier A's input exactly once. let mut signal = 0; chain.add_input(signal); loop { match chain.step() { StepResult::Ok | StepResult::NeedInput => { // keep going } StepResult::Output(value) => { chain.add_input(value); signal = value; } StepResult::Halt => { break; } }; } signal } fn part2(program: &Vec<i64>) -> i64 { let mut max_signal = 0; let mut settings: Vec<i64> = (5..=9).collect(); for permutation in Heap::new(&mut settings) { max_signal = max(max_signal, run_feedback_loop(program, &permutation)); } max_signal } #[cfg(test)] mod tests { use super::*; #[test] fn test_part1() { assert_eq!( part1(&vec![ 3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0 ]), 43210 ); assert_eq!( part1(&vec![ 3, 23, 3, 24, 1002, 24, 10, 24, 1002, 23, -1, 23, 101, 5, 23, 23, 1, 24, 23, 23, 4, 23, 99, 0, 0 ]), 54321 ); assert_eq!( part1(&vec![ 3, 31, 3, 32, 1002, 32, 10, 32, 1001, 31, -2, 31, 1007, 31, 0, 33, 1002, 33, 7, 33, 1, 33, 31, 31, 1, 32, 31, 31, 4, 31, 99, 0, 0, 0 ]), 65210 ); } #[test] fn test_part2() { assert_eq!( part2(&vec![ 3, 26, 1001, 26, -4, 26, 3, 27, 1002, 27, 2, 27, 1, 27, 26, 27, 4, 27, 1001, 28, -1, 28, 1005, 28, 6, 99, 0, 0, 5 ]), 139629729 ); assert_eq!( part2(&vec![ 3, 52, 1001, 52, -5, 52, 3, 53, 1, 52, 56, 54, 1007, 54, 5, 55, 1005, 55, 26, 1001, 54, -5, 54, 1105, 1, 12, 1, 53, 54, 53, 1008, 54, 0, 55, 1001, 55, 1, 55, 2, 53, 55, 53, 4, 53, 1001, 56, -1, 56, 1005, 56, 6, 99, 0, 0, 0, 0, 10 ]), 18216 ); } }
true
58b6dffcbb0a845fd80f534aa700cae52f991de0
Rust
xfbs/afp
/src/ui/view/section_overview.rs
UTF-8
2,798
2.609375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
extern crate gtk; use crate::ui::*; use gtk::prelude::*; #[derive(Clone)] pub struct SectionOverView { body: gtk::Grid, title: gtk::Label, subsections: gtk::FlowBox, exam: gtk::Button, practise: gtk::Button, } impl SectionOverView { pub fn new() -> SectionOverView { SectionOverView { body: gtk::Grid::new(), title: gtk::Label::new(None), subsections: gtk::FlowBox::new(), exam: gtk::Button::new(), practise: gtk::Button::new(), } } pub fn setup(&self) { self.title.set_hexpand(true); self.title.get_style_context().add_class("title"); self.subsections.set_hexpand(true); self.body.set_margin_top(10); self.body.set_margin_bottom(10); self.body.set_margin_start(10); self.body.set_margin_end(10); self.body.set_column_spacing(20); self.body.set_row_spacing(20); self.body.set_column_homogeneous(true); self.body.attach(&self.title, 0, 0, 2, 1); self.body.attach(&self.subsections, 0, 1, 2, 1); self.body.attach(&self.practise, 0, 2, 1, 1); self.body.attach(&self.exam, 1, 2, 1, 1); self.exam.set_label("Prüfung"); self.practise.set_label("Üben"); } pub fn set_title(&self, title: &str) { self.title.set_text(title); } pub fn button_add_class(&self, index: usize, class: &str) { if let Some(button) = self.get_button(index) { let style = button.get_style_context(); style.add_class(class); } else { panic!(); } } pub fn button_remove_class(&self, index: usize, class: &str) { if let Some(button) = self.get_button(index) { let style = button.get_style_context(); style.remove_class(class); } else { panic!(); } } pub fn get_button(&self, index: usize) -> Option<gtk::Widget> { match self.subsections.get_child_at_index(index as i32) { Some(child) => child.get_child(), None => None, } } pub fn add_button(&self, label: &str) -> gtk::Button { let button = gtk::Button::new(); button.set_label(label); button.set_hexpand(false); button.show(); self.subsections.add(&button); button } pub fn connect_exam<F: Fn() + 'static>(&self, fun: F) { self.exam.connect_clicked(move |_| { fun(); }); } pub fn connect_practise<F: Fn() + 'static>(&self, fun: F) { self.practise.connect_clicked(move |_| { fun(); }); } } impl View for SectionOverView { fn widget(&self) -> gtk::Widget { self.body.clone().upcast() } }
true
5d2c60da5f7373e8bd53bf13ef5c1e8e388abcca
Rust
ilovelll/learn-rust-by-example
/ch9-functions/src/closures.rs
UTF-8
4,267
3.5
4
[]
no_license
fn main() { fn function (i: i32) -> i32 { i + 1} let closure_annotated = |i: i32| -> i32 {i + 1}; let closure_inferred = |i| i + 1; println!("function: {}", function(1)); println!("closure_anotated: {}", closure_annotated(1)); println!("closure_inferred: {}", closure_inferred(1)); let one = || 1; println!("closure returing one: {}", one()); let color = "green"; let print = || println!("`color`:{}", color); print(); print(); let mut count = 0; let mut inc = || { count += 1; println!("`count`: {}", count); }; inc(); inc(); let _reborrow = &mut count; println!("{}", _reborrow); let movable = Box::new(3); let consume = || { println!("`moveable`: {:?}", movable); std::mem::drop(movable); }; consume(); // movable has been move // consume(); let haystack = vec![1,2,3]; let contains = move |needle| haystack.contains(needle); println!("{}", contains(&1)); println!("{}", contains(&4)); // use after `move` will cause error // println!("{}", haystack.len()); // As input params let greeting = "hello"; let mut farewell = "goodbye".to_owned(); apply(|| { println!("I said {}", greeting); farewell.push_str("!!!"); println!("Then I screamed {}.", farewell); println!("Now I can sleep. zzzz"); std::mem::drop(farewell); }); let x = apply_to3(|x|{ x * 2 }); println!("3 doubled: {}", x); let fn_plain = create_fn(); let mut fn_mut = create_fnmut(); fn_plain(); fn_mut(); //pub trait Iterator { // // The type being iterated over. // type Item; // // `any` takes `&mut self` meaning the caller may be borrowed // // and modified, but not consumed. // fn any<F>(&mut self, f: F) -> bool where // // `FnMut` meaning any captured variable may at most be // // modified, not consumed. `Self::Item` states it takes // // arguments to the closure by value. // F: FnMut(Self::Item) -> bool {} // } let vec1 = vec![1, 2, 3]; let vec2 = vec![4, 5, 6]; // `iter()` for vecs yields `&i32`. Destructure to `i32`. println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2)); // `into_iter()` for vecs yields `i32`. No destructuring required. println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2)); let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; // `iter()` for arrays yields `&i32`. println!("2 in array1: {}", array1.iter() .any(|&x| x == 2)); // `into_iter()` for arrays unusually yields `&i32`. println!("2 in array2: {}", array2.into_iter().any(|&x| x == 2)); // pub trait Iterator { // // The type being iterated over. // type Item; // // `find` takes `&mut self` meaning the caller may be borrowed // // and modified, but not consumed. // fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where // // `FnMut` meaning any captured variable may at most be // // modified, not consumed. `&Self::Item` states it takes // // arguments to the closure by reference. // P: FnMut(&Self::Item) -> bool {} // } let vec1 = vec![1, 2, 3]; let vec2 = vec![4, 5, 6]; // `iter()` for vecs yields `&i32`. let mut iter = vec1.iter(); // `into_iter()` for vecs yields `i32`. let mut into_iter = vec2.into_iter(); // A reference to what is yielded is `&&i32`. Destructure to `i32`. println!("Find 2 in vec1: {:?}", iter .find(|&&x| x == 2)); // A reference to what is yielded is `&i32`. Destructure to `i32`. println!("Find 2 in vec2: {:?}", into_iter.find(| &x| x == 2)); let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; // `iter()` for arrays yields `&i32` println!("Find 2 in array1: {:?}", array1.iter() .find(|&&x| x == 2)); // `into_iter()` for arrays unusually yields `&i32` println!("Find 2 in array2: {:?}", array2.into_iter().find(|&&x| x == 2)); } // input params FnOnce fn apply<F>(f: F) where F: FnOnce() { f(); } // input param Fn fn apply_to3<F>(f: F) -> i32 where F: Fn(i32) -> i32 { f(3) } fn create_fn() -> Box<Fn()> { let text = "Fn".to_owned(); Box::new(move || println!("This is a : {}", text)) } fn create_fnmut() -> Box<FnMut()> { let text = "FnMut".to_owned(); Box::new(move || println!("This is a : {}", text)) }
true
af7dc574031cb0d36adc0cc93c6ebd42569c055c
Rust
stakeada/jormungandr
/jcli/src/jcli_app/utils/rest_api.rs
UTF-8
7,431
2.609375
3
[ "MIT", "Apache-2.0" ]
permissive
use hex; use jcli_app::utils::{open_api_verifier, CustomErrorFiller, DebugFlag, OpenApiVerifier}; use reqwest::{self, header::HeaderValue, Client, Request, RequestBuilder, Response}; use serde::{self, Serialize}; use serde_json::error::Error as SerdeJsonError; use std::fmt; pub const DESERIALIZATION_ERROR_MSG: &'static str = "node returned malformed data"; pub struct RestApiSender<'a> { builder: RequestBuilder, body: RestApiRequestBody, debug_flag: &'a DebugFlag, } pub struct RestApiResponse { body: RestApiResponseBody, response: Response, } pub enum RestApiRequestBody { None, Binary(Vec<u8>), Json(String), } pub enum RestApiResponseBody { Text(String), Binary(Vec<u8>), } custom_error! { pub Error RequestFailed { source: reqwest::Error } = @{ reqwest_error_msg(source) }, VerificationFailed { source: open_api_verifier::Error } = "request didn't pass verification", RequestJsonSerializationError { source: SerdeJsonError, filler: CustomErrorFiller } = "failed to serialize request JSON", ResponseJsonDeserializationError { source: SerdeJsonError, filler: CustomErrorFiller } = "response JSON malformed", } fn reqwest_error_msg(err: &reqwest::Error) -> &'static str { if err.is_timeout() { "connection with node timed out" } else if err.is_http() { "could not connect with node" } else if err.is_serialization() { DESERIALIZATION_ERROR_MSG } else if err.is_redirect() { "redirecting error while connecting with node" } else if err.is_client_error() { "node rejected request because of invalid parameters" } else if err.is_server_error() { "node internal error" } else { "communication with node failed in unexpected way" } } impl<'a> RestApiSender<'a> { pub fn new(builder: RequestBuilder, debug_flag: &'a DebugFlag) -> Self { Self { builder, body: RestApiRequestBody::none(), debug_flag, } } pub fn with_binary_body(mut self, body: Vec<u8>) -> Self { self.body = RestApiRequestBody::from_binary(body); self } pub fn with_json_body(mut self, body: &impl Serialize) -> Result<Self, Error> { self.body = RestApiRequestBody::try_from_json(body)?; Ok(self) } pub fn send(self) -> Result<RestApiResponse, Error> { let mut request = self.builder.build()?; self.body.apply_header(&mut request); OpenApiVerifier::load_from_env()?.verify_request(&request, &self.body)?; self.debug_flag.write_request(&request, &self.body); self.body.apply_body(&mut request); let response_raw = Client::new().execute(request)?; let response = RestApiResponse::new(response_raw)?; self.debug_flag.write_response(&response); Ok(response) } } impl RestApiResponse { pub fn new(mut response: Response) -> Result<Self, Error> { Ok(RestApiResponse { body: RestApiResponseBody::new(&mut response)?, response, }) } pub fn response(&self) -> &Response { &self.response } pub fn ok_response(&self) -> Result<&Response, Error> { Ok(self.response().error_for_status_ref()?) } pub fn body(&self) -> &RestApiResponseBody { &self.body } } impl RestApiRequestBody { fn none() -> Self { RestApiRequestBody::None } fn from_binary(data: Vec<u8>) -> Self { RestApiRequestBody::Binary(data) } fn try_from_json(data: impl Serialize) -> Result<Self, Error> { let json = serde_json::to_string(&data).map_err(|source| { Error::RequestJsonSerializationError { source, filler: CustomErrorFiller, } })?; Ok(RestApiRequestBody::Json(json)) } fn apply_header(&self, request: &mut Request) { let content_type = match self { RestApiRequestBody::None => return, RestApiRequestBody::Binary(_) => &mime::APPLICATION_OCTET_STREAM, RestApiRequestBody::Json(_) => &mime::APPLICATION_JSON, }; let header_value = HeaderValue::from_static(content_type.as_ref()); request .headers_mut() .insert(reqwest::header::CONTENT_TYPE, header_value); } fn apply_body(self, request: &mut Request) { let body = match self { RestApiRequestBody::None => return, RestApiRequestBody::Binary(data) => data.into(), RestApiRequestBody::Json(data) => data.into(), }; request.body_mut().replace(body); } pub fn has_body(&self) -> bool { match self { RestApiRequestBody::None => false, _ => true, } } } impl fmt::Display for RestApiRequestBody { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { RestApiRequestBody::None => Ok(()), RestApiRequestBody::Binary(ref data) => write!(f, "{}", hex::encode(data)), RestApiRequestBody::Json(ref data) => write!(f, "{}", data), } } } impl RestApiResponseBody { fn new(response: &mut Response) -> Result<Self, Error> { match is_body_binary(response) { true => { let mut data = Vec::with_capacity(response.content_length().unwrap_or(0) as usize); response.copy_to(&mut data)?; Ok(RestApiResponseBody::Binary(data)) } false => { let data = response.text()?; Ok(RestApiResponseBody::Text(data)) } } } pub fn text<'a>(&'a self) -> impl AsRef<str> + 'a { match self { RestApiResponseBody::Text(text) => text.into(), RestApiResponseBody::Binary(binary) => String::from_utf8_lossy(binary), } } pub fn binary(&self) -> &[u8] { match self { RestApiResponseBody::Text(text) => text.as_bytes(), RestApiResponseBody::Binary(binary) => binary, } } pub fn json<'a, T: serde::Deserialize<'a>>(&'a self) -> Result<T, Error> { match self { RestApiResponseBody::Text(text) => serde_json::from_str(text), RestApiResponseBody::Binary(binary) => serde_json::from_slice(binary), } .map_err(|source| Error::ResponseJsonDeserializationError { source, filler: CustomErrorFiller, }) } pub fn json_value(&self) -> Result<serde_json::Value, Error> { self.json() } pub fn is_empty(&self) -> bool { match self { RestApiResponseBody::Text(text) => text.is_empty(), RestApiResponseBody::Binary(binary) => binary.is_empty(), } } } impl fmt::Display for RestApiResponseBody { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { RestApiResponseBody::Text(text) => text.fmt(f), RestApiResponseBody::Binary(binary) => hex::encode(binary).fmt(f), } } } fn is_body_binary(response: &Response) -> bool { response .headers() .get(reqwest::header::CONTENT_TYPE) .and_then(|header| header.to_str().ok()) .and_then(|header_str| header_str.parse::<mime::Mime>().ok()) == Some(mime::APPLICATION_OCTET_STREAM) }
true
0fda630aa56158451a0b52a9077b1b3370f9939b
Rust
ErickHdez96/lc
/src/terminal.rs
UTF-8
1,710
3.78125
4
[]
no_license
use core::fmt; #[derive(Debug, Copy, Clone)] pub enum Color { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, BrightBlack, BrightRed, BrightGreen, BrightYellow, BrightBlue, BrightMagenta, BrightCyan, BrightWhite, } impl Color { pub fn to_str(self) -> &'static str { match self { Self::Black => "30", Self::Red => "31", Self::Green => "32", Self::Yellow => "33", Self::Blue => "34", Self::Magenta => "35", Self::Cyan => "36", Self::White => "37", Self::BrightBlack => "90", Self::BrightRed => "91", Self::BrightGreen => "92", Self::BrightYellow => "93", Self::BrightBlue => "94", Self::BrightMagenta => "95", Self::BrightCyan => "96", Self::BrightWhite => "97", } } } #[derive(Debug, Default, Copy, Clone)] pub struct Style { bold: bool, color: Option<Color>, } impl Style { pub fn new() -> Self { Default::default() } pub fn bold(mut self) -> Self { self.bold = true; self } pub fn color(mut self, color: Color) -> Self { self.color = Some(color); self } } impl fmt::Display for Style { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\x1b[{}m", { let mut style = vec![]; if self.bold { style.push("0"); } if let Some(color) = self.color { style.push(color.to_str()); } &style.join(";") }) } }
true
f3b8017c1b05eba070c139ce0efca71f7d090544
Rust
Cyclonecinta88/naught
/src/error.rs
UTF-8
2,643
2.546875
3
[ "MIT" ]
permissive
extern crate hmac; extern crate hyper; extern crate serde; extern crate tokio; use std::error::Error as StdError; use std::fmt; use serde::Serialize; #[derive(Serialize, Debug)] pub enum Error { AddrParse(String), Hyper(String), HyperHTTP(String), TimerError, NotFound, StoreFailed(String), PingFailed, BadRequest, NonLocalStore(String), IO(String), Hmac, NotAuthorized, Unreachable, JSON(String), } impl StdError for Error { fn description(&self) -> &str { "TODO(indutny): implement me" } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::AddrParse(s) => write!(f, "AddrParse: {}", s), Error::Hyper(s) => write!(f, "Hyper: {}", s), Error::HyperHTTP(s) => write!(f, "Hyper HTTP: {}", s), Error::TimerError => write!(f, "TimerError"), Error::Unreachable => write!(f, "Unreachable"), Error::NotFound => write!(f, "Resource not found"), Error::StoreFailed(s) => write!(f, "Resource {} store failed", s), Error::PingFailed => write!(f, "Remote ping failed"), Error::BadRequest => write!(f, "Unsupported request method or uri"), Error::NonLocalStore(s) => write!(f, "Cannot store {} locally", s), Error::IO(s) => write!(f, "IO Error: {}", s), Error::Hmac => write!(f, "Hmac error"), Error::JSON(s) => write!(f, "JSON Error: {}", s), Error::NotAuthorized => write!(f, "Request not authorized"), } } } impl From<std::net::AddrParseError> for Error { fn from(err: std::net::AddrParseError) -> Self { Error::AddrParse(err.description().to_string()) } } impl From<hyper::error::Error> for Error { fn from(err: hyper::error::Error) -> Self { Error::Hyper(err.description().to_string()) } } impl From<hyper::http::Error> for Error { fn from(err: hyper::http::Error) -> Self { Error::HyperHTTP(err.description().to_string()) } } impl From<tokio::timer::Error> for Error { fn from(_: tokio::timer::Error) -> Self { Error::TimerError } } impl From<serde_json::Error> for Error { fn from(err: serde_json::Error) -> Self { Error::JSON(format!("{:#?}", err)) } } impl From<std::io::Error> for Error { fn from(err: std::io::Error) -> Self { Error::IO(err.description().to_string()) } } impl From<hmac::crypto_mac::InvalidKeyLength> for Error { fn from(_: hmac::crypto_mac::InvalidKeyLength) -> Self { Error::Hmac } }
true
294de65b9912ccdc30a42a3727c468adb7f59b3a
Rust
softprops/dynomite
/dynomite/trybuild-tests/fail/incorrect-fn-path-in-skip-serializing-if.rs
UTF-8
684
2.59375
3
[ "MIT" ]
permissive
use dynomite::{Attributes}; #[derive(Attributes)] struct Test1 { #[dynomite(skip_serializing_if = "true")] field: u32, } #[derive(Attributes)] struct Test2 { #[dynomite(skip_serializing_if = "2 + 2")] field: u32, } #[derive(Attributes)] struct Test3 { #[dynomite(skip_serializing_if = "|| true")] field: u32, } #[derive(Attributes)] struct Test4 { #[dynomite(skip_serializing_if = "invalid_fn")] field: u32, } fn invalid_fn() -> bool { true } #[derive(Attributes)] struct Test5 { #[dynomite(skip_serializing_if = "module::invalid_fn_in_module")] field: u32, } mod module { pub(super) fn invalid_fn_in_module() {} } fn main() {}
true
bbba9c5e53bd6bf93cf16f357672f50c719522b9
Rust
iCodeIN/css-1
/src/optimize.rs
UTF-8
661
2.859375
3
[ "Apache-2.0" ]
permissive
use std::fs; use std::io::Error; use std::process; use crate::css; pub fn css(file: &str) -> Result<(), Error> { let contents = match fs::read_to_string(file) { Ok(str) => str, Err(e) => return Err(e), }; let optimized = match css::optimize(contents) { Ok(opt) => opt, Err(e) => { eprintln!("Error parsing file {}!", file); eprintln!("{}", e); process::exit(1); } }; // Add min to file let mut split: Vec<&str> = file.split(".").collect(); split.insert(split.len() - 1, "min"); let out_file = split.join("."); fs::write(out_file, optimized) }
true
152af7a1c0036867adcc8454e8b74a5784d9548e
Rust
Nugine/heng-rs
/heng-utils/src/queue.rs
UTF-8
408
3.171875
3
[]
no_license
pub struct Queue<T> { tx: async_channel::Sender<T>, rx: async_channel::Receiver<T>, } impl<T: Send> Queue<T> { pub fn unbounded() -> Self { let (tx, rx) = async_channel::unbounded(); Self { tx, rx } } pub async fn push(&self, value: T) { self.tx.send(value).await.unwrap(); } pub async fn pop(&self) -> T { self.rx.recv().await.unwrap() } }
true
12711b438c36484e00588468906c42d0be841e28
Rust
bwhetherington/rust-lisp
/src/errors.rs
UTF-8
1,070
2.90625
3
[]
no_license
use values::Value; use sexpr::SExpr; pub fn arity_at_least(expected: usize, found: usize) -> String { format!("Expected at least {} arg(s), found {}.", expected, found) } pub fn arity_at_most(expected: usize, found: usize) -> String { format!("Expected at most {} arg(s), found {}.", expected, found) } pub fn arity_exact(expected: usize, found: usize) -> String { format!("Expected {} arg(s), found {}.", expected, found) } pub fn unbound(ident: &str) -> String { format!("Variable {} is unbound.", ident) } pub fn not_a_function(val: &Value) -> String { format!("{} is not a function.", val) } pub fn not_a_number(val: &Value) -> String { format!("{} is not a number.", val) } pub fn not_an_identifier(val: &SExpr) -> String { format!("{} is not an identifier.", val) } pub fn not_a_list(val: &SExpr) -> String { format!("{} is not a list.", val) } pub fn not_a_bool(val: &SExpr) -> String { format!("{} is not a bool.", val) } pub fn reserved_word(val: &str) -> String { format!("\"{}\" is a reserved word.", val) }
true
0b386dfedff3afdaf40a630b1296388b3c2f68cd
Rust
acshi/jlrs
/jlrs/src/wrappers/ptr/function.rs
UTF-8
5,463
2.75
3
[ "MIT" ]
permissive
//! Wrapper for `Function`, the super type of all Julia functions. //! //! All Julia functions are subtypes of `Function`, a function can be called with the methods //! of the [`Call`] trait. Note that you don't need to cast a [`Value`] to a [`Function`] in order //! to call it because [`Value`] also implements [`Call`]. //! //! [`Call`]: crate::wrappers::ptr::call::Call use jl_sys::jl_value_t; use std::{marker::PhantomData, ptr::NonNull}; use super::{ call::{Call, CallExt, WithKeywords}, datatype::DataType, private::Wrapper as WrapperPriv, value::Value, Wrapper, }; use crate::{ error::{JlrsError, JlrsResult, JuliaResultRef, CANNOT_DISPLAY_TYPE}, impl_debug, layout::{ typecheck::{NamedTuple, Typecheck}, valid_layout::ValidLayout, }, memory::{frame::Frame, global::Global, scope::Scope}, private::Private, }; /// A Julia function. #[derive(Clone, Copy)] #[repr(transparent)] pub struct Function<'scope, 'data> { inner: NonNull<jl_value_t>, _scope: PhantomData<&'scope ()>, _data: PhantomData<&'data ()>, } impl<'scope, 'data> Function<'scope, 'data> { /// Returns the `DataType` of this function. In Julia, every function has its own `DataType`. pub fn datatype(self) -> DataType<'scope> { self.as_value().datatype() } } unsafe impl ValidLayout for Function<'_, '_> { fn valid_layout(ty: Value) -> bool { let global = unsafe { Global::new() }; let function_type = DataType::function_type(global); ty.subtype(function_type.as_value()) } } unsafe impl Typecheck for Function<'_, '_> { fn typecheck(t: DataType) -> bool { <Self as ValidLayout>::valid_layout(t.as_value()) } } impl_debug!(Function<'_, '_>); impl<'scope, 'data> WrapperPriv<'scope, 'data> for Function<'scope, 'data> { type Wraps = jl_value_t; const NAME: &'static str = "Function"; unsafe fn wrap_non_null(inner: NonNull<Self::Wraps>, _: Private) -> Self { Self { inner, _scope: PhantomData, _data: PhantomData, } } fn unwrap_non_null(self, _: Private) -> NonNull<Self::Wraps> { self.inner } } impl<'data> Call<'data> for Function<'_, 'data> { unsafe fn call0<'target, 'current, S, F>(self, scope: S) -> JlrsResult<S::JuliaResult> where S: Scope<'target, 'current, 'data, F>, F: Frame<'current>, { self.as_value().call0(scope) } unsafe fn call1<'target, 'current, S, F>( self, scope: S, arg0: Value<'_, 'data>, ) -> JlrsResult<S::JuliaResult> where S: Scope<'target, 'current, 'data, F>, F: Frame<'current>, { self.as_value().call1(scope, arg0) } unsafe fn call2<'target, 'current, S, F>( self, scope: S, arg0: Value<'_, 'data>, arg1: Value<'_, 'data>, ) -> JlrsResult<S::JuliaResult> where S: Scope<'target, 'current, 'data, F>, F: Frame<'current>, { self.as_value().call2(scope, arg0, arg1) } unsafe fn call3<'target, 'current, S, F>( self, scope: S, arg0: Value<'_, 'data>, arg1: Value<'_, 'data>, arg2: Value<'_, 'data>, ) -> JlrsResult<S::JuliaResult> where S: Scope<'target, 'current, 'data, F>, F: Frame<'current>, { self.as_value().call3(scope, arg0, arg1, arg2) } unsafe fn call<'target, 'current, 'value, V, S, F>( self, scope: S, args: V, ) -> JlrsResult<S::JuliaResult> where V: AsMut<[Value<'value, 'data>]>, S: Scope<'target, 'current, 'data, F>, F: Frame<'current>, { self.as_value().call(scope, args) } unsafe fn call0_unrooted<'target>( self, global: Global<'target>, ) -> JuliaResultRef<'target, 'data> { self.as_value().call0_unrooted(global) } unsafe fn call1_unrooted<'target>( self, global: Global<'target>, arg0: Value<'_, 'data>, ) -> JuliaResultRef<'target, 'data> { self.as_value().call1_unrooted(global, arg0) } unsafe fn call2_unrooted<'target>( self, global: Global<'target>, arg0: Value<'_, 'data>, arg1: Value<'_, 'data>, ) -> JuliaResultRef<'target, 'data> { self.as_value().call2_unrooted(global, arg0, arg1) } unsafe fn call3_unrooted<'target>( self, global: Global<'target>, arg0: Value<'_, 'data>, arg1: Value<'_, 'data>, arg2: Value<'_, 'data>, ) -> JuliaResultRef<'target, 'data> { self.as_value().call3_unrooted(global, arg0, arg1, arg2) } unsafe fn call_unrooted<'target, 'value, V>( self, global: Global<'target>, args: V, ) -> JuliaResultRef<'target, 'data> where V: AsMut<[Value<'value, 'data>]>, { self.as_value().call_unrooted(global, args) } } impl<'target, 'current, 'value, 'data> CallExt<'target, 'current, 'value, 'data> for Function<'value, 'data> { fn with_keywords(self, kws: Value<'value, 'data>) -> JlrsResult<WithKeywords<'value, 'data>> { if !kws.is::<NamedTuple>() { let type_str = kws.datatype().display_string_or(CANNOT_DISPLAY_TYPE); Err(JlrsError::NotANamedTuple { type_str })? } Ok(WithKeywords::new(self.as_value(), kws)) } }
true