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
8c94fd9a88f4069d0e428aa68831fb84d80bcf1b
Rust
anagav/advent_code_rust
/src/bin/day1.rs
UTF-8
786
2.96875
3
[]
no_license
#[allow(non_snake_case)] #[allow(dead_code)] use std::io; use std::io::prelude::*; pub fn run() { //let mut map = HashMap::new(); let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let (count,basement) = input.trim().chars().map( |x| match x{ '(' => 1, ')' => -1, _ => panic!("invalid input: {}",x) } ).enumerate().fold( (0,None), |(count,basement),(elem_pos,elem)| { let temp_count = count+elem; (temp_count, if temp_count == -1 { basement.or(Some(elem_pos+1)) } else {basement}) } ); println!("counter: {:?} \nbasement: {:?}", count,basement.unwrap_or_else( ||{ 0 }) ); } fn main() { run(); }
true
75336afd593a2c89904591556069356da1bb9b35
Rust
wvanbreukelen/rust-research
/src/hal/pin.rs
UTF-8
1,992
2.5625
3
[]
no_license
pub use cortex_m::peripheral::syst; //pub use sam3x8e as target; // #[macro_use] // // Source: https://github.com/stm32-rs/stm32f4xx-hal/blob/9dab1701bc68efe3a1df8eb3b93c866d7ef1fa0e/src/lib.rs // #[cfg(not(feature = "device-selected"))] // compile_error!("This crate requires one of the following device features enabled: // sam3x8e // stm...."); // Trait objects with difference types, Rust doesn't have inheritance: https://doc.rust-lang.org/1.30.0/book/2018-edition/ch17-02-trait-objects.html pub struct IsDisabled; pub struct IsEnabled; pub struct IsInput; pub struct IsOutput; pub struct Unknown; // Macro for PIOA, PIOB, PIOC, PIOD generation // https://stackoverflow.com/questions/51932944/how-to-match-rusts-if-expressions-in-a-macro pub struct Pin<'a, PORT, STATE, DIRECTION> { pub port: &'a PORT, pub port_offset: u32, pub state: STATE, pub direction: DIRECTION, // is output } pub trait PinConfigure<PORT, STATE, DIRECTION> { fn disable(&self) -> Pin<PORT, IsDisabled, Unknown>; fn as_output(&self) -> Pin<PORT, IsEnabled, IsOutput>; fn as_input(&self) -> Pin<PORT, IsEnabled, IsInput>; fn enable_pullup(&self); fn disable_pullup(&self); } pub trait PinWrite { fn set_state(&self, s: bool) { if s { self.set_high(); } else { self.set_low(); } } fn set_high(&self); fn set_low(&self); } pub trait PinRead { fn get_state(&self) -> bool; fn is_low(&self) -> bool { !self.get_state() } fn is_high(&self) -> bool { self.get_state() } } pub fn create_pin<'a, PORT>( _port: &'a PORT, _port_offset: u32, ) -> Pin<'a, PORT, IsDisabled, Unknown> { Pin { port: _port, port_offset: _port_offset, direction: Unknown, state: IsDisabled, } } #[macro_export] macro_rules! create_pin { ($PIOX:expr, $PIOX_OFFSET:expr) => { create_pin($PIOX, $PIOX_OFFSET as u32); }; }
true
e34ed5dffca59b990151aba4b3acbce2904b7b7f
Rust
samscott89/ReCrypt
/src/profile.rs
UTF-8
7,089
2.59375
3
[ "MIT" ]
permissive
//! Methods to profile schemes extern crate rand; extern crate time; use super::*; use generic::*; use io::*; use std::fs::{metadata,remove_dir_all,create_dir,File}; use std::io::{Write,BufWriter}; use std::path::{Path,PathBuf}; use std::env; // type ProfileCipher = Kss<RingAes, RingAes>; type ProfileCipher = ReCrypt<RingAes, KhPrf>; pub fn run_all() { profile_init(); println!("{:20} {:>15} {:>18} {:>18} {:>15}", "Profile", "Average Time", "Min Time", "Max Time", "Iterations"); let params = vec![(1000,1), (100,1024), (100,1024*1024), (1, 1024*1024*1024)]; println!("\nReCrypt<RingAes, KhPrf>"); for (iterations,size) in params { profile_init(); profile_upenc::<ProfileCipher>(iterations, size); profile_clean(); } } // Run and time a closure and print the results. // NOTE: This is not quite right, ideally we should run setup code each time // to allow parameters to differ. fn run_profile<F, R, G, Args, InArgs: Copy>(name: &str, iterations: usize, setup_args: InArgs, setup: &G, closure: F) where F: FnMut(Args) -> R, G: Fn(InArgs) -> Args { let (avg_time,min_time,max_time) = profile_code(iterations, setup_args, setup, closure); println!("{:20} {:>15} ns {:>15} ns {:>15} ns {:>10}", name, fmt_val(avg_time), fmt_val(min_time), fmt_val(max_time), iterations); } // Run and time a closure and print the results. fn profile_code<F, R, G, Args, InArgs: Copy>(iterations: usize, setup_args: InArgs, setup: &G, mut closure: F) -> (u64,u64,u64) where F: FnMut(Args) -> R, G: Fn(InArgs) -> Args { let mut accum_time = 0; let mut min_time = u64::max_value(); let mut max_time = 0; for _ in 0..iterations { let input = setup(setup_args); let start = time::precise_time_ns(); closure(input); let end = time::precise_time_ns(); let time = end - start; if time > max_time { max_time = time; } if time < min_time { min_time = time; } accum_time += time; } let avg_time = accum_time/iterations as u64; (avg_time,min_time,max_time) } fn profile_upenc<Scheme: UpEnc>(iterations:usize, bytes:usize) { let prep_pt = &|l|{ let k = Scheme::keygen(); let m = random_vec(l); let pt_path = get_tmp_fname("upenc-profile"); create_test_file(&pt_path, &m); (k, pt_path) }; let enc = &|(k, pt_path)|{ let ct_path = get_tmp_fname("upenc-profile"); let mut pt_file = open_file(&pt_path); let mut ct_h = File::create(extend_path(&ct_path, "_h")).unwrap(); let mut ct_b = File::create(extend_path(&ct_path, "_b")).unwrap(); Scheme::encrypt(k, &mut pt_file, &mut ct_h, &mut ct_b).unwrap(); ct_path }; let prep_ct = &|l|{ let (k, pt_path) = prep_pt(l); let ct_path = enc((k.clone(), pt_path)); (k, ct_path) }; let rekeygen = &|(k1, ct_path)|{ let k2 = Scheme::keygen(); let token_path = get_tmp_fname("upenc-profile"); let mut ct_h = File::open(extend_path(&ct_path, "_h")).unwrap(); let mut token_file = open_file(&token_path); Scheme::rekeygen(k1, k2.clone(), &mut ct_h, &mut token_file).unwrap(); (k2, token_path) }; let prep_up_ct = &|l|{ let (k, ct_path) = prep_ct(l); let (k2, token_path) = rekeygen((k, ct_path.clone())); (k2, token_path, ct_path) }; let reenc = &|(_, token_path, ct_path)|{ let ct2_path = get_tmp_fname("upenc-profile"); let mut token_file = open_file(&token_path); let mut ct1_h = File::open(extend_path(&ct_path, "_h")).unwrap(); let mut ct1_b = File::open(extend_path(&ct_path, "_b")).unwrap(); let mut ct2_h = File::create(extend_path(&ct2_path, "_h")).unwrap(); let mut ct2_b = File::create(extend_path(&ct2_path, "_b")).unwrap(); Scheme::reencrypt(&mut token_file, &mut ct1_h, &mut ct1_b, &mut ct2_h, &mut ct2_b).unwrap(); ct2_path }; let prep_final_ct = &|l|{ let (k2, token_path, ct_path) = prep_up_ct(l); let ct2_path = reenc((k2.clone(), token_path, ct_path.clone())); (k2, ct2_path) }; let dec = &|(k, ct_path)|{ let pt = get_tmp_fname("upenc-profile"); let mut pt_file = open_file(&pt); let mut ct_h = File::open(extend_path(&ct_path, "_h")).unwrap(); let mut ct_b = File::open(extend_path(&ct_path, "_b")).unwrap(); Scheme::decrypt(k, &mut ct_h, &mut ct_b, &mut pt_file).unwrap() }; run_profile("KeyGen", iterations, (),&|()|{ }, |()|{ Scheme::keygen() }); let enc_text = format!("Enc {}", get_display_size(bytes)); let rkg_text = format!("ReKeyGen {}", get_display_size(bytes)); let re_text = format!("ReEnc {}", get_display_size(bytes)); let dec_text = format!("Decrypt {}", get_display_size(bytes)); run_profile(&enc_text, iterations, bytes, prep_pt, enc); run_profile(&rkg_text, iterations, bytes, prep_ct, rekeygen); run_profile(&re_text, iterations, bytes, prep_up_ct, reenc); run_profile(&dec_text, iterations, bytes, prep_final_ct, dec); } // Converts byte count into a human-readable strings. Examples: // 100 B // 50 KB // 13.3 MB fn get_display_size(n:usize) -> String { let kb = 1024; let mb = 1024*kb; let gb = 1024*mb; let (factor,appendix) = match n { x if x >= gb => (gb,"GB"), x if x >= mb => (mb,"MB"), x if x >= kb => (kb,"KB"), _ => (1,"B") }; format!("{} {}", (n as f32)/(factor as f32), appendix) } // Writes the specified contents to a file. fn create_test_file(fname: &Path, contents: &[u8]) { let f = open_file(fname); let mut writer = BufWriter::new(f); writer.write_all(contents).unwrap(); } fn fmt_val(x: u64) -> String { let mut output: String = String::new(); let mut y = x; while y/1000 > 0 { output = format!(",{:0>3}{}", y%1000,output); y = y/1000; } format!("{}{}", y%1000, output) } fn extend_path(p: &PathBuf, ext: &str) -> PathBuf { PathBuf::from(String::from(p.as_path().to_str().unwrap()) + ext) } fn profile_init(){ let test_dir = env::temp_dir().join("upenc-profile"); remove_dir_all(&test_dir).unwrap_or(()); create_dir(&test_dir).unwrap(); } fn profile_clean(){ let test_dir = env::temp_dir().join("upenc-profile"); remove_dir_all(&test_dir).unwrap_or(()); } pub fn get_tmp_fname(prefix: &str) -> PathBuf { let mut tmp_path = env::temp_dir(); tmp_path.push(prefix); if !metadata(&tmp_path).is_ok(){ create_dir(&tmp_path).expect(&format!("could not create tmp directory: {:?}", tmp_path)); } let r = rand::random::<u64>(); tmp_path.join(format!("{}", r)) } pub fn random_vec(n: usize) -> Vec<u8> { let mut v = Vec::new(); for _ in 0..n { v.push(rand::random::<u8>()); } v }
true
721a821355cac2b57a86188534b50b713f8b9cc6
Rust
no111u3/ist7920
/src/mode/buffered_graphics.rs
UTF-8
2,423
2.90625
3
[ "Apache-2.0" ]
permissive
use crate::Ist7920; use display_interface::{DisplayError, WriteOnlyDataCommand}; #[derive(Debug, Clone)] pub struct BufferedGraphicsMode { buffer: [u8; 128 * 128 / 8], } impl BufferedGraphicsMode { /// Create a new buffered graphics mode instance pub(crate) fn new() -> Self { Self { buffer: [0; 128 * 128 / 8], } } } impl<DI> Ist7920<DI, BufferedGraphicsMode> where DI: WriteOnlyDataCommand, { /// Clear the display buffer. You need to call `disp.flush()` for any effect on the screen. pub fn clear(&mut self) { self.mode.buffer = [0; 128 * 128 / 8]; } /// Write out data to the display. /// TODO: Rewrite to more efficient implementation pub fn flush(&mut self) -> Result<(), DisplayError> { Self::flush_buffer_chunks(&mut self.interface, &self.mode.buffer) } /// Turn a pixel on or off. A non-zero `value` is treated as on, `0` as off. If the X and Y /// coordinates are out of the bounds of the display, this method call is a noop. pub fn set_pixel(&mut self, x: u32, y: u32, value: bool) { let value = value as u8; let idx = ((y as usize) / 8 * 128 as usize) + (x as usize); let bit = y % 8; if let Some(byte) = self.mode.buffer.get_mut(idx) { // Set pixel value in byte *byte = *byte & !(1 << bit) | (value << bit) } } } #[cfg(feature = "graphics")] use embedded_graphics_core::{ draw_target::DrawTarget, geometry::Size, geometry::{Dimensions, OriginDimensions}, pixelcolor::BinaryColor, Pixel, }; #[cfg(feature = "graphics")] impl<DI> DrawTarget for Ist7920<DI, BufferedGraphicsMode> where DI: WriteOnlyDataCommand, { type Color = BinaryColor; type Error = DisplayError; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { let bb = self.bounding_box(); pixels .into_iter() .filter(|Pixel(pos, _color)| bb.contains(*pos)) .for_each(|Pixel(pos, color)| { self.set_pixel(pos.x as u32, pos.y as u32, color.is_on()) }); Ok(()) } } #[cfg(feature = "graphics")] impl<DI> OriginDimensions for Ist7920<DI, BufferedGraphicsMode> where DI: WriteOnlyDataCommand, { fn size(&self) -> Size { Size::new(128, 128) } }
true
243afd7cc5df51dbad462b888ede42b23e0f7adf
Rust
joaonmatos/exercism
/rust/rna-transcription/src/lib.rs
UTF-8
1,824
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
// Copyright 2020 João Nuno Matos // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[derive(Debug, PartialEq)] pub struct DNA { strand: String, } #[derive(Debug, PartialEq)] pub struct RNA { strand: String, } impl DNA { pub fn new(dna: &str) -> Result<DNA, usize> { let bad_char = dna .chars() .position(|c| !(c == 'A' || c == 'C' || c == 'G' || c == 'T')); match bad_char { Some(index) => Err(index), None => Ok(Self { strand: String::from(dna), }), } } pub fn into_rna(self) -> RNA { RNA { strand: self .strand .chars() .map(|c| match c { 'G' => 'C', 'C' => 'G', 'T' => 'A', 'A' => 'U', _ => unreachable!(), }) .collect(), } } } impl RNA { pub fn new(rna: &str) -> Result<RNA, usize> { let bad_char = rna .chars() .position(|c| !(c == 'A' || c == 'C' || c == 'G' || c == 'U')); match bad_char { Some(index) => Err(index), None => Ok(Self { strand: String::from(rna), }), } } }
true
931a245a52cb42f8481b72ced2a19d452446d031
Rust
scritchley/stm32-dsp
/src/dsp/mod.rs
UTF-8
9,520
2.875
3
[]
no_license
use micromath::F32Ext; use no_std_compat::slice::IterMut; pub trait IntoF32 { fn into_f32(self) -> f32; } impl IntoF32 for u16 { fn into_f32(self) -> f32 { self as i16 as f32 } } pub trait FromF32 { fn from_f32(value: f32) -> Self; } impl FromF32 for u16 { fn from_f32(value: f32) -> Self { value.round() as i16 as u16 } } pub trait Processor { fn process(&mut self, input: &Buffer, output: &mut Buffer); } pub struct DelayLine { delay_buffer: [u16; 50000], delay_index: usize, } impl DelayLine { pub fn new() -> Self { Self { delay_buffer: [0u16; 50000], delay_index: 0, } } } impl Processor for DelayLine { fn process(&mut self, input: &Buffer, output: &mut Buffer) { let l = self.delay_buffer.len(); let mut output_iter = output.buffer.iter_mut(); for rx in input.buffer.iter() { let tx = output_iter.next().unwrap(); let out = self.delay_buffer[self.delay_index % l]; *tx = out.into_f32(); self.delay_buffer[self.delay_index % l] = u16::from_f32(*rx); self.delay_index += 1; } } } pub struct PitchShift { buf: [f32; 5000], wp: f32, rp: f32, shift: f32, xf: f32, hp: HighPass, } impl PitchShift { pub fn new() -> Self { Self { buf: [0f32; 5000], wp: 0f32, rp: 0f32, shift: 1.5f32, xf: 1f32, hp: HighPass::new(), } } } impl Processor for PitchShift { fn process(&mut self, input: &Buffer, output: &mut Buffer) { let mut iter = input.buffer.iter(); let mut output_iter = output.buffer.iter_mut(); for _ in 0..64 { let left = iter.next().unwrap(); let right = iter.next().unwrap(); let mut sum = left + right; sum = self.hp.apply(sum); // Write to ring buffer self.buf[self.wp as usize] = sum; let r1 = self.rp; let l = self.buf.len() as f32; let lh = l / 2f32; let mut r2 = r1 + lh; if r1 >= lh { r2 = r1 - lh; } let rd0 = self.buf[r1 as usize]; let rd1 = self.buf[r2 as usize]; let overlap = 500f32; //Check if first readpointer starts overlap with write pointer? // if yes -> do cross-fade to second read-pointer if overlap >= (self.wp - r1) && (self.wp - r1) >= 0f32 && self.shift != 1f32 { let rel = self.wp - r1; self.xf = rel as f32 / (overlap as f32); } else if self.wp - r1 == 0f32 { self.xf = 0f32; } // //Check if second readpointer starts overlap with write pointer? // if yes -> do cross-fade to first read-pointer if overlap >= (self.wp - r2) && (self.wp - r2) >= 0f32 && self.shift != 1f32 { let rel = self.wp - r2; self.xf = 1f32 - (rel as f32 / (overlap as f32)); } else if self.wp - r2 == 0f32 { self.xf = 1f32; } // // Sum the crossfade. sum = rd0 * self.xf + rd1 * (1f32 - self.xf); self.rp += self.shift; self.wp += 1f32; if self.wp == l { self.wp = 0f32; } if self.rp >= l as f32 { self.rp = 0f32; } let ltx = output_iter.next().unwrap(); let rtx = output_iter.next().unwrap(); *ltx = sum; *rtx = sum; } } } pub struct HighPass { a0: f32, a1: f32, a2: f32, b1: f32, b2: f32, hp_in_z1: f32, hp_in_z2: f32, hp_out_z1: f32, hp_out_z2: f32, } impl HighPass { pub fn new() -> Self { Self { a0: 0.9862117951198142f32, a1: -1.9724235902396283f32, a2: 0.9862117951198142f32, b1: -1.972233470205696f32, b2: 0.9726137102735608f32, hp_in_z1: 0f32, hp_in_z2: 0f32, hp_out_z1: 0f32, hp_out_z2: 0f32, } } pub fn apply(&mut self, i: f32) -> f32 { let o = self.a0 * i + self.a1 * self.hp_in_z1 + self.a2 * self.hp_in_z2 - self.b1 * self.hp_out_z1 - self.b2 * self.hp_out_z2; self.hp_in_z2 = self.hp_in_z1; self.hp_in_z1 = i; self.hp_out_z2 = self.hp_out_z1; self.hp_out_z1 = o; o } } impl Processor for HighPass { fn process(&mut self, input: &Buffer, output: &mut Buffer) { let mut output_iter = output.buffer.iter_mut(); for rx in input.buffer.iter() { let tx = output_iter.next().unwrap(); *tx = self.apply(*rx); } } } #[derive(PartialEq)] enum CompressorState { None, Attack, GainReduction, Release, } pub struct Compressor { state: CompressorState, attack: usize, release: usize, hold: usize, timeout: usize, threshold: f32, gain_reduce: f32, gain: f32, gain_step_attack: f32, gain_step_release: f32, } impl Processor for Compressor { fn process(&mut self, input: &Buffer, output: &mut Buffer) { let mut output_iter = output.buffer.iter_mut(); for i in input.buffer.iter() { if *i > self.threshold { if self.gain >= self.gain_reduce { match self.state { CompressorState::None => { self.state = CompressorState::Attack; self.timeout = self.attack; } CompressorState::Release => { self.state = CompressorState::Attack; self.timeout = self.attack; } _ => {} } } if self.state == CompressorState::GainReduction { self.timeout = self.hold; } } if *i < self.threshold && self.gain <= 1f32 { if self.timeout == 0 && self.state == CompressorState::GainReduction { self.state = CompressorState::Release; self.timeout = self.release; } } match self.state { CompressorState::Attack => { if self.timeout > 0 && self.gain > self.gain_reduce { self.gain -= self.gain_step_attack; self.timeout -= 1; } else { self.state = CompressorState::GainReduction; self.timeout = self.hold; } } CompressorState::GainReduction => { if self.timeout > 0 { self.timeout -= 1; } else { self.state = CompressorState::Release; self.timeout = self.release; } } CompressorState::Release => { if self.timeout > 0 && self.gain < 1f32 { self.timeout -= 1; self.gain += self.gain_step_release } else { self.state = CompressorState::None; } } CompressorState::None => { if self.gain < 1f32 { self.gain = 1f32; } } } let tx = output_iter.next().unwrap(); *tx = *i * self.gain; } } } pub struct Buffer { pub buffer: [f32; 128], } impl Buffer { pub fn new() -> Self { Self { buffer: [0f32; 128], } } pub fn from_u16(input: &[u16; 128]) -> Self { let mut buffer = [0f32; 128]; for i in 0..128 { buffer[i] = input[i].into_f32(); } Self { buffer } } pub fn from_f32(input: &[f32; 128]) -> Self { Self { buffer: input.clone(), } } pub fn to_u16(&self, output: &mut [u16; 128]) { let iter = self.buffer.iter(); let mut output_iter = output.iter_mut(); for i in iter { let o = output_iter.next().unwrap(); *o = u16::from_f32(*i); } } pub fn sum_to_u16(&self, output: &mut [u16; 128]) { let iter = self.buffer.iter(); let mut output_iter = output.iter_mut(); for i in iter { let o = output_iter.next().unwrap(); *o = u16::from_f32(*i + (*o).into_f32()); } } pub fn sum(&mut self, input: &Buffer) -> &mut Self{ unsafe { cmsis_dsp_sys_pregenerated::arm_add_f32(self.buffer.as_ptr(), input.buffer.as_ptr(), self.buffer.as_mut_ptr(), 128); } self } pub fn scale(&mut self, scale: f32) -> &mut Self { unsafe { cmsis_dsp_sys_pregenerated::arm_scale_f32(self.buffer.as_ptr(), scale, self.buffer.as_mut_ptr(), 128); } self } pub fn fill(&mut self, fill: f32) -> &mut Self { unsafe { cmsis_dsp_sys_pregenerated::arm_fill_f32(fill, self.buffer.as_mut_ptr(), 128); } self } }
true
0ea33524b69a7aa96417e39a17bda2559b2e434c
Rust
sampullman/rust-scheme
/src/environment.rs
UTF-8
5,245
3.0625
3
[]
no_license
#![allow(unused_variables)] use std::collections::HashMap; use std::cell::RefCell; use std::rc::Rc; use std::mem; use atom::Atom; use interpreter::evaluate; use builtins::*; #[derive(Clone, PartialEq)] pub struct SchemeLambda { pub name: String, pub arg_list: Vec<String>, pub body: Vec<Atom>, } pub type SchemeFn = fn(env: Rc<RefCell<Environment>>, Vec<Atom>) -> Result<Atom, String>; // Necessary because I could not find a way to implement clone for SchemeFn // https://github.com/rust-lang/rust/issues/24000 pub enum SchemeFnWrap { Fn(SchemeFn), Lambda(SchemeLambda) } impl Clone for SchemeFnWrap { fn clone(&self) -> SchemeFnWrap { match self { &SchemeFnWrap::Fn(func) => SchemeFnWrap::Fn(func), &SchemeFnWrap::Lambda(ref lambda) => SchemeFnWrap::Lambda(lambda.clone()) } } } impl PartialEq for SchemeFnWrap { fn eq(&self, other: &SchemeFnWrap) -> bool { unsafe { mem::transmute::<_, usize>(self) == mem::transmute::<_, usize>(other) } } } impl SchemeLambda { pub fn new(name: String, arg_list: Vec<String>, body: Vec<Atom>) -> SchemeLambda { SchemeLambda {name: name, arg_list: arg_list, body: body} } pub fn evaluate(self, env: Rc<RefCell<Environment>>, args: Vec<Atom>) -> Result<Atom, String> { if args.len() != self.arg_list.len() { return Err(format!("{} requires {} arguments", self.name, self.arg_list.len())) } let new_env = env_spawn_child(env); let mut i = 0; for name in self.arg_list.into_iter() { env_set(new_env.clone(), name, args[i].clone()); i += 1; } let mut body_iter = self.body.iter(); for statement in body_iter.by_ref().take(self.body.len()-1) { try!(evaluate(statement.clone(), new_env.clone())); } evaluate(body_iter.last().unwrap_or(&Atom::Nil).clone(), new_env) } } #[derive(PartialEq)] pub struct Environment { parent: Option<Rc<RefCell<Environment>>>, definitions: HashMap<String, Atom>, } // Wrappers to avoid working directly with Rc/RefCell pub fn env_get(env: &Rc<RefCell<Environment>>, s: &String) -> Result<Atom, String> { env.as_ref().borrow().get_symbol(s) } pub fn env_set(env: Rc<RefCell<Environment>>, symbol: String, atom: Atom) { env.as_ref().borrow_mut().set_symbol(symbol, atom) } pub fn env_spawn_child(env: Rc<RefCell<Environment>>) -> Rc<RefCell<Environment>> { Rc::new(RefCell::new(Environment { parent: Some(env), definitions: HashMap::new() })) } impl Environment { pub fn new() -> Environment { Environment { parent: None, definitions: HashMap::new() } } pub fn standard_env() -> Rc<RefCell<Environment>> { let mut env = Environment::new(); env.set_symbol("+".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_add))); env.set_symbol("*".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_multiply))); env.set_symbol("-".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_subtract))); env.set_symbol("/".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_divide))); env.set_symbol(">".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_gt))); env.set_symbol("<".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_lt))); env.set_symbol(">=".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_ge))); env.set_symbol("<=".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_le))); env.set_symbol("=".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_eq))); env.set_symbol("abs".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_abs))); env.set_symbol("append".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_append))); env.set_symbol("apply".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_apply))); env.set_symbol("begin".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_begin))); env.set_symbol("car".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_car))); env.set_symbol("cdr".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_cdr))); env.set_symbol("cons".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_cons))); env.set_symbol("eq?".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_is_eq))); env.set_symbol("equal?".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_is_equal))); env.set_symbol("list".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_list))); env.set_symbol("list?".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_is_list))); env.set_symbol("let".to_string(), Atom::Callable(SchemeFnWrap::Fn(scheme_let))); Rc::new(RefCell::new(env)) } pub fn set_symbol(&mut self, symbol: String, atom: Atom) { self.definitions.insert(symbol, atom); } pub fn get_symbol(&self, symbol: &String) -> Result<Atom, String> { if let Some(atom) = self.definitions.get(symbol) { Ok(atom.clone()) } else { match self.parent { Some(ref parent) => env_get(&parent, symbol), None => Err(format!("Invalid definition {:?}", symbol)) } } } }
true
ba38e8d6e2bb6cdbedb31ead10bf1da1173980aa
Rust
fospring/feature_workspace
/xtask/src/main.rs
UTF-8
1,077
2.609375
3
[]
no_license
use argh::FromArgs; use std::{ env, process::{Command, Stdio}, }; /// fospring build tools #[derive(FromArgs, Debug)] struct Options { #[argh(subcommand)] command: Cmd } #[derive(FromArgs, Debug)] #[argh(subcommand)] /// Reach new heights. enum Cmd { Build(BuildCmd) } fn main() -> anyhow::Result<()> { let options: Options = argh::from_env(); match options.command { Cmd::Build(cmd) => cmd.build() } } /// build cmd #[derive(FromArgs, Debug, Default)] #[argh(subcommand, name = "build")] struct BuildCmd {} impl BuildCmd { fn build(&self) -> anyhow::Result<()> { let mut cmd = Command::new("cargo"); let pwd = env::current_dir()?; cmd.current_dir(&pwd) .stderr(Stdio::inherit()) .stdout(Stdio::piped()) .arg("rustc") .arg("--manifest-path") .arg(pwd.join("fospring").join("Cargo.toml")); let output = cmd.output()?; if !output.status.success() { anyhow::bail!("build project failed"); } Ok(()) } }
true
d7d38a9e5a0cc652bfde3743ac3c80fd2d6e0d68
Rust
vstepchik/sprack
/sprack/src/structs/mod.rs
UTF-8
1,962
2.78125
3
[ "MIT" ]
permissive
mod bin; mod node; mod options; pub use self::bin::*; pub use self::node::*; pub use self::options::*; use super::{SortHeuristic, ALL as DEFAULT_HEURISTICS}; use std::cmp::max; use std::fmt::{Debug, Result, Formatter}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct PackInput { pub dim: Dimension, pub id: u32 } pub struct PackResult<'a> { pub bins: Vec<Bin>, pub heuristics: &'a SortHeuristic } impl<'a> Debug for PackResult<'a> { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}[{}]", self.heuristics.name(), self.bins.len()) } } #[derive(Debug)] pub struct PackErr(pub &'static str); #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Dimension { pub w: u32, pub h: u32 } #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Rectangle { pub x: u32, pub y: u32, pub size: Dimension, pub flipped: bool, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct Placement { pub index: u32, pub rect: Rectangle, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Fit { No, Yes(bool), Exact(bool) } // bool is for `flipped` // =============================================================================================== impl Dimension { pub fn new(w: u32, h: u32) -> Dimension { Dimension { w, h } } pub fn fits(&self, inner: &Dimension) -> Fit { if self.w == inner.w && self.h == inner.h { return Fit::Exact(false); } if self.h == inner.w && self.w == inner.h { return Fit::Exact(true); } if self.w >= inner.w && self.h >= inner.h { return Fit::Yes(false); } if self.h >= inner.w && self.w >= inner.h { return Fit::Yes(true); } Fit::No } } impl Rectangle { pub fn t(&self) -> u32 { self.y } pub fn l(&self) -> u32 { self.x } pub fn b(&self) -> u32 { self.y + self.size.h } pub fn r(&self) -> u32 { self.x + self.size.w } pub fn non_flipped_size(&self) -> Dimension { if self.flipped { Dimension::new(self.size.h, self.size.w) } else { self.size } } }
true
20120aa8145393f2466fb2aeb7390f2840cf2d75
Rust
brightly-salty/rox
/src/parser.rs
UTF-8
10,278
3.3125
3
[]
no_license
use crate::ast::{Expr, Stmt}; use crate::error; use crate::tokens::TokenType::{ Bang, BangEqual, Class, Else, Eof, Equal, EqualEqual, False, For, Fun, Greater, GreaterEqual, Identifier, If, LeftBrace, LeftParen, Less, LessEqual, Minus, Nil, Number, Or, Plus, Print, Return, RightBrace, RightParen, Semicolon, Slash, Star, String_, True, Var, While, }; use crate::tokens::{Literal, Token, TokenType}; use anyhow::Result; pub struct Parser { tokens: Vec<Token>, current: usize, } impl Parser { pub fn new(tokens: Vec<Token>) -> Self { Self { tokens, current: 0 } } pub fn parse(&mut self) -> Vec<Stmt> { let mut statements = Vec::new(); loop { if let Some(stmt) = self.declaration() { statements.push(stmt); } if self.is_at_end() { break; } } statements } fn declaration(&mut self) -> Option<Stmt> { if self.matches(&[Var]) { if let Ok(stmt) = self.var_declaration() { Some(stmt) } else { self.synchronize(); None } } else if let Ok(stmt) = self.statement() { Some(stmt) } else { self.synchronize(); None } } fn var_declaration(&mut self) -> Result<Stmt> { let name = self.consume(&Identifier, "Expect variable name.")?; let initializer = if self.matches(&[Equal]) { self.expression().ok() } else { None }; self.consume(&Semicolon, "Expect ';' after variable declaration.")?; Ok(Stmt::Var(name, initializer)) } fn statement(&mut self) -> Result<Stmt> { if self.matches(&[For]) { self.for_statement() } else if self.matches(&[If]) { self.if_statement() } else if self.matches(&[Print]) { self.print_statement() } else if self.matches(&[While]) { self.while_statement() } else if self.matches(&[LeftBrace]) { Ok(Stmt::Block(self.block()?)) } else { self.expression_statement() } } fn for_statement(&mut self) -> Result<Stmt> { self.consume(&LeftParen, "Expect '(' after 'for'.")?; let initializer = if self.matches(&[Semicolon]) { None } else if self.matches(&[Var]) { self.var_declaration().ok() } else { self.expression_statement().ok() }; let condition = if self.check(&Semicolon) { Expr::Literal(Literal::Bool(true)) } else { self.expression()? }; self.consume(&Semicolon, "Expect ';' after loop condition.")?; let increment = if self.check(&RightParen) { None } else { self.expression().ok() }; self.consume(&RightParen, "Expect ')' after for clauses.")?; let mut body = self.statement()?; if let Some(increment) = increment { body = Stmt::Block(vec![body, Stmt::Expression(increment)]); } body = Stmt::While(condition, Box::new(body)); if let Some(initializer) = initializer { body = Stmt::Block(vec![initializer, body]); } Ok(body) } fn while_statement(&mut self) -> Result<Stmt> { self.consume(&LeftParen, "Expect '(' after 'while'.")?; let condition = self.expression()?; self.consume(&RightParen, "Expect ')' after condition.")?; let body = self.statement()?; Ok(Stmt::While(condition, Box::new(body))) } fn if_statement(&mut self) -> Result<Stmt> { self.consume(&LeftParen, "Expect '(' after 'if'.")?; let condition = self.expression()?; self.consume(&RightParen, "Expect ')' after if condition.")?; let then_branch = self.statement()?; let else_branch = if self.matches(&[Else]) { self.statement().ok() } else { None }; Ok(Stmt::If( condition, Box::new(then_branch), Box::new(else_branch), )) } fn block(&mut self) -> Result<Vec<Stmt>> { let mut statements = Vec::new(); loop { if let Some(stmt) = self.declaration() { statements.push(stmt); } if self.check(&RightBrace) || self.is_at_end() { break; } } self.consume(&RightBrace, "Expect ';' after block.")?; Ok(statements) } fn print_statement(&mut self) -> Result<Stmt> { let value = self.expression()?; self.consume(&Semicolon, "Expect ';' after value.")?; Ok(Stmt::Print(value)) } fn expression_statement(&mut self) -> Result<Stmt> { let expr = self.expression()?; self.consume(&Semicolon, "Expect ';' after expression.")?; Ok(Stmt::Expression(expr)) } fn expression(&mut self) -> Result<Expr> { self.assignment() } fn assignment(&mut self) -> Result<Expr> { let expr = self.or()?; if self.matches(&[Equal]) { let equals = self.previous(); let value = self.assignment()?; if let Expr::Variable(name) = expr { Ok(Expr::Assign(name, Box::new(value))) } else { error(equals.line, "Invalid assignment taarget."); Ok(expr) } } else { Ok(expr) } } fn or(&mut self) -> Result<Expr> { let mut expr = self.and()?; while self.matches(&[Or]) { let operator = self.previous(); let right = self.and()?; expr = Expr::Logical(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn and(&mut self) -> Result<Expr> { let mut expr = self.equality()?; while self.matches(&[Or]) { let operator = self.previous(); let right = self.equality()?; expr = Expr::Logical(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn equality(&mut self) -> Result<Expr> { let mut expr = self.comparison()?; while self.matches(&[BangEqual, EqualEqual]) { let operator = self.previous(); let right = self.comparison()?; expr = Expr::Binary(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn comparison(&mut self) -> Result<Expr> { let mut expr = self.term()?; while self.matches(&[Greater, GreaterEqual, Less, LessEqual]) { let operator = self.previous(); let right = self.term()?; expr = Expr::Binary(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn term(&mut self) -> Result<Expr> { let mut expr = self.factor()?; while self.matches(&[Plus, Minus]) { let operator = self.previous(); let right = self.factor()?; expr = Expr::Binary(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn factor(&mut self) -> Result<Expr> { let mut expr = self.unary()?; while self.matches(&[Slash, Star]) { let operator = self.previous(); let right = self.unary()?; expr = Expr::Binary(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn unary(&mut self) -> Result<Expr> { if self.matches(&[Bang, Minus]) { let operator = self.previous(); let right = self.unary()?; Ok(Expr::Unary(operator, Box::new(right))) } else { self.primary() } } fn primary(&mut self) -> Result<Expr> { if self.matches(&[False]) { return Ok(Expr::Literal(Literal::Bool(false))); } if self.matches(&[True]) { return Ok(Expr::Literal(Literal::Bool(true))); } if self.matches(&[Nil]) { return Ok(Expr::Literal(Literal::Nil)); } if self.matches(&[Number, String_]) { return Ok(Expr::Literal(match self.previous().literal { Some(l) => l, None => Literal::Nil, })); } if self.matches(&[Identifier]) { return Ok(Expr::Variable(self.previous())); } if self.matches(&[LeftParen]) { let expr = self.expression()?; self.consume(&RightParen, "Expect `)` after expression")?; return Ok(Expr::Grouping(Box::new(expr))); } crate::error_at_token(&self.peek(), "Expect expression"); Err(anyhow!("Parse error")) } fn synchronize(&mut self) { self.advance(); while !self.is_at_end() { if self.previous().type_ == Semicolon { return; } match self.peek().type_ { Class | Fun | Var | For | If | While | Print | Return => { return; } _ => {} } self.advance(); } } fn matches(&mut self, types: &[TokenType]) -> bool { for type_ in types { if self.check(type_) { self.advance(); return true; } } false } fn consume(&mut self, type_: &TokenType, message: &str) -> Result<Token> { if self.check(type_) { Ok(self.advance()) } else { crate::error_at_token(&self.peek(), message); Err(anyhow!("Parse error")) } } fn check(&self, type_: &TokenType) -> bool { if self.is_at_end() { false } else { &self.peek().type_ == type_ } } fn advance(&mut self) -> Token { if !self.is_at_end() { self.current += 1; } self.previous() } fn is_at_end(&self) -> bool { self.peek().type_ == Eof } fn peek(&self) -> Token { self.tokens[self.current].clone() } fn previous(&self) -> Token { self.tokens[self.current - 1].clone() } }
true
4e022df829565ecac2a9211d18171e21ee155067
Rust
devillove084/reclaim
/src/unprotected.rs
UTF-8
4,193
2.78125
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use core::fmt; use core::marker::PhantomData; use typenum::Unsigned; use crate::internal::Internal; use crate::pointer::{Marked, MarkedNonNull, MarkedNonNullable, MarkedPointer}; use crate::{Reclaim, Shared, Unprotected}; /********** impl Clone ****************************************************************************/ impl<T, R, N> Clone for Unprotected<T, R, N> { #[inline] fn clone(&self) -> Self { Self { inner: self.inner, _marker: PhantomData } } } /********** impl Copy *****************************************************************************/ impl<T, R: Reclaim, N> Copy for Unprotected<T, R, N> {} /********** impl MarkedPointer ********************************************************************/ impl<T, R: Reclaim, N: Unsigned> MarkedPointer for Unprotected<T, R, N> { impl_trait!(unprotected); } /********** impl inherent *************************************************************************/ impl<T, R: Reclaim, N: Unsigned> Unprotected<T, R, N> { impl_inherent!(unprotected); /// Dereferences the `Unprotected`, returning the resulting reference which /// is not bound to the lifetime of `self`. /// /// # Safety /// /// Since the pointed-to value is not protected from reclamation it could /// be freed at any point (even before calling this method). Hence, this /// method is only safe to call if the caller can guarantee that no /// reclamation can occur, e.g. when records are never retired at all. /// /// # Example /// /// ... #[inline] pub unsafe fn deref_unprotected<'a>(self) -> &'a T { self.inner.as_ref_unbounded() } /// Decomposes the `Unprotected`, returning the reference (which is not /// bound to the lifetime of `self`) itself and the separated tag. /// /// # Safety /// /// Since the pointed-to value is not protected from reclamation it could /// be freed at any point (even before calling this method). Hence, this /// method is only safe to call if the caller can guarantee that no /// reclamation can occur, e.g. when records are never retired at all. #[inline] pub unsafe fn decompose_ref_unprotected<'a>(self) -> (&'a T, usize) { self.inner.decompose_ref_unbounded() } /// Consumes the `unprotected` and converts it to a [`Shared`] reference /// with arbitrary lifetime. /// /// # Safety /// /// The returned reference is not in fact protected and could be reclaimed /// by other threads, so the caller has to ensure no concurrent reclamation /// is possible. #[inline] pub unsafe fn into_shared<'a>(unprotected: Self) -> Shared<'a, T, R, N> { Shared::from_marked_non_null(unprotected.inner) } /// Casts the [`Unprotected`] to a reference to a different type. #[inline] pub fn cast<U>(unprotected: Self) -> Unprotected<U, R, N> { Unprotected { inner: unprotected.inner.cast(), _marker: PhantomData } } } /********** impl Debug ****************************************************************************/ impl<T, R: Reclaim, N: Unsigned> fmt::Debug for Unprotected<T, R, N> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (ptr, tag) = self.inner.decompose(); f.debug_struct("Shared").field("ptr", &ptr).field("tag", &tag).finish() } } /********** impl Pointer **************************************************************************/ impl<T, R: Reclaim, N: Unsigned> fmt::Pointer for Unprotected<T, R, N> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Pointer::fmt(&self.inner.decompose_ptr(), f) } } /********** impl NonNullable **********************************************************************/ impl<T, R, N: Unsigned> MarkedNonNullable for Unprotected<T, R, N> { type Item = T; type MarkBits = N; #[inline] fn into_marked_non_null(self) -> MarkedNonNull<Self::Item, Self::MarkBits> { self.inner } } /********** impl Internal *************************************************************************/ impl<T, R, N> Internal for Unprotected<T, R, N> {}
true
99dbf37a70d03bea513ecc9a970735845ce6fe05
Rust
kerskuchen/Advent-of-Code-2017-Rust
/day4_high_entropy_passphrases/src/main.rs
UTF-8
1,087
3.3125
3
[ "Unlicense" ]
permissive
extern crate itertools; use itertools::Itertools; use std::fs::File; use std::io::*; fn main() { let lines: Vec<Vec<String>> = BufReader::new(File::open("input.txt").unwrap()) .lines() .filter_map(|line| line.ok()) .map(|line| { line.trim() .split_whitespace() .map(|word| word.to_string()) .collect() }) .collect(); println!( "Number of valid passphrases: {}", // Count the lines where the number of unique words is the number of total words lines .iter() .filter(|line| line.iter().unique().count() == line.len()) .count() ); println!( "Number of valid anagram passphrases: {:?}", // Count the lines where the number of unique sorted words is the number of total words lines .iter() .filter(|line| line.iter() .map(|word| word.chars().sorted()) .unique() .count() == line.len()) .count() ); }
true
d0a1e97ee74b6d2b073607df95ee8cd7f9217cc9
Rust
uu-haunter/busplus
/server/src/config.rs
UTF-8
5,554
3.359375
3
[]
no_license
//! Utility for reading values from a config file. use std::fs; use std::path::Path; use yaml_rust::{Yaml, YamlLoader}; /// The file path to the config file. pub const CONFIG_FILE_PATH: &str = "../config.yml"; /// The YAML key where all trafiklab data is stored. /// Example: /// /// trafiklab_api: <-- this is the key /// api_key: a12b34c567d89 /// const TRAFIKLAB_YAML_KEY: &str = "trafiklab_api"; const DATABASE_YAML_KEY: &str = "database"; /// Stores the parsed contents of a YAML config file. pub struct Config { documents: Vec<Yaml>, } impl Config { pub fn new() -> Self { Config { documents: Vec::new(), } } /// Loads the config from a file path and tries to parse it from YAML. pub fn load_config(&mut self, config_path: &str) -> Result<(), String> { // Read the contents of the config file into a string. let config_file_contents = fs::read_to_string(Path::new(config_path)); if config_file_contents.is_err() { return Err(format!( "Could not load config file from {:?}.", config_path )); } // Parse the contents of the config file to YAML. let config = YamlLoader::load_from_str(&config_file_contents.unwrap()); if config.is_err() { return Err("Could not parse contents of the config file into YAML.".to_owned()); } // Store the parsed YAML contents. self.documents = config.unwrap(); Ok(()) } /// Returns a reference to the Yaml document that contains relevant data fn get_config_docuemnt(&self) -> Option<&Yaml> { // If the documents vector is empty that means we haven't loaded in any config // file yet, so None is returned. if self.documents.is_empty() { return None; } Some(&self.documents[0]) } /// Gets a key value from the config section in the config file as a `&str` pub fn get_config_value_str(&self, field: &str, key: &str) -> Option<&str> { let document = match self.get_config_docuemnt() { Some(doc) => doc, None => return None, }; document[field][key].as_str() } /// Gets a key value from the config section in the config file as a `f64` pub fn get_config_value_f64(&self, field: &str, key: &str) -> Option<f64> { let document = match self.get_config_docuemnt() { Some(doc) => doc, None => return None, }; document[field][key].as_f64() } /// Returns a value from the trafiklab section in the config file as a `f64` pub fn get_trafiklab_value_f64(&self, key: &str) -> Option<f64> { self.get_config_value_f64(TRAFIKLAB_YAML_KEY, key) } /// Returns a value from the trafiklab section in the config file as a `&str` pub fn get_trafiklab_value_str(&self, key: &str) -> Option<&str> { self.get_config_value_str(TRAFIKLAB_YAML_KEY, key) } /// Returns a value from the database section in the config file as a `&str` pub fn get_database_value(&self, key: &str) -> Option<&str> { self.get_config_value_str(DATABASE_YAML_KEY, key) } } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::Write; use tempdir::TempDir; const TEST_DIRECTORY_NAME: &str = "config_test_dir"; const TEST_FILE_NAME: &str = "test_config.yml"; const TEST_API_KEY: &str = "api_key"; const TEST_API_KEY_VALUE: &str = "a12b34c567d89"; const TEST_DATABASE_KEY: &str = "test_uri"; const TEST_DATABASE_KEY_VALUE: &str = "testconnectionstring"; #[test] fn test_config() -> std::io::Result<()> { let yaml_content: String = format!( " {}: {}: {} {}: {}: {} ", TRAFIKLAB_YAML_KEY, TEST_API_KEY, TEST_API_KEY_VALUE, DATABASE_YAML_KEY, TEST_DATABASE_KEY, TEST_DATABASE_KEY_VALUE ); // Create a temporary directory to create the config file in. let dir = TempDir::new(TEST_DIRECTORY_NAME)?; let file_path = dir.path().join(TEST_FILE_NAME); eprintln!("FILE PATH: {:?}", file_path); // Create the file containing the yaml content. let mut test_file = File::create(&file_path)?; test_file.write_all(yaml_content.as_bytes())?; let mut config_handler = Config::new(); // Make sure that the config is properly loaded in. assert_eq!( config_handler .load_config(file_path.to_str().unwrap()) .is_ok(), true ); // Make sure that some bad key returns None assert_eq!( config_handler.get_trafiklab_value_str("bad_key").is_none(), true ); assert_eq!(config_handler.get_database_value("bad_key").is_none(), true); let get_key_result_database = config_handler.get_database_value(TEST_DATABASE_KEY); let get_key_result_trafik = config_handler.get_trafiklab_value_str(TEST_API_KEY); // Make sure that a correct key is returned as Some and the correct value. assert_eq!(get_key_result_trafik.is_some(), true); assert_eq!(get_key_result_trafik.unwrap(), TEST_API_KEY_VALUE); assert_eq!(get_key_result_database.is_some(), true); assert_eq!(get_key_result_database.unwrap(), TEST_DATABASE_KEY_VALUE); // Close the temporary directory. dir.close()?; Ok(()) } }
true
848c68aa1342464a872d917409cf3b8a1de46d8c
Rust
tirust/msp432e4
/src/sysctl/pcuart.rs
UTF-8
13,559
2.8125
3
[ "BSD-3-Clause" ]
permissive
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::PCUART { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct SYSCTL_PCUART_P0R { bits: bool, } impl SYSCTL_PCUART_P0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCUART_P0W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCUART_P0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCUART_P1R { bits: bool, } impl SYSCTL_PCUART_P1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCUART_P1W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCUART_P1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCUART_P2R { bits: bool, } impl SYSCTL_PCUART_P2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCUART_P2W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCUART_P2W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCUART_P3R { bits: bool, } impl SYSCTL_PCUART_P3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCUART_P3W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCUART_P3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCUART_P4R { bits: bool, } impl SYSCTL_PCUART_P4R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCUART_P4W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCUART_P4W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCUART_P5R { bits: bool, } impl SYSCTL_PCUART_P5R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCUART_P5W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCUART_P5W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCUART_P6R { bits: bool, } impl SYSCTL_PCUART_P6R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCUART_P6W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCUART_P6W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_PCUART_P7R { bits: bool, } impl SYSCTL_PCUART_P7R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SYSCTL_PCUART_P7W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_PCUART_P7W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - UART Module 0 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p0(&self) -> SYSCTL_PCUART_P0R { let bits = ((self.bits >> 0) & 1) != 0; SYSCTL_PCUART_P0R { bits } } #[doc = "Bit 1 - UART Module 1 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p1(&self) -> SYSCTL_PCUART_P1R { let bits = ((self.bits >> 1) & 1) != 0; SYSCTL_PCUART_P1R { bits } } #[doc = "Bit 2 - UART Module 2 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p2(&self) -> SYSCTL_PCUART_P2R { let bits = ((self.bits >> 2) & 1) != 0; SYSCTL_PCUART_P2R { bits } } #[doc = "Bit 3 - UART Module 3 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p3(&self) -> SYSCTL_PCUART_P3R { let bits = ((self.bits >> 3) & 1) != 0; SYSCTL_PCUART_P3R { bits } } #[doc = "Bit 4 - UART Module 4 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p4(&self) -> SYSCTL_PCUART_P4R { let bits = ((self.bits >> 4) & 1) != 0; SYSCTL_PCUART_P4R { bits } } #[doc = "Bit 5 - UART Module 5 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p5(&self) -> SYSCTL_PCUART_P5R { let bits = ((self.bits >> 5) & 1) != 0; SYSCTL_PCUART_P5R { bits } } #[doc = "Bit 6 - UART Module 6 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p6(&self) -> SYSCTL_PCUART_P6R { let bits = ((self.bits >> 6) & 1) != 0; SYSCTL_PCUART_P6R { bits } } #[doc = "Bit 7 - UART Module 7 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p7(&self) -> SYSCTL_PCUART_P7R { let bits = ((self.bits >> 7) & 1) != 0; SYSCTL_PCUART_P7R { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - UART Module 0 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p0(&mut self) -> _SYSCTL_PCUART_P0W { _SYSCTL_PCUART_P0W { w: self } } #[doc = "Bit 1 - UART Module 1 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p1(&mut self) -> _SYSCTL_PCUART_P1W { _SYSCTL_PCUART_P1W { w: self } } #[doc = "Bit 2 - UART Module 2 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p2(&mut self) -> _SYSCTL_PCUART_P2W { _SYSCTL_PCUART_P2W { w: self } } #[doc = "Bit 3 - UART Module 3 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p3(&mut self) -> _SYSCTL_PCUART_P3W { _SYSCTL_PCUART_P3W { w: self } } #[doc = "Bit 4 - UART Module 4 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p4(&mut self) -> _SYSCTL_PCUART_P4W { _SYSCTL_PCUART_P4W { w: self } } #[doc = "Bit 5 - UART Module 5 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p5(&mut self) -> _SYSCTL_PCUART_P5W { _SYSCTL_PCUART_P5W { w: self } } #[doc = "Bit 6 - UART Module 6 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p6(&mut self) -> _SYSCTL_PCUART_P6W { _SYSCTL_PCUART_P6W { w: self } } #[doc = "Bit 7 - UART Module 7 Power Control"] #[inline(always)] pub fn sysctl_pcuart_p7(&mut self) -> _SYSCTL_PCUART_P7W { _SYSCTL_PCUART_P7W { w: self } } }
true
222277d89f50298110defa98ac6e1dd8729f6b95
Rust
michaelstarmer/rust-examples
/src/impl_/src/main.rs
UTF-8
591
3.984375
4
[]
no_license
/* * Tutorial 06 */ struct Rectangle { width: u32, height: u32, } impl Rectangle { fn print_description(&self) { println!("Rectangle: {} x {}", self.width, self.height); } fn is_square(&self) -> bool { self.width == self.height } } fn main() { let rect1 = Rectangle { width: 10, height: 5 }; rect1.print_description(); println!("Rectangle 1 is a square: {}", rect1.is_square()); let rect2 = Rectangle { width: 5, height: 5 }; rect2.print_description(); println!("Rectangle 2 is a square: {}", rect2.is_square()); }
true
ab2a724844a4e981a04bac9db4122696c0567a9f
Rust
PSeitz/stainless
/tests/expression.rs
UTF-8
875
2.890625
3
[ "MIT" ]
permissive
// Copyright 2016 The Stainless Developers. See the LICENSE file at the top-level directory of // this distrubution. // // Licensed under the MIT license. This file may not be copied, modified, or distributed except // according to those terms. #![feature(plugin)] #![plugin(stainless)] describe! expression_at_end_of_block { before_each { let x = 5; let y = 6; let mut z = 0; for _ in 0..5 { z += 1; } } it "should execute expressions at ends of test blocks as statements" { assert_eq!(x + y, 11); assert_eq!(z, 5); for _ in 0..5 { z += 1; } } after_each { assert_eq!(x, 5); assert_eq!(y, 6); assert_eq!(z, 10); for _ in 0..5 { // Purposefully empty-- tests that after_each can end with loop } } }
true
aef9d66fc29a007a902ba936e8b1d63d88391b98
Rust
BattleMage0231/borz-client
/src/app.rs
UTF-8
1,946
2.6875
3
[ "Apache-2.0" ]
permissive
use crate::api::fetch::APIFetcher; use crate::widgets::page::{GroupPage, ThreadPage, UserPage}; use crate::TOP_LEVEL_ID; use clap::ArgMatches; use crossterm::event::KeyEvent; use json::JsonValue; use url::Url; #[derive(Debug)] pub enum AppPage { User(UserPage), Group(GroupPage), Thread(ThreadPage), } #[derive(Debug)] pub struct App<'a> { route: Vec<AppPage>, args: ArgMatches<'a>, config: JsonValue, } impl<'a> App<'a> { pub fn new(args: ArgMatches<'a>, config: JsonValue) -> App { App { route: Vec::new(), args, config, } } pub fn start(&mut self) { self.route.push(AppPage::Group(GroupPage::new( APIFetcher::new( Url::parse(&self.config["server"].to_string()[..]).unwrap(), TOP_LEVEL_ID.clone(), ), String::from("/Universe"), self.config["username"].to_string(), ))); } pub fn tick(&mut self) { match self.get_page().unwrap() { _ => {} } } pub fn update(&mut self, chr: KeyEvent) -> bool { if self.route.is_empty() { return false; } let closure = match self.get_page().unwrap() { AppPage::Group(gp) => gp.update(chr), AppPage::User(up) => up.update(chr), AppPage::Thread(tp) => tp.update(chr), }; closure(self); return !self.route.is_empty(); } pub fn push_page(&mut self, page: AppPage) { self.route.push(page); } pub fn pop_page(&mut self) -> Option<AppPage> { if self.route.is_empty() { None } else { Some(self.route.pop().unwrap()) } } pub fn get_page(&mut self) -> Option<&mut AppPage> { if self.route.is_empty() { None } else { Some(self.route.last_mut().unwrap()) } } }
true
2735b2b67a7eff5bc8f42f59a49fe0a590c0a481
Rust
cosmo0920/ruroonga_client
/src/uri_base.rs
UTF-8
2,052
3.703125
4
[ "MIT" ]
permissive
use std::borrow::Cow; #[derive(Clone, Debug)] pub struct URIBase<'a> { base_uri: Cow<'a, str>, port: u16, } impl<'a> Default for URIBase<'a> { fn default() -> URIBase<'a> { URIBase { base_uri: "localhost".into(), port: 10041, } } } impl<'a> URIBase<'a> { /// /// Create URIBase struct. /// /// Default values are: /// /// base_uri: "localhost" /// /// port: 10041 /// pub fn new() -> URIBase<'a> { URIBase::default() } /// Set base to replace default value with specified value. pub fn base_uri<T>(mut self, base_uri: T) -> URIBase<'a> where T: Into<Cow<'a, str>> { self.base_uri = base_uri.into(); self } /// Set port number to replace default value with specified value. pub fn port(mut self, port: u16) -> URIBase<'a> { self.port = port; self } /// Build and get base uri. pub fn build(self) -> String { format!("http://{}:{}", self.base_uri.into_owned(), self.port) } } #[cfg(test)] mod tests { use super::*; #[test] fn construct_uri_default() { let uri_base = URIBase::new().build(); assert_eq!("http://localhost:10041", uri_base) } #[test] fn build_only_uri_base() { let uri_base = URIBase::new().base_uri("127.0.0.1").build(); assert_eq!("http://127.0.0.1:10041", uri_base); } #[test] fn build_only_uri_base_with_owned_str() { let uri_base = URIBase::new().base_uri("127.0.0.1".to_owned()).build(); assert_eq!("http://127.0.0.1:10041", uri_base); } #[test] fn build_only_port() { let uri_base = URIBase::new().port(10042).build(); assert_eq!("http://localhost:10042", uri_base); } #[test] fn uri_with_builder() { let uri_base = URIBase::new() .base_uri("127.0.1.1".to_string()) .port(10043) .build(); assert_eq!("http://127.0.1.1:10043", uri_base) } }
true
1a463cd0c14a1c73c411e8847e7ec8e4b202d4e7
Rust
pkalivas/radiate
/radiate_matrix_tree/src/matrix_tree/evenv.rs
UTF-8
6,146
3.09375
3
[ "MIT" ]
permissive
extern crate radiate; use radiate::engine::environment::Envionment; /// unique mutations: /// start_height height of the starting tree to generate /// max height the maximum height of a tree /// network mutation rate the probability of mutating the neural network inside a node /// node add rate the probability of adding a node to a crossovered tree /// gut rate the probability of re-initalizing a neural network for a tree and changing the node's output /// shuffle rate the probability of randomly mixing up the tree and rebalancing it - results in a balanced tree /// layer mutate the probability of randomly mutating the weights and biases of the current layer of the neural network /// weight rate the probability of either editing the current weight, or reinitalizing it with a new random number /// weight transform if the generated random number is less than weight_rate, edit that number in the layer of the neural network by multiplying it by +/- weight_transform /// /// /// Unique mutation options for a tree object including options for mutation individual /// nodes and their owned neural networks as well #[derive(Debug, Clone, PartialEq)] pub struct TreeEnvionment { pub input_size: Option<i32>, pub outputs: Option<Vec<i32>>, pub start_height: Option<i32>, pub max_height: Option<i32>, pub network_mutation_rate: Option<f32>, pub node_add_rate: Option<f32>, pub gut_rate: Option<f32>, pub shuffle_rate: Option<f32>, pub layer_mutate_rate: Option<f32>, pub weight_mutate_rate: Option<f32>, pub weight_transform_rate: Option<f32>, } /// implement the Settings impl TreeEnvionment { /// create a new Settings struct that is completely empty /// /// Note: this is initiated with everything being none, however the /// algorithm will panic! at several places if these options are not set /// The only reason this is set like this is to avoid confusion by creating /// a constructor with like 10 different arguments which have to be placed /// at the correct place within it. pub fn new() -> Self { TreeEnvionment { input_size: None, outputs: None, start_height: None, max_height: None, network_mutation_rate: None, node_add_rate: None, gut_rate: None, shuffle_rate: None, layer_mutate_rate: None, weight_mutate_rate: None, weight_transform_rate: None } } #[allow(dead_code)] pub fn set_input_size(mut self, size: i32) -> Self { self.input_size = Some(size); self } #[allow(dead_code)] pub fn get_input_size(&self) -> i32 { self.input_size.unwrap_or_else(|| panic!("Input size not set")) } #[allow(dead_code)] pub fn set_outputs(mut self, outs: Vec<i32>) -> Self { self.outputs = Some(outs); self } #[allow(dead_code)] pub fn get_outputs(&self) -> &[i32] { self.outputs.as_ref().unwrap_or_else(|| panic!("Outputs not set")) } #[allow(dead_code)] pub fn set_start_height(mut self, height: i32) -> Self { self.start_height = Some(height); self } #[allow(dead_code)] pub fn get_start_height(&self) -> i32 { self.start_height.unwrap_or_else(|| panic!("Start height not set.")) } #[allow(dead_code)] pub fn set_max_height(mut self, m: i32) -> Self { self.max_height = Some(m); self } #[allow(dead_code)] pub fn get_max_height(&self) -> i32 { self.max_height.unwrap_or_else(|| panic!("Max height not set.")) } #[allow(dead_code)] pub fn set_network_mutation_rate(mut self, rate: f32) -> Self { self.network_mutation_rate = Some(rate); self } #[allow(dead_code)] pub fn get_network_mutation_rate(&self) -> f32 { self.network_mutation_rate.unwrap_or_else(|| panic!("Network mutation rate not set.")) } #[allow(dead_code)] pub fn set_node_add_rate(mut self, rate: f32) -> Self { self.node_add_rate = Some(rate); self } #[allow(dead_code)] pub fn get_node_add_rate(&self) -> f32 { self.node_add_rate.unwrap_or_else(|| panic!("Node add rate not set.")) } #[allow(dead_code)] pub fn set_gut_rate(mut self, rate: f32) -> Self { self.gut_rate = Some(rate); self } #[allow(dead_code)] pub fn get_gut_rate(&self) -> f32 { self.gut_rate.unwrap_or_else(|| panic!("Gut rate not set")) } #[allow(dead_code)] pub fn set_shuffle_rate(mut self, rate: f32) -> Self { self.shuffle_rate = Some(rate); self } #[allow(dead_code)] pub fn get_shuffle_rate(&self) -> f32 { self.shuffle_rate.unwrap_or_else(|| panic!("Shuffle rate not set.")) } #[allow(dead_code)] pub fn set_layer_mutate_rate(mut self, rate: f32) -> Self { self.layer_mutate_rate = Some(rate); self } #[allow(dead_code)] pub fn get_layer_mutate_rate(&self) -> f32 { self.layer_mutate_rate.unwrap_or_else(|| panic!("Layer mutate rate not set")) } #[allow(dead_code)] pub fn set_weight_mutate_rate(mut self, rate: f32) -> Self { self.weight_mutate_rate = Some(rate); self } #[allow(dead_code)] pub fn get_weight_mutate_rate(&self) -> f32 { self.weight_mutate_rate.unwrap_or_else(|| panic!("Weight mutate rate not set.")) } #[allow(dead_code)] pub fn set_weight_transform_rate(mut self, rate: f32) -> Self { self.weight_transform_rate = Some(rate); self } #[allow(dead_code)] pub fn get_weight_transform_rate(&self) -> f32 { self.weight_transform_rate.unwrap_or_else(|| panic!("Weight transform rate not set")) } } impl Default for TreeEnvionment { fn default() -> Self { Self::new() } } impl Envionment for TreeEnvionment {}
true
06ce87863fb2d4837a3acc33f521b36a26ea5ebb
Rust
qiuchengxuan/max7456
/src/incremental_writer.rs
UTF-8
3,490
3.265625
3
[]
no_license
use peripheral_register::Register; use crate::registers::{DisplayMemoryMode, OperationMode, Registers}; use crate::{display_memory_address, Attributes, Display}; /// Incremental writer starting from given row and column /// based on MAX7456 incremental write capability pub struct IncrementalWriter<'a> { bytes: &'a [u8], address: u16, attributes: Attributes, index: usize, } impl<'a> IncrementalWriter<'a> { pub fn new(bytes: &'a [u8], row: u8, column: u8, attributes: Attributes) -> Self { Self { bytes, address: display_memory_address(row, column), attributes, index: 0 } } pub fn remain(&self) -> usize { self.bytes.len() - self.index } pub fn write<'b>(&mut self, buffer: &'b mut [u8]) -> Option<Display<'b>> { assert!(buffer.len() >= 10); buffer[0] = Registers::DisplayMemoryMode as u8; let mut dmm = Register::<u8, DisplayMemoryMode>::new(0); dmm.set(DisplayMemoryMode::OperationMode, OperationMode::Mode16Bit as u8); dmm.set( DisplayMemoryMode::LocalBackgroundControl, self.attributes.local_background_control as u8, ); dmm.set(DisplayMemoryMode::Blink, self.attributes.blink as u8); dmm.set(DisplayMemoryMode::Invert, self.attributes.revert as u8); dmm.set(DisplayMemoryMode::AutoIncrement, 1); buffer[1] = dmm.value; buffer[2] = Registers::DisplayMemoryAddressHigh as u8; buffer[3] = (self.address >> 8) as u8; buffer[4] = Registers::DisplayMemoryAddressLow as u8; buffer[5] = self.address as u8; let mut offset = 6; let mut written = 0; let mut ff_checker = false; for &byte in self.bytes[self.index..].iter() { buffer[offset] = Registers::DisplayMemoryDataIn as u8; buffer[offset + 1] = byte; ff_checker = byte == 0xFF; written += 1; offset += 2; if offset + 2 >= buffer.len() { break; } } if ff_checker { return None; } buffer[offset] = Registers::DisplayMemoryDataIn as u8; buffer[offset + 1] = 0xFF; self.index += written; self.address += written as u16; Some(Display(&buffer[..offset + 2])) } } #[cfg(test)] mod test { use super::IncrementalWriter; #[test] fn test_functional() { let mut output = [0u8; 32]; let mut writer = IncrementalWriter::new(b"test", 0, 0, Default::default()); let expected = hex!("04 01 05 00 06 00 07 74 07 65 07 73 07 74 07 FF"); assert_eq!(writer.write(&mut output).unwrap().0, expected); } #[test] fn test_breaks() { let mut output = [0u8; 6 + 26 + 2]; let upper_letters = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let mut writer = IncrementalWriter::new(upper_letters, 0, 0, Default::default()); let expected = hex!( "04 01 05 00 06 00 07 41 07 42 07 43 07 44 07 45 07 46 07 47 07 48 07 49 07 4A 07 4B 07 4C 07 4D 07 FF" ); assert_eq!(writer.write(&mut output).unwrap().0, expected); assert_eq!(writer.remain() > 0, true); let expected = hex!( "04 01 05 00 06 0D 07 4E 07 4F 07 50 07 51 07 52 07 53 07 54 07 55 07 56 07 57 07 58 07 59 07 5A 07 FF" ); assert_eq!(writer.write(&mut output).unwrap().0, expected); assert_eq!(writer.remain(), 0); } }
true
421c7b680f283183e87f49379f28f7a208607c46
Rust
jblindsay/whitebox-tools
/whitebox-tools-app/src/tools/lidar_analysis/lidar_tile.rs
UTF-8
16,565
2.65625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: 26/06/2017 Last Modified: 05/02/2019 License: MIT */ use whitebox_lidar::*; use crate::tools::*; use std; use std::env; use std::fs::DirBuilder; use std::io::{Error, ErrorKind}; use std::path; use std::path::Path; /// This tool can be used to break a LiDAR LAS file into multiple, non-overlapping tiles, each saved as a /// single LAS file. The user must specify the parameter of the tile grid, including its origin (`--origin_x` and /// `--origin_y`) and the tile width and height (`--width` and `--height`). Tiles containing fewer points than /// specified in the `--min_points` parameter will not be output. This can be useful when tiling terrestrial LiDAR /// datasets because the low point density at the edges of the point cloud (i.e. most distant from the scan /// station) can result in poorly populated tiles containing relatively few points. /// /// # See Also /// `LidarJoin`, `LidarTileFootprint` pub struct LidarTile { name: String, description: String, toolbox: String, parameters: Vec<ToolParameter>, example_usage: String, } impl LidarTile { pub fn new() -> LidarTile { // public constructor let name = "LidarTile".to_string(); let toolbox = "LiDAR Tools".to_string(); let description = "Tiles a LiDAR LAS file into multiple LAS files.".to_string(); let mut parameters = vec![]; parameters.push(ToolParameter { name: "Input File".to_owned(), flags: vec!["-i".to_owned(), "--input".to_owned()], description: "Input LiDAR file.".to_owned(), parameter_type: ParameterType::ExistingFile(ParameterFileType::Lidar), default_value: None, optional: false, }); parameters.push(ToolParameter { name: "Tile Width".to_owned(), flags: vec!["--width".to_owned()], description: "Width of tiles in the X dimension; default 1000.0.".to_owned(), parameter_type: ParameterType::Float, default_value: Some("1000.0".to_owned()), optional: true, }); parameters.push(ToolParameter { name: "Tile Height".to_owned(), flags: vec!["--height".to_owned()], description: "Height of tiles in the Y dimension.".to_owned(), parameter_type: ParameterType::Float, default_value: Some("1000.0".to_owned()), optional: true, }); parameters.push(ToolParameter { name: "Origin Point X-Coordinate".to_owned(), flags: vec!["--origin_x".to_owned()], description: "Origin point X coordinate for tile grid.".to_owned(), parameter_type: ParameterType::Float, default_value: Some("0.0".to_owned()), optional: true, }); parameters.push(ToolParameter { name: "Origin Point Y-Coordinate".to_owned(), flags: vec!["--origin_y".to_owned()], description: "Origin point Y coordinate for tile grid.".to_owned(), parameter_type: ParameterType::Float, default_value: Some("0.0".to_owned()), optional: true, }); parameters.push(ToolParameter { name: "Minimum Number of Tile Points".to_owned(), flags: vec!["--min_points".to_owned()], description: "Minimum number of points contained in a tile for it to be saved." .to_owned(), parameter_type: ParameterType::Integer, default_value: Some("2".to_owned()), optional: true, }); let sep: String = path::MAIN_SEPARATOR.to_string(); let e = format!("{}", env::current_exe().unwrap().display()); let mut parent = env::current_exe().unwrap(); parent.pop(); let p = format!("{}", parent.display()); let mut short_exe = e .replace(&p, "") .replace(".exe", "") .replace(".", "") .replace(&sep, ""); if e.contains(".exe") { short_exe += ".exe"; } let usage = format!(">>.*{0} -r={1} -v -i=*path*to*data*input.las --width=1000.0 --height=2500.0 -=min_points=100", short_exe, name).replace("*", &sep); LidarTile { name: name, description: description, toolbox: toolbox, parameters: parameters, example_usage: usage, } } } impl WhiteboxTool for LidarTile { fn get_source_file(&self) -> String { String::from(file!()) } fn get_tool_name(&self) -> String { self.name.clone() } fn get_tool_description(&self) -> String { self.description.clone() } fn get_tool_parameters(&self) -> String { let mut s = String::from("{\"parameters\": ["); for i in 0..self.parameters.len() { if i < self.parameters.len() - 1 { s.push_str(&(self.parameters[i].to_string())); s.push_str(","); } else { s.push_str(&(self.parameters[i].to_string())); } } s.push_str("]}"); s } fn get_example_usage(&self) -> String { self.example_usage.clone() } fn get_toolbox(&self) -> String { self.toolbox.clone() } fn run<'a>( &self, args: Vec<String>, working_directory: &'a str, verbose: bool, ) -> Result<(), Error> { let mut input_file: String = String::new(); let mut width_x = 1000.0; let mut width_y = 1000.0; let mut origin_x = 0.0; let mut origin_y = 0.0; let mut min_points = 2; // read the arguments if args.len() == 0 { return Err(Error::new( ErrorKind::InvalidInput, "Tool run with no parameters.", )); } for i in 0..args.len() { let mut arg = args[i].replace("\"", ""); arg = arg.replace("\'", ""); let cmd = arg.split("="); // in case an equals sign was used let vec = cmd.collect::<Vec<&str>>(); let mut keyval = false; if vec.len() > 1 { keyval = true; } let flag_val = vec[0].to_lowercase().replace("--", "-"); if flag_val == "-i" || flag_val == "-input" { if keyval { input_file = vec[1].to_string(); } else { input_file = args[i + 1].to_string(); } } else if flag_val == "-width_x" || flag_val == "-width" { if keyval { width_x = vec[1] .to_string() .parse::<f64>() .expect(&format!("Error parsing {}", flag_val)); } else { width_x = args[i + 1] .to_string() .parse::<f64>() .expect(&format!("Error parsing {}", flag_val)); } } else if flag_val == "-width_y" || flag_val == "-height" { if keyval { width_y = vec[1] .to_string() .parse::<f64>() .expect(&format!("Error parsing {}", flag_val)); } else { width_y = args[i + 1] .to_string() .parse::<f64>() .expect(&format!("Error parsing {}", flag_val)); } } else if flag_val == "-origin_x" { if keyval { origin_x = vec[1] .to_string() .parse::<f64>() .expect(&format!("Error parsing {}", flag_val)); } else { origin_x = args[i + 1] .to_string() .parse::<f64>() .expect(&format!("Error parsing {}", flag_val)); } } else if flag_val == "-origin_y" { if keyval { origin_y = vec[1] .to_string() .parse::<f64>() .expect(&format!("Error parsing {}", flag_val)); } else { origin_y = args[i + 1] .to_string() .parse::<f64>() .expect(&format!("Error parsing {}", flag_val)); } } else if flag_val == "-min_points" { if keyval { min_points = vec[1] .to_string() .parse::<f32>() .expect(&format!("Error parsing {}", flag_val)) as usize; } else { min_points = args[i + 1] .to_string() .parse::<f32>() .expect(&format!("Error parsing {}", flag_val)) as usize; } } } if verbose { let tool_name = self.get_tool_name(); let welcome_len = format!("* Welcome to {} *", tool_name).len().max(28); // 28 = length of the 'Powered by' by statement. println!("{}", "*".repeat(welcome_len)); println!("* Welcome to {} {}*", tool_name, " ".repeat(welcome_len - 15 - tool_name.len())); println!("* Powered by WhiteboxTools {}*", " ".repeat(welcome_len - 28)); println!("* www.whiteboxgeo.com {}*", " ".repeat(welcome_len - 23)); println!("{}", "*".repeat(welcome_len)); } let sep = std::path::MAIN_SEPARATOR; if min_points < 2 { min_points = 2; } if width_x <= 0f64 || width_y <= 0f64 { panic!("ERROR: The grid cell width must be greater than zero."); } if !input_file.contains(sep) && !input_file.contains("/") { input_file = format!("{}{}", working_directory, input_file); } if verbose { println!("Performing analysis..."); } let input = match LasFile::new(&input_file, "r") { Ok(lf) => lf, Err(err) => panic!("Error reading file {}: {}", input_file, err), }; let min_x = input.header.min_x; let max_x = input.header.max_x; let min_y = input.header.min_y; let max_y = input.header.max_y; let n_points = input.header.number_of_points as usize; let num_points: f64 = (input.header.number_of_points - 1) as f64; // used for progress calculation only let start_x_grid = ((min_x - origin_x) / width_x).floor(); let end_x_grid = ((max_x - origin_x) / width_x).ceil(); let start_y_grid = ((min_y - origin_y) / width_y).floor(); let end_y_grid = ((max_y - origin_y) / width_y).ceil(); let cols = (end_x_grid - start_x_grid).abs() as usize; let rows = (end_y_grid - start_y_grid).abs() as usize; let num_tiles = rows * cols; if num_tiles > 32767usize { return Err(Error::new( ErrorKind::InvalidInput, "There are too many output tiles. Try choosing a larger grid width.", )); } let mut tile_data = vec![0usize; n_points]; let (mut col, mut row): (usize, usize); let mut progress: i32; let mut old_progress: i32 = -1; for i in 0..n_points { // let p: PointData = input[i]; let p = input.get_transformed_coords(i); col = (((p.x - origin_x) / width_x) - start_x_grid).floor() as usize; // relative to the grid edge row = (((p.y - origin_y) / width_y) - start_y_grid).floor() as usize; // relative to the grid edge tile_data[i] = row * cols + col; if verbose { progress = (100.0_f64 * i as f64 / num_points) as i32; if progress != old_progress { println!("Progress (Loop 1 of 3): {}%", progress); old_progress = progress; } } } // figure out the last point for each tile, so that the shapefile can be closed afterwards let n_points_plus_one = n_points + 1; let mut first_point_num = vec![n_points_plus_one; num_tiles]; let mut last_point_num = vec![0usize; num_tiles]; let mut num_points_in_tile = vec![0usize; num_tiles]; for i in 0..n_points { last_point_num[tile_data[i]] = i; num_points_in_tile[tile_data[i]] += 1; if first_point_num[tile_data[i]] == n_points_plus_one { first_point_num[tile_data[i]] = i; } if verbose { progress = (100.0_f64 * i as f64 / num_points) as i32; if progress != old_progress { println!("Progress (Loop 2 of 3): {}%", progress); old_progress = progress; } } } let mut output_tile = vec![false; num_tiles]; for tile_num in 0..num_tiles { if num_points_in_tile[tile_num] > min_points { output_tile[tile_num] = true; } } let mut min_row = 999999; let mut min_col = 999999; for tile_num in 0..num_tiles { if output_tile[tile_num] { row = (tile_num as f64 / cols as f64).floor() as usize; col = tile_num % cols; if row < min_row { min_row = row; } if col < min_col { min_col = col; } } } let sep: String = path::MAIN_SEPARATOR.to_string(); let name: String = match Path::new(&input_file).file_stem().unwrap().to_str() { Some(n) => n.to_string(), None => "".to_string(), }; let dir: String = match Path::new(&input_file).parent().unwrap().to_str() { Some(n) => n.to_string(), None => "".to_string(), }; let output_dir: String = format!("{}{}{}{}", dir.to_string(), sep, name, sep); DirBuilder::new() .recursive(true) .create(output_dir.clone()) .unwrap(); let mut num_tiles_created = 0; for tile_num in 0..num_tiles { if output_tile[tile_num] { row = (tile_num as f64 / cols as f64).floor() as usize; col = tile_num % cols; let output_file = format!( "{}{}_row{}_col{}.laz", output_dir, name, row - min_row + 1, col - min_col + 1 ); let mut output = LasFile::initialize_using_file(&output_file, &input); output.header.system_id = "EXTRACTION".to_string(); for i in first_point_num[tile_num]..last_point_num[tile_num] { if tile_data[i] == tile_num { output.add_point_record(input.get_record(i)); } } let _ = match output.write() { Ok(_) => (), // do nothing Err(e) => { return Err(Error::new( ErrorKind::Other, format!("Error while writing: {:?}", e), )) } }; num_tiles_created += 1; } if verbose { progress = (100.0_f64 * tile_num as f64 / (num_tiles - 1) as f64) as i32; if progress != old_progress { println!("Progress (Loop 3 of 3): {}%", progress); old_progress = progress; } } } if num_tiles_created > 0 { if verbose { println!("Successfully created {} tiles.", num_tiles_created); } } else if num_tiles_created == 0 { return Err(Error::new( ErrorKind::Other, "Error: No tiles were created.", )); } Ok(()) } }
true
9f6aeaede2913829ea563ff15b5307ae63d85fdd
Rust
stadust/dash-rs
/src/model/level/object/speed.rs
UTF-8
764
3.40625
3
[ "MIT" ]
permissive
// TODO: Speed portals and stuff use serde::{Deserialize, Serialize}; /// Enum modelling the different speeds a player can have during gameplay #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Speed { Slow, #[default] Normal, Medium, Fast, VeryFast, Unknown(u8), } /// Converts the speed to the game-internal "pixel / second" value represented by some [`Speed`] /// variant impl From<Speed> for f32 { fn from(speed: Speed) -> f32 { match speed { Speed::Unknown(_) => 0.0, Speed::Slow => 251.16, Speed::Normal => 311.58, Speed::Medium => 387.42, Speed::Fast => 468.0, Speed::VeryFast => 576.0, } } }
true
b1037b727e3f7aff27a72763f62006fb684b1b43
Rust
RRRadicalEdward/memmap
/src/memory.rs
UTF-8
6,946
2.53125
3
[]
no_license
use std::{ fmt::{self, Formatter}, mem::size_of_val, ptr, rc::Rc, }; use winapi::{ shared::{ minwindef::{BYTE, FALSE, MAX_PATH, TRUE}, ntdef::LPSTR, }, um::{ handleapi::{CloseHandle, INVALID_HANDLE_VALUE}, memoryapi::VirtualQueryEx, psapi::GetMappedFileNameA, sysinfoapi::{GetSystemInfo, SYSTEM_INFO}, tlhelp32::{ CreateToolhelp32Snapshot, Module32First, Module32Next, MODULEENTRY32, TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32, }, winnt::{ HANDLE, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_FREE, MEM_RESERVE, PAGE_GUARD, PVOID, }, }, }; use crate::{ enums::{MemState, MemoryPageProtection, PagesType}, error::{MemMapResult, WinAPIError}, process_info::ProcessInfo, utils::array_i8_to_string, }; #[derive(Debug)] pub struct ProcessMemory { base_address: PVOID, size: usize, blocks_count: usize, guard_blocks_count: usize, memory_blocks: Vec<MemoryBlock>, } impl ProcessMemory { pub fn new(process: ProcessInfo) -> MemMapResult<Self> { let mut mbi = MEMORY_BASIC_INFORMATION::default(); let mut system_info = SYSTEM_INFO::default(); unsafe { GetSystemInfo(&mut system_info); } let mut address = system_info.lpMinimumApplicationAddress; let mut memory_blocks = Vec::new(); let process_info = Rc::new(process.clone()); while address <= system_info.lpMaximumApplicationAddress { let vmqeuery_result = unsafe { VirtualQueryEx(process.handle, address, &mut mbi, size_of_val(&mbi)) }; if vmqeuery_result == 0 { return Err(WinAPIError::new()); } memory_blocks.push(MemoryBlock::new(&mbi, process_info.clone())); address = unsafe { address.add(mbi.RegionSize) }; } let rng_base_address = memory_blocks .first() .map(|block| block.base_address) .unwrap_or(ptr::null_mut()); let rng_size = memory_blocks.iter().map(|block| block.size).sum(); let rng_guard_blocks_count = memory_blocks .iter() .filter(|block| block.protection == MemoryPageProtection::Guard || block.is_stack) .count(); Ok(Self { base_address: rng_base_address, size: rng_size, blocks_count: memory_blocks.len(), guard_blocks_count: rng_guard_blocks_count, memory_blocks, }) } } impl fmt::Display for ProcessMemory { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( f, "base_address: {:p}\nsize: {} bytes\nblocks_count: {}\nguard_blocks_count: {}\nmemory blocks: {:#?}", self.base_address, self.size, self.blocks_count, self.guard_blocks_count, self.memory_blocks ) } } struct MemoryBlock { base_address: PVOID, protection: MemoryPageProtection, size: usize, storage: MemState, page_type: PagesType, is_stack: bool, process_info: Rc<ProcessInfo>, } impl MemoryBlock { fn new(mbi: &MEMORY_BASIC_INFORMATION, process_info: Rc<ProcessInfo>) -> Self { let (block_protection, storage, page_type, is_stack) = match mbi.State { MEM_FREE => ( MemoryPageProtection::CallerDoesNotHaveAccess, MemState::MemFree, PagesType::Undefined, false, ), MEM_RESERVE => ( MemoryPageProtection::from(mbi.AllocationProtect), MemState::MemReserve, PagesType::from(mbi.Type), false, ), MEM_COMMIT => ( MemoryPageProtection::from(mbi.AllocationProtect), MemState::MemCommit, PagesType::from(mbi.Type), mbi.Protect & PAGE_GUARD == PAGE_GUARD, ), _ => unreachable!("No others mem states exist"), }; Self { base_address: mbi.BaseAddress, protection: block_protection, size: mbi.RegionSize, storage, is_stack, page_type, process_info, } } pub fn find_module(&self) -> MemMapResult<Option<String>> { let mut module_entry = MODULEENTRY32::default(); module_entry.dwSize = size_of_val(&module_entry) as u32; let processes_snapshot: HANDLE = unsafe { CreateToolhelp32Snapshot( TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, self.process_info.process_id, ) }; if processes_snapshot == INVALID_HANDLE_VALUE { return Err(WinAPIError::new()); } let mut module_name = None; unsafe { Module32First(processes_snapshot, &mut module_entry); } if unsafe { Module32First(processes_snapshot, &mut module_entry) } == TRUE { if module_entry.modBaseAddr == self.base_address as *mut BYTE { module_name = Some(array_i8_to_string(&module_entry.szExePath)); } } else { while unsafe { Module32Next(processes_snapshot, &mut module_entry) } != FALSE { if module_entry.modBaseAddr == self.base_address as *mut BYTE { module_name = Some(array_i8_to_string(&module_entry.szExePath)); } } } unsafe { CloseHandle(processes_snapshot) }; Ok(module_name) } pub fn mapped_file(&self) -> MemMapResult<Option<String>> { let mut filename: [i8; 260] = [0; MAX_PATH]; let read: u32 = unsafe { GetMappedFileNameA( self.process_info.handle, self.base_address, &mut filename as LPSTR, MAX_PATH as u32, ) }; if read == 0 { return Err(WinAPIError::new()); } Ok(Some(array_i8_to_string(&filename[0..read as usize]))) } } impl fmt::Debug for MemoryBlock { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut address_description = if self.is_stack { String::from("THREAD STACK") } else if let Ok(Some(module_path)) = self.find_module() { format!("MODULE: {}", module_path) } else { String::new() }; if let Ok(Some(mapped_file)) = self.mapped_file() { address_description.push_str(&format!(" MAPPED FILE: {}", mapped_file)) } write!(f, "[\n\tbase_address: {:p} {}\n\tsize: {} bytes\n\tprotection: {:?}\n\tstorage: {:?}\n\tpage type: {:?}\n]", self.base_address, address_description, self.size, self.protection, self.storage, self.page_type ) } }
true
ef5af7c47079556fc187cf823f085562ab1e09b3
Rust
johanlindblad/advent-of-code-2018
/src/day15.rs
UTF-8
7,722
3.046875
3
[]
no_license
use std::collections::BTreeSet; use std::collections::VecDeque; #[derive(Debug, Clone)] pub struct Unit { hit_points: isize, friendly: bool, } #[derive(Debug, Clone)] pub enum Square { Wall, Space, Occupied(Unit) } fn parse_line(input: &str) -> Vec<Square> { input.chars().map(|c| match c { '#' => Square::Wall, '.' => Square::Space, 'E' | 'G' => Square::Occupied(Unit { hit_points: 200, friendly: c == 'E' }), other => panic!("Unexpected {}", other) }).collect() } #[aoc_generator(day15)] pub fn input_generator(input: &str) -> Vec<Vec<Square>> { input.lines().map(|l| parse_line(l)).collect() } #[aoc(day15, part1)] pub fn solve_part1(input: &Vec<Vec<Square>>) -> usize { let (_, score) = result(input, 3); score } #[aoc(day15, part2)] pub fn solve_part2(input: &Vec<Vec<Square>>) -> usize { for elf_power in 4.. { let (no_losses, score) = result(input, elf_power); if no_losses { return score } } panic!("Did not finish") } // (elfs_win, score) pub fn result(input: &Vec<Vec<Square>>, elf_power: isize) -> (bool, usize) { let mut unit_positions: BTreeSet<(usize, usize)> = BTreeSet::new(); let mut board: Vec<Vec<Square>> = input.clone().to_vec(); let (height, width) = (board.len(), board[0].len()); let mut elfs_left = 0; let mut goblins_left = 0; for row in 0..height { for column in 0..width { match &mut board[row][column] { Square::Occupied(ref mut by) => { unit_positions.insert((row, column)); if by.friendly { elfs_left += 1 } else { goblins_left += 1}; }, _ => () }; } } let original_elfs = elfs_left; let adjacent: Vec<(isize, isize)> = vec![(-1, 0), (0, -1), (0, 1), (1, 0)]; let mut full_round = true; for round in 1.. { let mut new_positions: BTreeSet<(usize, usize)> = BTreeSet::new(); for (mut row, mut column) in unit_positions { let friendly = match &board[row][column] { Square::Wall | Square::Space => continue, Square::Occupied(by) => by.friendly }; if goblins_left == 0 || elfs_left == 0 { full_round = false; break; } let mut found_enemy: Option<(usize, usize)> = None; let mut closest = usize::max_value(); let mut move_to: Option<(usize, usize)> = None; for (dy, dx) in &adjacent { let mut frontier: VecDeque<(usize, (usize, usize))> = VecDeque::new(); let first_y = (row as isize + dy) as usize; let first_x = (column as isize + dx) as usize; let mut visited = vec![vec![false; width]; height]; if let Square::Space = &board[first_y][first_x] { frontier.push_back((1, (first_y, first_x))); while let Some((distance, (y, x))) = frontier.pop_front() { if distance > closest { break }; for (dy, dx) in &adjacent { let new_y = (y as isize + dy) as usize; let new_x = (x as isize + dx) as usize; if let Square::Space = board[new_y][new_x] { if visited[new_y][new_x] { continue }; visited[new_y][new_x] = true; frontier.push_back((distance + 1, (new_y, new_x))); } else if let Square::Occupied(ref by) = board[new_y][new_x] { if by.friendly == friendly { continue } if found_enemy.is_none() || (y, x) < found_enemy.unwrap() || distance < closest { //println!("Can make it to {:?} in {} with {:?}", (y, x), distance, (first_y, first_x)); found_enemy = Some((y, x)); closest = distance; move_to = Some((first_y, first_x)); } } } } } else if let Square::Occupied(ref by) = board[first_y][first_x] { if by.friendly == friendly { continue } closest = 0; move_to = None; break; } } if let Some((new_y, new_x)) = move_to { let unit = board[row][column].clone(); board[new_y][new_x] = unit.clone(); board[row][column] = Square::Space; new_positions.insert((new_y, new_x)); row = new_y; column = new_x; } else { new_positions.insert((row, column)); } let mut attack_at: Option<(usize, usize)> = None; if closest <= 1 { let mut lowest_points = 201; for (dy, dx) in &adjacent { let ny = (row as isize + *dy) as usize; let nx = (column as isize + *dx) as usize; if let Square::Occupied(by) = &board[ny][nx] { if by.friendly != friendly && by.hit_points < lowest_points { attack_at = Some((ny, nx)); lowest_points = by.hit_points; } } } } if let Some((y, x)) = attack_at { let mut killed = false; if let &mut Square::Occupied(ref mut target) = &mut board[y][x] { if friendly { target.hit_points -= elf_power } else { target.hit_points -= 3; } if target.hit_points <= 0 { killed = true; } } else { panic!("WTF") } if killed { board[y][x] = Square::Space; new_positions.remove(&(y, x)); if friendly { goblins_left -=1 } else { elfs_left -= 1 }; } } } unit_positions = new_positions; if elfs_left == 0 || goblins_left == 0 { let mut outcome = 0usize; for row in &board { for column in row { if let Square::Occupied(unit) = column { outcome += unit.hit_points as usize; } } } if full_round { return (elfs_left == original_elfs, outcome * round) }; return (elfs_left == original_elfs, outcome * (round - 1)); } } panic!("Did not finish"); } #[cfg(test)] mod tests { use super::{solve_part1, solve_part2, input_generator}; #[test] fn examples() { let raw = "####### #.G...# #...EG# #.#.#G# #..G#E# #.....# #######"; let input = input_generator(raw); assert_eq!(solve_part1(&input), 27730); assert_eq!(solve_part2(&input), 4988); let raw2 = "####### #G..#E# #E#E.E# #G.##.# #...#E# #...E.# #######"; let input2 = input_generator(raw2); assert_eq!(solve_part1(&input2), 36334); let raw3 = "######### #G......# #.E.#...# #..##..G# #...##..# #...#...# #.G...G.# #.....G.# #########"; let input3 = input_generator(raw3); assert_eq!(solve_part1(&input3), 18740); assert_eq!(solve_part2(&input3), 1140); } }
true
55c84135051fbb71ac6e9868d8e9d950f4c995bd
Rust
bytecodealliance/wasmtime
/cranelift/reader/src/isaspec.rs
UTF-8
4,491
3.359375
3
[ "LLVM-exception", "Apache-2.0" ]
permissive
//! Parsed representation of `set` and `isa` commands. //! //! A test case file can contain `set` commands that set ISA-independent settings, and it can //! contain `isa` commands that select an ISA and applies ISA-specific settings. //! //! If a test case file contains `isa` commands, the tests will only be run against the specified //! ISAs. If the file contains no `isa` commands, the tests will be run against all supported ISAs. use crate::error::{Location, ParseError}; use crate::testcommand::TestOption; use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa}; use cranelift_codegen::settings::{Configurable, Flags, SetError}; /// The ISA specifications in a `.clif` file. pub enum IsaSpec { /// The parsed file does not contain any `isa` commands, but it may contain `set` commands /// which are reflected in the finished `Flags` object. None(Flags), /// The parsed file does contain `isa` commands. /// Each `isa` command is used to configure a `TargetIsa` trait object. Some(Vec<OwnedTargetIsa>), } impl IsaSpec { /// If the `IsaSpec` contains exactly 1 `TargetIsa` we return a reference to it pub fn unique_isa(&self) -> Option<&dyn TargetIsa> { if let Self::Some(ref isa_vec) = *self { if isa_vec.len() == 1 { return Some(&*isa_vec[0]); } } None } } /// An error type returned by `parse_options`. pub enum ParseOptionError { /// A generic ParseError. Generic(ParseError), /// An unknown flag was used, with the given name at the given location. UnknownFlag { /// Location where the flag was given. loc: Location, /// Name of the unknown flag. name: String, }, /// An unknown value was used, with the given name at the given location. UnknownValue { /// Location where the flag was given. loc: Location, /// Name of the unknown value. name: String, /// Value of the unknown value. value: String, }, } impl From<ParseOptionError> for ParseError { fn from(err: ParseOptionError) -> Self { match err { ParseOptionError::Generic(err) => err, ParseOptionError::UnknownFlag { loc, name } => Self { location: loc, message: format!("unknown setting '{}'", name), is_warning: false, }, ParseOptionError::UnknownValue { loc, name, value } => Self { location: loc, message: format!("unknown setting '{}={}'", name, value), is_warning: false, }, } } } macro_rules! option_err { ( $loc:expr, $fmt:expr, $( $arg:expr ),+ ) => { Err($crate::ParseOptionError::Generic($crate::ParseError { location: $loc.clone(), message: format!( $fmt, $( $arg ),+ ), is_warning: false, })) }; } /// Parse an iterator of command line options and apply them to `config`. /// /// Note that parsing terminates after the first error is encountered. pub fn parse_options<'a, I>( iter: I, config: &mut dyn Configurable, loc: Location, ) -> Result<(), ParseOptionError> where I: Iterator<Item = &'a str>, { for opt in iter { parse_option(opt, config, loc)?; } Ok(()) } /// Parse an single command line options and apply it to `config`. pub fn parse_option( opt: &str, config: &mut dyn Configurable, loc: Location, ) -> Result<(), ParseOptionError> { match TestOption::new(opt) { TestOption::Flag(name) => match config.enable(name) { Ok(_) => Ok(()), Err(SetError::BadName(name)) => Err(ParseOptionError::UnknownFlag { loc, name }), Err(_) => option_err!(loc, "not a boolean flag: '{}'", opt), }, TestOption::Value(name, value) => match config.set(name, value) { Ok(_) => Ok(()), Err(SetError::BadName(name)) => Err(ParseOptionError::UnknownValue { loc, name, value: value.to_string(), }), Err(SetError::BadType) => option_err!(loc, "invalid setting type: '{}'", opt), Err(SetError::BadValue(expected)) => { option_err!( loc, "invalid setting value for '{}', expected {}", opt, expected ) } }, } }
true
fd30b2e0a2229b3c4c20dd39e02f442cd9c04fb6
Rust
mariuspod/safe-client-gateway
/src/models/converters/tests/get_address_info.rs
UTF-8
1,620
2.765625
3
[ "MIT" ]
permissive
use crate::models::converters::get_address_info; use crate::providers::address_info::AddressInfo; use crate::providers::info::*; #[rocket::async_test] async fn get_address_info_address_diff_than_safe() { let address = "0x1234"; let safe = "0x4321"; let mut mock_info_provider = MockInfoProvider::new(); mock_info_provider .expect_full_address_info_search() .times(1) .return_once(move |_| { Ok(AddressInfo { name: "".to_string(), logo_uri: None, }) }); let expected = AddressInfo { name: "".to_string(), logo_uri: None, }; let actual = get_address_info(safe, address, &mut mock_info_provider).await; assert!(actual.is_some()); assert_eq!(expected, actual.unwrap()); } #[rocket::async_test] async fn get_address_info_address_diff_than_safe_error() { let address = "0x1234"; let safe = "0x4321"; let mut mock_info_provider = MockInfoProvider::new(); mock_info_provider .expect_full_address_info_search() .times(1) .return_once(move |_| bail!("No address info")); let actual = get_address_info(safe, address, &mut mock_info_provider).await; assert!(actual.is_none()); } #[rocket::async_test] async fn get_address_info_address_equal_to_safe() { let address = "0x1234"; let safe = "0x1234"; let mut mock_info_provider = MockInfoProvider::new(); mock_info_provider.expect_contract_info().times(0); let actual = get_address_info(safe, address, &mut mock_info_provider).await; assert!(actual.is_none()); }
true
5887d4f102ec213c516e797f534812b46cd85265
Rust
yoshuawuyts/markdown-edit
/src/lib.rs
UTF-8
2,968
2.71875
3
[ "MIT", "Apache-2.0" ]
permissive
#![cfg_attr(feature = "nightly", deny(missing_docs))] #![cfg_attr(feature = "nightly", feature(external_doc))] #![cfg_attr(feature = "nightly", doc(include = "../README.md"))] #![cfg_attr(test, deny(warnings))] extern crate pulldown_cmark; extern crate pulldown_cmark_to_cmark; #[macro_use] extern crate failure; use pulldown_cmark::{Event, Parser, Tag}; use pulldown_cmark_to_cmark::fmt::cmark; use std::{fs, path}; /// The Markdown object. pub struct Markdown<'p> { parser: Parser<'p>, } impl<'p> Markdown<'p> { /// Create a new instance. #[inline] pub fn new(raw_md: &'p str) -> Self { Self { parser: Parser::new(raw_md), } } /// Replace the body for a header. pub fn replace_section( self, header: &str, section: Vec<Event>, ) -> Result<String, failure::Error> { // Define the internal state machine. let mut inspect_header = false; let mut header_found = false; let mut should_replace_section = false; let mut sections_replaced = false; let events: Vec<Event> = { // Remove the unused text. self .parser .into_iter() .flat_map(move |event| { // Find all headers. if let Event::Start(tag) = &event { if let Tag::Header(_text) = tag { inspect_header = true; } } // Read the header text. if inspect_header { inspect_header = false; if let Event::Text(text) = &event { if text == header { header_found = true; } } } // Edit the body. if should_replace_section { let mut should_continue = true; if let Event::Start(tag) = &event { if let Tag::Header(_) = tag { should_replace_section = false; should_continue = false; } } if should_continue { return if !sections_replaced { sections_replaced = true; // FIXME: heh, this is inefficient. section.clone() } else { vec![] }; } } // Unless specified otherwise, return the event. vec![event] }) .collect() }; if sections_replaced { let mut buf = String::from(""); cmark(events.iter(), &mut buf, None)?; Ok(buf) } else if header_found { bail!("No header body found to replace."); } else { bail!("Could not find header"); } } } /// Replace pub fn replace_section( path: path::PathBuf, header: &str, body: String, ) -> Result<(), failure::Error> { let target = fs::read_to_string(&path)?; let body: Vec<Event> = Parser::new(&body).into_iter().collect(); let parser = Markdown::new(&target); let res = parser.replace_section(header, body)?; fs::write(&path, res)?; Ok(()) }
true
d3a0d4f18bf8341503c79008f464bcb94db8a22a
Rust
funn1est/leetcode-rust
/src/solutions/n557_reverse_words_in_a_string_iii/mod.rs
UTF-8
1,364
3.78125
4
[]
no_license
/// https://leetcode.com/problems/reverse-words-in-a-string-iii/ /// /// https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/ pub struct Solution {} impl Solution { pub fn reverse_words(s: String) -> String { s.split_whitespace() .map(|str| str.chars().rev().collect::<String>()) .collect::<Vec<_>>() .join(" ") } pub fn reverse_words_1(s: String) -> String { let mut tmp = "".to_owned(); s.chars() .enumerate() .fold(String::from(""), |mut all, (ind, c)| { if c == ' ' { all.push_str(&(format!("{} ", &tmp))); tmp = "".to_owned(); } else { tmp = c.to_string() + &tmp; if ind == s.len() - 1 { all.push_str(&tmp); } } all }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_reverse_words() { assert_eq!( Solution::reverse_words("Let's take LeetCode contest".to_owned()), "s'teL ekat edoCteeL tsetnoc".to_owned() ); assert_eq!( Solution::reverse_words_1("Let's take LeetCode contest".to_owned()), "s'teL ekat edoCteeL tsetnoc".to_owned() ); } }
true
1d812d300452c8eabe448ef35b3c913172365320
Rust
velyan/rust-skia
/skia-org/src/drivers/pdf.rs
UTF-8
619
2.625
3
[ "MIT" ]
permissive
use crate::artifact; use crate::drivers::DrawingDriver; use skia_safe::Canvas; use std::path::Path; pub struct PDF; impl DrawingDriver for PDF { const NAME: &'static str = "pdf"; fn new() -> Self { Self } fn draw_image( &mut self, size: (i32, i32), path: &Path, name: &str, func: impl Fn(&mut Canvas), ) { let mut document = skia_safe::pdf::new_document(None).begin_page(size, None); func(document.canvas()); let data = document.end_page().close(); artifact::write_file(data.as_bytes(), path, name, "pdf"); } }
true
41102f38b5d3d8d066c20e4ef41ca7038e59a575
Rust
repos-rust/iron
/src/response/mod.rs
UTF-8
1,883
3.328125
3
[ "MIT" ]
permissive
//! An augmentation of the rust-http Response struct. use std::io::{IoResult, File}; use std::io::util::copy; use std::path::BytesContainer; use http::status::Status; pub use Response = http::server::response::ResponseWriter; use self::mimes::get_generated_content_type; mod mimes; /// Adds common serving methods to Response. pub trait Serve: Writer { /// Serve the file located at `path`. /// /// This is usually a terminal process, and `Middleware` may want to /// call `Unwind` after a file is served. If the status should be /// anything other than `200`, the `Middleware` must set it, including in /// the case of an `Err`. /// /// `serve_file` will err out if the file does not exist, the process /// does not have correct permissions, or it has other issues in reading /// from the file. Middleware should handle this gracefully. fn serve_file(&mut self, &Path) -> IoResult<()>; /// Write the `Status` and data to the `Response`. /// /// `serve` will forward write errors to its caller. fn serve<S: BytesContainer>(&mut self, status: Status, body: S) -> IoResult<()>; } impl<'a> Serve for Response<'a> { fn serve_file(&mut self, path: &Path) -> IoResult<()> { let mut file = try!(File::open(path)); self.headers.content_type = path.extension_str().and_then(get_generated_content_type); copy(&mut file, self) } fn serve<S: BytesContainer>(&mut self, status: Status, body: S) -> IoResult<()> { self.status = status; Ok(try!(self.write(body.container_as_bytes()))) } } #[test] fn matches_content_type () { let path = &Path::new("test.txt"); let content_type = path.extension_str().and_then(get_generated_content_type).unwrap(); assert_eq!(content_type.type_.as_slice(), "text"); assert_eq!(content_type.subtype.as_slice(), "plain"); }
true
3e76044afc3dde3f3f1b0000c30e8dc790f0b375
Rust
chrisk699/twitch-discord-relay
/src/connectors/irc_parser.rs
UTF-8
2,770
3.203125
3
[]
no_license
use regex::Regex; pub struct IrcParser { regex: Regex } pub struct IrcMessage { pub raw: String, pub prefix: String, pub nick: String, pub username: String, pub hostname: String, pub command: String, pub params: Vec<String> } impl IrcParser { pub fn new() -> IrcParser { IrcParser { /* Regex that captures a reply received from an irc server Source: https://gist.github.com/datagrok/380449c30fd0c5cf2f30 Explanation: ^ # We'll match the whole line. Start. # Optional prefix and the space that separates it # from the next thing. Prefix can be a servername, # or nick[[!user]@host] (?::( # This whole set is optional but if it's # here it begins with : and ends with space ([^@!\ ]*) # nick (?: # then, optionally user/host (?: # but user is optional if host is given !([^@]*) # !user )? # (user was optional) @([^\ ]*) # @host )? # (host was optional) )\ )? # ":nick!user@host " ends ([^\ ]+) # IRC command (required) # Optional args, max 15, space separated. Last arg is # the only one that may contain inner spaces. More than # 15 words means remainder of words are part of 15th arg. # Last arg may be indicated by a colon prefix instead. # Pull the leading and last args out separately; we have # to split the former on spaces. ( (?: \ [^:\ ][^\ ]* # space, no colon, non-space characters ){0,14} # repeated up to 14 times ) # captured in one reference (?:\ :?(.*))? # the rest, does not capture colon. $ # EOL */ regex: Regex::new(r#"^(?::(([^@!\s]*)(?:(?:!([^@]*))?@([^\s]*))?)\s)?([^\s]+)((?:\s[^:\s][^\s]*){0,14})(?:\s:?(.*))?$"#).unwrap() } } pub fn parse(&self, str: String) -> IrcMessage { let caps = self.regex.captures(&str).unwrap(); // Extract variable parameters from capture group 7 and counting let params: Vec<String> = caps.iter().skip(6).map(|e| { match e { Some(val) => val.as_str().to_string(), None => "".to_string() } }).filter(|s| !s.is_empty()).collect(); IrcMessage { raw: caps.get(0).map_or("".to_string(), |m| m.as_str().to_string()), prefix: caps.get(1).map_or("".to_string(), |m| m.as_str().to_string()), nick: caps.get(2).map_or("".to_string(), |m| m.as_str().to_string()), username: caps.get(3).map_or("".to_string(), |m| m.as_str().to_string()), hostname: caps.get(4).map_or("".to_string(), |m| m.as_str().to_string()), command: caps.get(5).map_or("".to_string(), |m| m.as_str().to_string()), params: params } } }
true
c9ed789d8ef2cd1d0c6ff220ff8af822ad07bae9
Rust
ACRONYM-Group/ACIRustServer
/tests/database.rs
UTF-8
5,036
2.75
3
[]
no_license
//! Integration tests for the DatabaseInterface object, this object is used for access to individual databases extern crate aci_server; use aci_server::database::{Database, DatabaseInterface, UserAuthentication}; #[test] pub fn integration_test_database_read_write() { let db = DatabaseInterface::new(Database::new("Database0"), chashmap::CHashMap::new()); let user = UserAuthentication{is_authed: true, name: "user".to_string(), domain:"a_auth".to_string()}; assert!(db.read_from_key("key", &user).is_err()); db.write_to_key("key", serde_json::json!(0), &user).unwrap(); assert_eq!(db.read_from_key("key", &user), Ok(serde_json::json!(0))); assert!(db.read_from_key("obj", &user).is_err()); db.write_to_key("obj", serde_json::json!({"a": "b", "c": 5}), &user).unwrap(); assert_eq!(db.read_from_key("obj", &user), Ok(serde_json::json!({"a": "b", "c": 5}))); } #[test] pub fn integration_test_database_read_write_lists() { let db = DatabaseInterface::new(Database::new("Database0"), chashmap::CHashMap::new()); let user = UserAuthentication{is_authed: true, name: "user".to_string(), domain:"a_auth".to_string()}; assert!(db.read_from_key("list", &user).is_err()); db.write_to_key("list", serde_json::json!([0, 1, "2", "3", {"a": "b", "c": 5}]), &user).unwrap(); assert_eq!(db.read_from_key_index("list", 0, &user), Ok(serde_json::json!(0))); assert_eq!(db.read_from_key_index("list", 1, &user), Ok(serde_json::json!(1))); assert_eq!(db.read_from_key_index("list", 2, &user), Ok(serde_json::json!("2"))); assert_eq!(db.read_from_key_index("list", 3, &user), Ok(serde_json::json!("3"))); assert_eq!(db.read_from_key_index("list", 4, &user), Ok(serde_json::json!({"a": "b", "c": 5}))); assert!(db.read_from_key_index("list", 5, &user).is_err()); } #[test] pub fn integration_test_database_append_lists() { let db = DatabaseInterface::new(Database::new("Database0"), chashmap::CHashMap::new()); let user = UserAuthentication{is_authed: true, name: "user".to_string(), domain:"a_auth".to_string()}; assert!(db.read_from_key("list", &user).is_err()); db.write_to_key("list", serde_json::json!([0, 1, "2"]), &user).unwrap(); assert_eq!(db.read_from_key_index("list", 0, &user), Ok(serde_json::json!(0))); assert_eq!(db.read_from_key_index("list", 1, &user), Ok(serde_json::json!(1))); assert_eq!(db.read_from_key_index("list", 2, &user), Ok(serde_json::json!("2"))); assert!(db.read_from_key_index("list", 3, &user).is_err()); db.append_to_key("list", serde_json::json!("Hello World!"), &user).unwrap(); assert_eq!(db.read_from_key_index("list", 0, &user), Ok(serde_json::json!(0))); assert_eq!(db.read_from_key_index("list", 1, &user), Ok(serde_json::json!(1))); assert_eq!(db.read_from_key_index("list", 2, &user), Ok(serde_json::json!("2"))); assert_eq!(db.read_from_key_index("list", 3, &user), Ok(serde_json::json!("Hello World!"))); assert!(db.read_from_key_index("list", 4, &user).is_err()); } #[test] pub fn integration_test_database_list_length() { let db = DatabaseInterface::new(Database::new("Database0"), chashmap::CHashMap::new()); let user = UserAuthentication{is_authed: true, name: "user".to_string(), domain:"a_auth".to_string()}; assert!(db.read_from_key("list", &user).is_err()); db.write_to_key("list", serde_json::json!([0, 1, "2"]), &user).unwrap(); assert_eq!(db.get_length_from_key("list", &user), Ok(3)); db.append_to_key("list", serde_json::json!("Hello World!"), &user).unwrap(); assert_eq!(db.get_length_from_key("list", &user), Ok(4)); } #[test] pub fn integration_test_database_last_n_list() { let db = DatabaseInterface::new(Database::new("Database0"), chashmap::CHashMap::new()); let user = UserAuthentication{is_authed: true, name: "user".to_string(), domain:"a_auth".to_string()}; assert!(db.read_from_key("list", &user).is_err()); db.write_to_key("list", serde_json::json!([0, 1, "2", "3", 4, 5, "6"]), &user).unwrap(); assert_eq!(db.read_last_n_from_key("list", 0, &user), Ok(serde_json::json!([]))); assert_eq!(db.read_last_n_from_key("list", 1, &user), Ok(serde_json::json!(["6"]))); assert_eq!(db.read_last_n_from_key("list", 2, &user), Ok(serde_json::json!([5, "6"]))); assert_eq!(db.read_last_n_from_key("list", 3, &user), Ok(serde_json::json!([4, 5, "6"]))); assert_eq!(db.read_last_n_from_key("list", 4, &user), Ok(serde_json::json!(["3", 4, 5, "6"]))); assert_eq!(db.read_last_n_from_key("list", 5, &user), Ok(serde_json::json!(["2", "3", 4, 5, "6"]))); assert_eq!(db.read_last_n_from_key("list", 6, &user), Ok(serde_json::json!([1, "2", "3", 4, 5, "6"]))); assert_eq!(db.read_last_n_from_key("list", 7, &user), Ok(serde_json::json!([0, 1, "2", "3", 4, 5, "6"]))); assert_eq!(db.read_last_n_from_key("list", 8, &user), Ok(serde_json::json!([0, 1, "2", "3", 4, 5, "6"]))); }
true
47d4432fbceb3ddb47ab4de00ae7839af5af335f
Rust
andrewhickman/json-view
/src/ser/exclude.rs
UTF-8
7,213
2.953125
3
[ "Apache-2.0", "MIT" ]
permissive
use std::collections::BTreeMap; use std::io::{self, Write}; use std::ops::Range; use failure::Fallible; use json::ser::{CharEscape, Formatter, PrettyFormatter}; pub fn write<'de, F, W>(excludes: ExcludeSet, writer: W, f: F) -> Fallible<()> where F: FnOnce(&mut json::Serializer<W, Excluder>) -> Fallible<()>, W: Write, { let excluder = Excluder { excludes, position: 0, depth: 0, pretty: PrettyFormatter::new(), }; let mut ser = json::Serializer::with_formatter(writer, excluder); f(&mut ser) } pub struct Excluder { excludes: ExcludeSet, position: u32, depth: u32, pretty: PrettyFormatter<'static>, } impl Excluder { fn writing(&self) -> bool { self.depth == 0 } fn begin<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { if let Some(length) = self.excludes.get(self.position) { if self.writing() { write!(writer, " {} items... ", length)? } self.depth += 1; } self.position += 1; Ok(()) } fn end(&mut self) { if let Some(_) = self.excludes.get(self.position) { self.depth -= 1; } self.position += 1; } fn delegate( &mut self, f: impl FnOnce(&mut PrettyFormatter) -> io::Result<()>, ) -> io::Result<()> { if self.writing() { f(&mut self.pretty) } else { Ok(()) } } } impl Formatter for Excluder { fn write_null<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_null(writer)) } fn write_bool<W: ?Sized>(&mut self, writer: &mut W, value: bool) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_bool(writer, value)) } fn write_i8<W: ?Sized>(&mut self, writer: &mut W, value: i8) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_i8(writer, value)) } fn write_i16<W: ?Sized>(&mut self, writer: &mut W, value: i16) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_i16(writer, value)) } fn write_i32<W: ?Sized>(&mut self, writer: &mut W, value: i32) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_i32(writer, value)) } fn write_i64<W: ?Sized>(&mut self, writer: &mut W, value: i64) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_i64(writer, value)) } fn write_u8<W: ?Sized>(&mut self, writer: &mut W, value: u8) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_u8(writer, value)) } fn write_u16<W: ?Sized>(&mut self, writer: &mut W, value: u16) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_u16(writer, value)) } fn write_u32<W: ?Sized>(&mut self, writer: &mut W, value: u32) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_u32(writer, value)) } fn write_u64<W: ?Sized>(&mut self, writer: &mut W, value: u64) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_u64(writer, value)) } fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_f32(writer, value)) } fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_f64(writer, value)) } fn write_number_str<W: ?Sized>(&mut self, writer: &mut W, value: &str) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_number_str(writer, value)) } fn begin_string<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.begin_string(writer)) } fn end_string<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.end_string(writer)) } fn write_string_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_string_fragment(writer, fragment)) } fn write_char_escape<W: ?Sized>( &mut self, writer: &mut W, char_escape: CharEscape, ) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_char_escape(writer, char_escape)) } fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.begin_array(writer))?; self.begin(writer) } fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.end(); self.delegate(|f| f.end_array(writer)) } fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> where W: Write, { self.delegate(|f| f.begin_array_value(writer, first)) } fn end_array_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.end_array_value(writer)) } fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.begin_object(writer))?; self.begin(writer) } fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.end(); self.delegate(|f| f.end_object(writer)) } fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> where W: Write, { self.delegate(|f| f.begin_object_key(writer, first)) } fn end_object_key<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.end_object_key(writer)) } fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.begin_object_value(writer)) } fn end_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> where W: Write, { self.delegate(|f| f.end_object_value(writer)) } fn write_raw_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> where W: Write, { self.delegate(|f| f.write_raw_fragment(writer, fragment)) } } #[derive(Debug)] pub struct ExcludeSet { indices: BTreeMap<u32, u32>, } impl ExcludeSet { pub fn new() -> Self { ExcludeSet { indices: BTreeMap::new(), } } pub fn insert(&mut self, range: Range<u32>, length: u32) { debug_assert!(length != 0); self.indices.insert(range.start, length); self.indices.insert(range.end, 0); } fn get(&self, index: u32) -> Option<u32> { self.indices.get(&index).cloned() } }
true
36310afe2ba44ed8921a9f6bdbacf70e9231a6dc
Rust
canpok1/atcoder-rust
/contests/abc188/src/bin/a.rs
UTF-8
445
2.890625
3
[]
no_license
fn main() { let (x, y) = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut ws = line.trim_end().split_whitespace(); let n1: isize = ws.next().unwrap().parse().unwrap(); let n2: isize = ws.next().unwrap().parse().unwrap(); (n1, n2) }; let diff = x - y; if diff.abs() < 3 { println!("Yes"); } else { println!("No"); } }
true
580b82c57b67138bda311950f009a980f482f0b6
Rust
mislav-markovic/advent-of-code
/aoc-17/day03_spiral_memory/src/main.rs
UTF-8
4,152
3.28125
3
[]
no_license
use std::collections::HashMap; enum SquareSide { Down(i32), Up(i32), Left(i32), Right(i32), } #[derive(PartialEq, Eq, Hash)] struct Point { x: i32, y: i32, } fn main() { println!("Enter part 1 input: "); let location = read_number(); println!("Enter part 2 input: "); let threshold = read_number(); let (level, _, _) = find_level(location); let zero = Point {x: 0, y : 0}; let first_after_threshold = find_threshold_value(threshold); match find_side(location){ SquareSide::Down(x) => println!("Part 1 distance: {}", manhattan_distance(zero, Point{x: x, y: -1 * level as i32})), SquareSide::Up(x) => println!("Part 1 distance: {}", manhattan_distance(zero, Point{x: x, y: level as i32})), SquareSide::Left(y) => println!("Part 1 distance: {}", manhattan_distance(zero, Point{x: -1 * level as i32, y: y})), SquareSide::Right(y) => println!("Part 1 distance: {}", manhattan_distance(zero, Point{x: level as i32, y: y})), } println!("First after threshold is: {}", first_after_threshold); } fn find_threshold_value(thrsh: u32) -> u32 { let mut memory: HashMap<Point, u32> = HashMap::new(); memory.insert(Point{x: 0, y: 0}, 1); let mut level = 1; let mut side = 1; loop { let (last_max, thrsh_passed) = fill_spiral(&mut memory, side, level, thrsh); if thrsh_passed {break last_max;} level += 1; side += 2 } } fn fill_spiral(mem: &mut HashMap<Point, u32>, prev_side: u32, level: u32, threshold: u32) -> (u32, bool){ let start_point = Point{x:level as i32, y:-1 * (level-1) as i32}; let mut sum = 0u32; for i in 0..prev_side + 1 { let p = Point {x:start_point.x, y: start_point.y + i as i32}; sum = get_neighbours_sum(&p, &mem); if sum > threshold { return (sum, true); } mem.insert(p, sum); } for i in 1..prev_side + 2 { let p = Point {x:start_point.x - i as i32, y: start_point.y + prev_side as i32}; sum = get_neighbours_sum(&p, &mem); if sum > threshold { return (sum, true); } mem.insert(p, sum); } for i in 1..prev_side + 2 { let p = Point {x:start_point.x - (prev_side+1) as i32, y:start_point.y + prev_side as i32 - i as i32}; sum = get_neighbours_sum(&p, &mem); if sum > threshold { return (sum, true); } mem.insert(p, sum); } for i in 1..prev_side + 2 { let p = Point {x:start_point.x - (prev_side + 1) as i32 + i as i32, y: start_point.y - 1}; sum = get_neighbours_sum(&p, &mem); if sum > threshold { return (sum, true); } mem.insert(p, sum); } (sum, false) } fn get_neighbours_sum(loc: &Point, mem: &HashMap<Point, u32>) -> u32 { let mut sum = 0; for i in -1..2 { for j in -1..2 { let p = Point{x: loc.x + i, y: loc.y + j}; sum += mem.get(&p).unwrap_or(&0); } } sum } fn manhattan_distance(p1: Point, p2: Point) -> i32 { (p1.x - p2.x).abs() + (p1.y - p2.y).abs() } fn read_number() -> u32 { use std::io; let mut s = String::new(); io::stdin().read_line(&mut s).expect("Failed to read line"); s.trim().parse().unwrap() } fn find_side(loc: u32) -> SquareSide { let (_, mut high, row_len) = find_level(loc); let mut low = high - row_len; if loc >= low { return SquareSide::Down(loc as i32 - half_point(high, low)) } high = low; low -= row_len; if loc >= low { return SquareSide::Left(half_point(high, low) - loc as i32) } high = low; low -= row_len; if loc >= low { return SquareSide::Up(half_point(high, low) - loc as i32) } high = low; low -= row_len; return SquareSide::Right(loc as i32 - half_point(high, low)) } fn half_point(h: u32, l: u32) -> i32 { ((h+l) / 2) as i32 } fn find_level(loc: u32) -> (u32, u32, u32) { let mut max = 1; let mut side = 1; for i in 1.. { max += 2*(side+2) + 2*side; side += 2; if max >= loc { return (i, max, side-1); } } (0, 0, 0) }
true
f3a2880c062b8427ecf1ba77d7e6a684278ae36e
Rust
yijie37/DaQiao
/bridge/parity-ethereum/ethcore/machine/src/substate.rs
UTF-8
2,841
2.9375
3
[ "Unlicense" ]
permissive
// Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity Ethereum is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>. //! Execution environment substate. use std::collections::HashSet; use ethereum_types::Address; use common_types::log_entry::LogEntry; /// State changes which should be applied in finalize, /// after transaction is fully executed. #[derive(Debug, Default)] pub struct Substate { /// Any accounts that have suicided. pub suicides: HashSet<Address>, /// Any accounts that are touched. pub touched: HashSet<Address>, /// Any logs. pub logs: Vec<LogEntry>, /// Refund counter of SSTORE. pub sstore_clears_refund: i128, /// Created contracts. pub contracts_created: Vec<Address>, } impl Substate { /// Creates new substate. pub fn new() -> Self { Substate::default() } /// Merge secondary substate `s` into self, accruing each element correspondingly. pub fn accrue(&mut self, s: Substate) { self.suicides.extend(s.suicides); self.touched.extend(s.touched); self.logs.extend(s.logs); self.sstore_clears_refund += s.sstore_clears_refund; self.contracts_created.extend(s.contracts_created); } } #[cfg(test)] mod tests { use ethereum_types::Address; use common_types::log_entry::LogEntry; use super::Substate; #[test] fn created() { let sub_state = Substate::new(); assert_eq!(sub_state.suicides.len(), 0); } #[test] fn accrue() { let mut sub_state = Substate::new(); sub_state.contracts_created.push(Address::from_low_u64_be(1)); sub_state.logs.push(LogEntry { address: Address::from_low_u64_be(1), topics: vec![], data: vec![] }); sub_state.sstore_clears_refund = (15000 * 5).into(); sub_state.suicides.insert(Address::from_low_u64_be(10)); let mut sub_state_2 = Substate::new(); sub_state_2.contracts_created.push(Address::from_low_u64_be(2u64)); sub_state_2.logs.push(LogEntry { address: Address::from_low_u64_be(1), topics: vec![], data: vec![] }); sub_state_2.sstore_clears_refund = (15000 * 7).into(); sub_state.accrue(sub_state_2); assert_eq!(sub_state.contracts_created.len(), 2); assert_eq!(sub_state.sstore_clears_refund, (15000 * 12).into()); assert_eq!(sub_state.suicides.len(), 1); } }
true
0c2d9fed22cc119167ee4211ff61855c3ea9847c
Rust
KaoImin/bft-core
/src/types.rs
UTF-8
6,716
2.859375
3
[ "MIT" ]
permissive
use serde_derive::{Deserialize, Serialize}; use std::{collections::HashMap, fmt}; /// Type for node address. #[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Hash)] pub struct Address(Vec<u8>); impl fmt::Debug for Address { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.0.len() > 5 { return write!( f, "Addr[{}, {}, {}, {}, {}]", self.0[0], self.0[1], self.0[2], self.0[3], self.0[4] ); } write!(f, "Prop {:?}", self.0) } } impl Address { /// A function to create a new Address. pub fn new(addr: Vec<u8>) -> Self { Address(addr) } /// A function to transfer Address into vec. pub fn into_vec(self) -> Vec<u8> { self.0 } } /// Type for proposal. #[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Hash)] pub struct Target(Vec<u8>); impl fmt::Debug for Target { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.0.len() > 5 { return write!( f, "Prop[{}, {}, {}, {}, {}]", self.0[0], self.0[1], self.0[2], self.0[3], self.0[4] ); } write!(f, "Prop {:?}", self.0) } } impl Target { /// A function to create a new Target. pub fn new(ctx: Vec<u8>) -> Self { Target(ctx) } /// Return true if the Target is an empty vec. pub fn is_nil(&self) -> bool { self.0.is_empty() } /// pub fn into_vec(self) -> Vec<u8> { self.0 } } /// BFT input message type. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub enum CoreInput { /// Proposal message. Proposal(Proposal), /// Vote message. Vote(Vote), /// Feed messge, this is the proposal of the height. Feed(Feed), /// Verify response #[cfg(feature = "async_verify")] VerifyResp(VerifyResp), /// Status message, rich status. Status(Status), /// Commit message. Commit(Commit), /// Pause BFT state machine. Pause, /// Start running BFT state machine. Start, } /// BFT output message type. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub enum CoreOutput { /// Proposal message. Proposal(Proposal), /// Vote message. Vote(Vote), /// Feed messge, this is the proposal of the height. Commit(Commit), /// Request a feed of a height. GetProposalRequest(u64), } /// Bft vote types. #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Hash)] pub enum VoteType { /// Vote type prevote. Prevote, /// Vote type precommit. Precommit, } /// A proposal #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Proposal { /// The height of a proposal. pub height: u64, /// The round of a proposal. pub round: u64, /// The proposal content. pub content: Target, /// A lock round of the proposal. If the proposal has not been locked, /// it should be `None`. pub lock_round: Option<u64>, /// The lock votes of the proposal. If the proposal has not been locked, /// it should be an empty `Vec`. pub lock_votes: Vec<Vote>, /// The address of proposer. pub proposer: Address, } /// A PoLC. #[derive(Serialize, Deserialize, Clone, Debug)] pub(crate) struct LockStatus { /// The lock proposal. pub(crate) proposal: Target, /// The lock round. pub(crate) round: u64, /// The lock votes. pub(crate) votes: Vec<Vote>, } /// A vote to a proposal. #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Hash)] pub struct Vote { /// Prevote vote or precommit vote pub vote_type: VoteType, /// The height of a vote. pub height: u64, /// The round of a vote. pub round: u64, /// The vote proposal. pub proposal: Target, /// The address of voter. pub voter: Address, } /// A proposal content for a height. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Feed { /// The height of the proposal. pub height: u64, /// A proposal content. pub proposal: Target, } /// A commit of a height. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Commit { /// The height of result. pub height: u64, /// The round of result. pub round: u64, /// Consensus result. pub proposal: Target, /// Precommit votes for generate proof. pub lock_votes: Vec<Vote>, /// The node address. pub address: Address, } /// The rich status of a height. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Status { /// The height of rich status. pub height: u64, /// The time interval of next height. If it is none, maintain the old interval. pub interval: Option<u64>, /// A new authority list for next height. pub authority_list: Vec<Node>, } impl Status { pub(crate) fn get_address_list(&self) -> Vec<Address> { let mut res = Vec::new(); for addr in self.authority_list.iter() { res.push(addr.address.clone()); } res } pub(crate) fn get_propose_weight_list(&self) -> Vec<u64> { let mut res = Vec::new(); for pw in self.authority_list.iter() { res.push(pw.propose_weight); } res } pub(crate) fn get_vote_weight_map(&self) -> HashMap<Address, u64> { let mut res = HashMap::new(); for vw in self.authority_list.iter() { res.entry(vw.address.clone()).or_insert(vw.vote_weight); } res } } /// The node information. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Node { /// The node address. pub address: Address, /// The propose weight of the node. pub propose_weight: u64, /// The vote weight of the node. pub vote_weight: u64, } impl Node { /// A function to create a new Node. pub fn new(address: Address) -> Self { Node { address, propose_weight: 1, vote_weight: 1, } } /// A function to set a propose weight of the node. pub fn set_propose_weight(&mut self, weight: u64) { self.propose_weight = weight; } /// A function to set a vote weight of the node. pub fn set_vote_weight(&mut self, weight: u64) { self.vote_weight = weight; } } /// A verify result of a proposal. #[cfg(feature = "async_verify")] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct VerifyResp { /// The Response of proposal verify pub is_pass: bool, /// The verify proposal pub proposal: Target, }
true
000dc4bfba067eed169b14073b9d26022f85139a
Rust
DavidMikeSimon/lotsa
/lotsa/src/unique_descrip.rs
UTF-8
681
2.75
3
[ "MIT" ]
permissive
pub trait UniqueDescrip { // TODO: Const? fn unique_descrip(&self) -> String; } impl UniqueDescrip for u8 { fn unique_descrip(&self) -> String { format!("{}u8", self) } } impl UniqueDescrip for u16 { fn unique_descrip(&self) -> String { format!("{}u16", self) } } impl UniqueDescrip for u32 { fn unique_descrip(&self) -> String { format!("{}u32", self) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_descrip_u8() { assert_eq!("42u8", 42u8.unique_descrip()); } #[test] fn test_descrip_u16() { assert_eq!("42u16", 42u16.unique_descrip()); } #[test] fn test_descrip_u32() { assert_eq!("42u32", 42u32.unique_descrip()); } }
true
829bc16467b10293cb06f1dd5524f801e9566916
Rust
koivunej/aoc
/2019/day12/src/main.rs
UTF-8
9,271
2.96875
3
[]
no_license
use std::str::FromStr; use std::fmt; use std::io::Read; //use itertools::Itertools; fn main() { let mut buffer = String::new(); let stdin = std::io::stdin(); let mut locked = stdin.lock(); locked.read_to_string(&mut buffer).unwrap(); let initial = System { time: 0, bodies: buffer.lines() .map(Body::from_str) .collect::<Result<_, _>>() .unwrap() }; let s = initial .clone() .into_iter() .nth(1000) .unwrap(); println!("stage1: {}", s.total_energy()); let mut initial_again = initial.clone(); initial_again.step_until_eq(&initial); println!("stage2: {}", initial_again.time); } #[derive(Clone, PartialEq)] struct System { time: u64, bodies: Vec<Body>, } impl fmt::Debug for System { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { writeln!(fmt, "After {} steps:", self.time)?; for body in &self.bodies { writeln!(fmt, "{:?}", body)?; } writeln!(fmt, "") } } impl System { fn total_energy(&self) -> i32 { self.bodies.iter() .map(Body::total_energy) .sum() } fn step(&self) -> System { let mut bodies = Vec::with_capacity(self.bodies.len()); for a in self.bodies.iter() { let mut vel = a.vel.clone(); for b in self.bodies.iter() { for ((a, b), v) in a.pos.iter().zip(b.pos.iter()).zip(vel.iter_mut()) { *v = *v + (b - a).signum(); } } let mut pos = a.pos.clone(); for (v, p) in vel.iter().zip(pos.iter_mut()) { *p = *p + v; } bodies.push(Body { pos, vel }); } System { time: self.time + 1, bodies } } #[allow(dead_code)] fn step_mut(&mut self, tmp: &mut Vec<Body>) { // too slow tmp.clear(); for a in self.bodies.iter() { let mut vel = a.vel.clone(); for b in self.bodies.iter() { for ((a, b), v) in a.pos.iter().zip(b.pos.iter()).zip(vel.iter_mut()) { *v = *v + (b - a).signum(); } } let mut pos = a.pos.clone(); for (v, p) in vel.iter().zip(pos.iter_mut()) { *p = *p + v; } tmp.push(Body { pos, vel }); } std::mem::swap(&mut self.bodies, tmp); if (self.time + 1) % 1_000_000 == 0 { println!("{}", self.time + 1); } self.time += 1; } fn step_until_eq(&mut self, other: &Self) { use num::Integer; // could not do this without a hint ... threading is really extra for this let (a, b, c) = if false { (self.partition_off(0, other), self.partition_off(1, other), self.partition_off(2, other)) } else { // this might faster by a millisecond let a = self.partition_off_thread(0, other); let b = self.partition_off_thread(1, other); let c = self.partition_off_thread(2, other); (a.join().unwrap(), b.join().unwrap(), c.join().unwrap()) }; let ((a, xs), (b, ys), (c, zs)) = (a, b, c); // each of the axes is periodic and we need to find suitable time when they all align let time = a.lcm(&b.lcm(&c)); self.time += time; for i in 0..4 { self.bodies[i].pos = [xs[i], ys[i], zs[i]]; self.bodies[i].vel = [0, 0, 0]; } } fn partition_off_thread(&self, axis: usize, other: &Self) -> std::thread::JoinHandle<(u64, [i32; 4])> { let other = other.clone(); let mut cs = [0i32; 4]; cs.copy_from_slice(self.bodies.iter().map(|b| b.pos[axis]).collect::<Vec<_>>().as_slice()); let mut vcs = [0i32; 4]; vcs.copy_from_slice(self.bodies.iter().map(|b| b.vel[axis]).collect::<Vec<_>>().as_slice()); let mut expected = [0i32; 4]; expected.copy_from_slice(other.bodies.iter().map(|b| b.pos[axis]).collect::<Vec<_>>().as_slice()); std::thread::spawn(move || Self::run_axis_period(cs, vcs, expected, [0, 0, 0, 0])) } fn run_axis_period(mut cs: [i32; 4], mut vcs: [i32; 4], expected_pos: [i32; 4], expected_vel: [i32; 4]) -> (u64, [i32; 4]) { for steps in 1u64.. { for i in 0..4 { for j in 0..4 { vcs[i] += (cs[j] - cs[i]).signum(); } } for i in 0..4 { cs[i] += vcs[i]; } if vcs == expected_vel && cs == expected_pos { return (steps, cs); } } unreachable!() } fn partition_off(&self, axis: usize, other: &Self) -> (u64, [i32; 4]) { let mut cs = [0i32; 4]; cs.copy_from_slice(self.bodies.iter().map(|b| b.pos[axis]).collect::<Vec<_>>().as_slice()); let mut vcs = [0i32; 4]; vcs.copy_from_slice(self.bodies.iter().map(|b| b.vel[axis]).collect::<Vec<_>>().as_slice()); let mut expected = [0i32; 4]; expected.copy_from_slice(other.bodies.iter().map(|b| b.pos[axis]).collect::<Vec<_>>().as_slice()); Self::run_axis_period(cs, vcs, expected, [0, 0, 0, 0]) } fn into_iter(self) -> Steps { Steps { s: self } } } struct Steps { s: System } impl Iterator for Steps { type Item = System; fn next(&mut self) -> Option<System> { let ret = Some(self.s.clone()); self.s = self.s.step(); ret } } #[derive(Clone, PartialEq)] struct Body { pos: [i32; 3], vel: [i32; 3], } impl fmt::Debug for Body { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "<{:>3?} {:>3?}>", self.pos, self.vel) } } impl Body { fn total_energy(&self) -> i32 { self.potential_energy() * self.kinetic_energy() } fn potential_energy(&self) -> i32 { Self::energy(&self.pos) } fn kinetic_energy(&self) -> i32 { Self::energy(&self.vel) } fn energy(vals: &[i32]) -> i32 { vals.iter().copied().map(i32::abs).sum() } } #[derive(Debug, PartialEq)] enum BodyParsingError { ExtraElements, MissingElements, Form, InvalidNum(std::num::ParseIntError), } impl From<std::num::ParseIntError> for BodyParsingError { fn from(e: std::num::ParseIntError) -> Self { BodyParsingError::InvalidNum(e) } } impl FromStr for Body { type Err = BodyParsingError; fn from_str(s: &str) -> Result<Self, Self::Err> { use BodyParsingError::*; let mut split = s.split(','); let x = split.next().ok_or(MissingElements)?; let y = split.next().ok_or(MissingElements)?.trim(); let z = split.next().ok_or(MissingElements)?.trim(); if split.next().is_some() { return Err(ExtraElements); } // well this is horrific let x = i32::from_str(x.split('=').skip(1).next().ok_or(Form)?)?; let y = i32::from_str(y.split('=').skip(1).next().ok_or(Form)?)?; let z = z.split('=').skip(1).next() .and_then(|s| s.split('>').next()).ok_or(Form) .and_then(|s| s.parse().map_err(BodyParsingError::from))?; Ok(Body { pos: [x, y, z], vel: [0, 0, 0], }) } } impl From<&([i32; 3], [i32; 3])> for Body { fn from((pos, vel): &([i32; 3], [i32; 3])) -> Self { Body { pos: *pos, vel: *vel } } } #[test] fn parse_body() { let input = "<x=-1, y=0, z=2>"; assert_eq!([-1, 0, 2], Body::from_str(input).unwrap().pos) } #[test] fn example_system1() { let input = "<x=-1, y=0, z=2> <x=2, y=-10, z=-7> <x=4, y=-8, z=8> <x=3, y=5, z=-1>"; let s = System { time: 0, bodies: input.lines().map(|s| s.parse::<Body>()).collect::<Result<_, _>>().unwrap() }.into_iter().nth(10).unwrap(); let expected = System { time: 10, bodies: [ ([2, 1, -3], [-3,-2, 1]), ([1,-8, 0], [-1, 1, 3]), ([3,-6, 1], [ 3, 2,-3]), ([2, 0, 4], [ 1,-1,-1]) ].into_iter().map(Body::from).collect() }; assert_eq!(s, expected); assert_eq!(s.total_energy(), 179); } #[test] fn example_system2() { let input = "<x=-8, y=-10, z=0> <x=5, y=5, z=10> <x=2, y=-7, z=3> <x=9, y=-8, z=-3>"; let s = System { time: 0, bodies: input.lines().map(|s| s.parse::<Body>()).collect::<Result<_, _>>().unwrap() }.into_iter().nth(100).unwrap(); let expected = System { time: 100, bodies: [ ([ 8,-12,-9], [-7, 3, 0]), ([ 13, 16, -3], [ 3,-11,-5]), ([-29,-11, -1], [-3, 7, 4]), ([ 16,-13, 23], [ 7, 1, 1]) ].into_iter().map(Body::from).collect() }; assert_eq!(s, expected); assert_eq!(s.total_energy(), 1940); } #[test] fn step_until_initial() { let input = "<x=-1, y=0, z=2> <x=2, y=-10, z=-7> <x=4, y=-8, z=8> <x=3, y=5, z=-1>"; let mut s = System { time: 0, bodies: input.lines().map(|s| s.parse::<Body>()).collect::<Result<_, _>>().unwrap() }; let initial = s.clone(); s.step_until_eq(&initial); assert_eq!(s.time, 2772, "{:?}", s); }
true
7f84345a7b05db323178b8162b66ef3bc78e7ef4
Rust
JoshOrndorff/advent-of-code-2019
/day14/src/djkstra.rs
UTF-8
4,740
3.21875
3
[]
no_license
use super::{parser, Reaction, Reagent}; use std::collections::{BTreeMap, HashSet}; use std::convert::TryInto; #[derive(Hash, Debug, PartialEq, Eq, Clone)] struct State { reagents: BTreeMap<String, i64>, ore_consumed: u64, } impl State { fn new() -> Self { Self { reagents: BTreeMap::new(), ore_consumed: 0, } } fn new_one_fuel() -> Self { let mut s = Self { reagents: BTreeMap::new(), ore_consumed: 0, }; s.reagents.insert("FUEL".into(), 1); s } fn get_next_state(&self, reaction: &Reaction) -> Option<Self> { // Make a clone that we will mutate into the neighbor state let mut neighbor = self.clone(); // Loop through the inputs subtracting them for input in &reaction.inputs { // If we don't have enough, then exit early match neighbor.reagents.get(&input.name) { None => { return None; } Some(&amount_we_have) => { if amount_we_have < input.quantity { return None; } neighbor .reagents .insert(input.name.clone(), amount_we_have - input.quantity); } } } // If we made it through the inputs without early returning, then this reaction is possible // so update the output quantity too *neighbor .reagents .entry(reaction.output.name.clone()) .or_insert(0) += reaction.output.quantity; Some(neighbor) } fn get_prev_state(&self, reaction: &Reaction) -> Option<Self> { // Make a clone that we will mutate into the previous state let mut prev = self.clone(); // Make sure we have the output necessary, and if so subtract it. let our_output_quantity = prev.reagents.get(&reaction.output.name).unwrap_or(&0); if our_output_quantity <= &0i64 { // This reaction doesn't apply, so return early return None; } prev.reagents.insert( reaction.output.name.clone(), our_output_quantity - reaction.output.quantity, ); // Loop through the inputs adding them for input in &reaction.inputs { *prev.reagents.entry(input.name.clone()).or_insert(0) += input.quantity; } Some(prev) } fn has_fuel(&self) -> bool { match self.reagents.get("FUEL".into()) { None => false, Some(amount) => amount > &0, } } fn gather_ore(&self) -> Self { let mut next_state = self.clone(); *next_state.reagents.entry("ORE".into()).or_insert(0) += 1; next_state.ore_consumed += 1; next_state } } pub fn dijkstra_solution(reactions: &Vec<Reaction>) -> u64 { // We'll solve the problem using Dijkstra's algorithm to find a path from no resources // to one fules let mut unexplored = HashSet::<State>::new(); let mut explored = HashSet::<State>::new(); // We'll find a path from the // starting state (empty) to any valid target state (at least one fuel). unexplored.insert(State::new()); let mut current_state = State::new(); while !current_state.has_fuel() { // Get an owned instance of the next state to explore current_state = unexplored .iter() .min_by(|x, y| x.ore_consumed.cmp(&y.ore_consumed)) .expect("Unexplored set should not be empty; min_by will return Some(_); qed;") .clone(); // Calculate any states we can transition to by applying a reaction let neighbors = reactions .iter() .filter_map(|r| current_state.get_next_state(r)) .collect::<Vec<_>>(); // Mark the current state explored explored.insert(unexplored.take(&current_state).unwrap()); // We also want to explore gathering more ore because some reactions // need more than 1 ore. unexplored.insert(current_state.gather_ore()); // Mark each neighbor as unexplored for neighbor in neighbors { unexplored.insert(neighbor); } } current_state.ore_consumed } #[test] fn first_example() { let input = " 10 ORE => 10 A 1 ORE => 1 B 7 A, 1 B => 1 C 7 A, 1 C => 1 D 7 A, 1 D => 1 E 7 A, 1 E => 1 FUEL "; let reactions = parser::parse_reactions(input); // This one is small so Djkstra can actually solve it assert_eq!(dijkstra_solution(&reactions), 31); }
true
b4ba7bfbbe393f043bc5d55f758c901efa638ea3
Rust
alexey-mz/rust
/pascals-triangle/src/lib.rs
UTF-8
373
2.671875
3
[]
no_license
mod binom; use binom::binom::pascal_row; pub struct PascalsTriangle(Vec<Vec<u32>>); impl PascalsTriangle { pub fn new(row_count: u32) -> Self { let result = (0..row_count).into_iter().map(|x| pascal_row(x)).collect(); PascalsTriangle(result) } pub fn rows(&self) -> Vec<Vec<u32>> { let result = self.0.clone(); result } }
true
e54e0b00eefe535bd15bd7f4aaae9ccaa5e611c8
Rust
yomaytk/ruscaml
/src/lib.rs
UTF-8
3,421
2.65625
3
[]
no_license
use once_cell::sync::Lazy; use std::collections::HashMap; use std::env; use std::fs; use std::sync::Mutex; pub mod closure; pub mod codegen; pub mod flat; pub mod lexer; pub mod normal; pub mod parser; pub mod regalloc; pub mod vm; use lexer::*; type Id = String; type NV = normal::Value; type FV = flat::Value; pub static PROGRAM: Lazy<Mutex<String>> = Lazy::new(|| { let file: String = env::args().collect::<Vec<String>>().last().unwrap().clone(); Mutex::new(fs::read_to_string(file).expect("failed to read file.")) }); pub fn compile_error(tokenset: &TokenSet, message: &str) { let mut start: usize = 0; let mut end: usize = std::usize::MAX; for i in 0..std::usize::MAX { if tokenset.pos - i == 0 || tokenset.tokens[tokenset.pos - i].position.0 == true { start = tokenset.tokens[tokenset.pos - i].position.2; break; } } for i in 0..std::usize::MAX { if tokenset.pos + i == tokenset.tokens.len() - 1 { end = (*PROGRAM).lock().unwrap().len(); break; } if tokenset.tokens[tokenset.pos + i].position.0 == true { end = tokenset.tokens[tokenset.pos + i].position.2 - 1; break; } } println!( "Error: {} Line: {}.", message, tokenset.tokens[tokenset.pos].position.1 ); println!("\t{}", &(*PROGRAM).lock().unwrap()[start..end]); print!("\t"); for _ in 0..tokenset.tokens[tokenset.pos].position.2 - start { print!(" "); } println!("^"); } pub fn message_error(message: &str) { println!("Error: {}", message); } #[derive(Debug, Clone)] struct Env<T, V> { vals: HashMap<T, V>, prev: Option<Box<Env<T, V>>>, } impl<T: std::cmp::Eq + std::hash::Hash + std::fmt::Debug, V: std::fmt::Debug> Env<T, V> { fn new() -> Self { Self { vals: HashMap::new(), prev: None, } } fn inc(&mut self) { let curenv = std::mem::replace(self, Env::new()); *self = Self { vals: HashMap::new(), prev: Some(Box::new(curenv)), } } fn dec(&mut self) { let env = std::mem::replace(&mut (*self).prev, None); *self = *env.unwrap() } fn addval(&mut self, key: T, value: V) { self.vals.insert(key, value); } fn find(&self, key: &T) -> Option<&V> { let mut nenv = self; loop { if let Some(value) = nenv.vals.get(key) { return Some(value); } else { match nenv.prev { None => { message_error(&format!(" {:?} is not defined. ", key)); panic!("{:?}", &self); return None; } Some(ref next_env) => { nenv = next_env; } } } } } } impl Env<NV, FV> { fn efind(&self, key: &NV) -> FV { if let normal::Value::Intv(v) = key { return FV::Intv(*v); } self.find(key).unwrap().clone() } } impl Env<String, Vec<vm::Byte>> { fn is_dummy(&self) -> bool { let dm = self.find(&String::from("$$$dummy")).unwrap(); if dm.len() == 1 && dm[0] == -100 { return true; } else { panic!(" $$$dummy is not defined. ") } } }
true
99242e5e3186d0d70dc2ca568df13095358b7051
Rust
rustyforks/warden
/src/main.rs
UTF-8
893
2.640625
3
[ "MIT" ]
permissive
use axum::routing::get; use axum::{AddExtensionLayer, Json, Router}; use serde::Serialize; use warden::config::Config; use warden::state::State; #[tokio::main] async fn main() { let config = Config::new().expect("Failed to load values from config sources."); println!("{:#?}", config); let config = State::new(config); let app = Router::new() .route("/health", get(health_check)) .layer(AddExtensionLayer::new(config.clone())); println!("Starting server. Listening on {}", config.bind_address()); axum::Server::bind(&config.bind_address()) .serve(app.into_make_service()) .await .expect("Server failed to start."); } #[derive(Serialize)] pub struct HealthStatus { pub message: String, } pub async fn health_check() -> Json<HealthStatus> { Json::from(HealthStatus { message: "healthy".to_string(), }) }
true
fcd3b1cbad0d5b81ecd826dfdf0a9401aadc1c2c
Rust
j-carpentier/ALVR
/alvr/xtask/src/main.rs
UTF-8
2,626
2.953125
3
[ "MIT" ]
permissive
use alvr_xtask::*; use pico_args::Arguments; fn ok_or_exit<T, E: std::fmt::Display>(res: Result<T, E>) { use std::process::exit; if let Err(e) = res { #[cfg(not(windows))] { use termion::color::*; println!("\n{}Error: {}{}", Fg(Red), e, Fg(Reset)); } #[cfg(windows)] println!("{}", e); exit(1); } } fn print_help() { println!( r#" cargo xtask Developement actions for ALVR. USAGE: cargo xtask <SUBCOMMAND> [FLAG] SUBCOMMANDS: build-server Build server driver and GUI, then copy binaries to build folder build-client Build client, then copy binaries to build folder build-all 'build-server' + 'build-client' add-firewall-rules Add firewall rules for ALVR web server and SteamVR vrserver register-driver Register ALVR driver in SteamVR unregister-all Unregister all SteamVR drivers (including non ALVR) clean Removes build folder kill-oculus Kill all Oculus processes FLAGS: --release Optimized build without debug info. Used only for build subcommands --help Print this text "# ); } fn main() { let mut args = Arguments::from_env(); if args.contains(["-h", "--help"]) { print_help(); } else if let Ok(Some(subcommand)) = args.subcommand() { let is_release = args.contains("--release"); if args.finish().is_ok() { match subcommand.as_str() { "build-server" => ok_or_exit(build_server(is_release)), "build-client" => ok_or_exit(build_client(is_release)), "build-all" => { ok_or_exit(build_server(is_release)); ok_or_exit(build_client(is_release)); } "add-firewall-rules" => ok_or_exit(firewall_rules(&server_build_dir(), true)), "register-driver" => ok_or_exit(driver_registration(&server_build_dir(), true)), "unregister-all" => ok_or_exit(unregister_all_drivers()), "clean" => remove_build_dir(), "kill-oculus" => kill_oculus_processes(), _ => { println!("\nUnrecognized subcommand."); print_help(); return; } } } else { println!("\nWrong arguments."); print_help(); return; } } else { println!("\nMissing subcommand."); print_help(); return; } println!("\nDone\n"); }
true
9682151b8339d91d54ce000584c5ed3416a5132e
Rust
forgerpl/hyena-edge
/hyena-engine/src/storage/memory.rs
UTF-8
5,819
3.015625
3
[ "Apache-2.0" ]
permissive
use super::{ByteStorage, Realloc, Storage}; use crate::error::*; use hyena_common::map_type::{map_type, map_type_mut}; use std::fmt; use std::fmt::Debug; use std::intrinsics::copy_nonoverlapping; use std::marker::PhantomData; use std::mem::{size_of, zeroed, MaybeUninit}; const PAGE_SIZE: usize = 1 << 12; #[derive(Debug, Clone, PartialEq, Default)] pub struct MemoryStorage<Align: Zero + Clone> { data: Vec<Align>, } impl<Align: Zero + Debug + Copy + Clone + PartialEq> MemoryStorage<Align> { pub fn new(size: usize) -> Result<MemoryStorage<Align>> { assert_eq!(size % size_of::<Align>(), 0); Ok(MemoryStorage { data: vec![Align::zero(); size / size_of::<Align>()], }) } pub fn len(&self) -> usize { self.data.len() * size_of::<Align>() } pub fn is_empty(&self) -> bool { self.data.is_empty() } } impl<'stor, T: 'stor, Align: Zero + Debug + Copy + Clone + PartialEq> Storage<'stor, T> for MemoryStorage<Align> { fn sync(&mut self) -> Result<()> { Ok(()) } } impl<'stor, Align: Zero + Debug + Copy + Clone + PartialEq> ByteStorage<'stor> for MemoryStorage<Align> { } impl<T, Align: Zero + Debug + Copy + Clone + PartialEq> AsRef<[T]> for MemoryStorage<Align> { fn as_ref(&self) -> &[T] { map_type(&self.data, PhantomData) } } impl<T, Align: Zero + Debug + Copy + Clone + PartialEq> AsMut<[T]> for MemoryStorage<Align> { fn as_mut(&mut self) -> &mut [T] { map_type_mut(&mut self.data, PhantomData) } } impl<Align: Zero + Debug + Copy + Clone + PartialEq> Realloc for MemoryStorage<Align> { fn realloc(self, size: usize) -> Result<Self> { let mut new_storage = Self::new(size)?; let copy_size = ::std::cmp::min(size, self.realloc_size()); new_storage.as_mut()[..copy_size] .copy_from_slice(&<MemoryStorage<Align> as AsRef<[u8]>>::as_ref(&self)[..copy_size]); Ok(new_storage) } fn realloc_size(&self) -> usize { <Self as ByteStorage>::size(self) } } pub trait Zero { fn zero() -> Self; } macro_rules! auto_impl_zero { ($($t: ty),*) => { $(impl Zero for $t { fn zero() -> $t { 0 } })* }; } auto_impl_zero!(u8, u16, u32, u64); impl Zero for Page { fn zero() -> Page { Page([0; size_of::<Page>()]) } } #[derive(Copy)] pub struct Page([u8; PAGE_SIZE]); impl fmt::Debug for Page { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_list().entries(self.0.iter()).finish() } } impl Clone for Page { fn clone(&self) -> Page { unsafe { let mut dst = MaybeUninit::<Page>::uninit(); copy_nonoverlapping(self, dst.as_mut_ptr(), 1); dst.assume_init() } } } impl Default for Page { fn default() -> Page { unsafe { zeroed() } } } impl PartialEq<Page> for Page { #[inline] fn eq(&self, other: &Page) -> bool { self.0[..] == other.0[..] } #[inline] fn ne(&self, other: &Page) -> bool { self.0[..] != other.0[..] } } pub type PagedMemoryStorage = MemoryStorage<Page>; #[cfg(test)] mod tests { use super::*; const TEST_BYTES_LEN: usize = 10; static TEST_BYTES: [u8; TEST_BYTES_LEN] = *b"hyena test"; const BLOCK_SIZE: usize = 1 << 20; // 1 MiB fn create_block() -> PagedMemoryStorage { PagedMemoryStorage::new(BLOCK_SIZE) .with_context(|_| "failed to create PagedMemoryStorage") .unwrap() } mod align { use super::*; fn deref_aligned<T, M: AsRef<[T]>>(storage: &M) -> &[T] { storage.as_ref() } #[allow(non_snake_case)] fn as_T<T>() { deref_aligned::<T, _>(&create_block()); } #[test] fn as_u8() { as_T::<u8>() } #[test] fn as_u16() { as_T::<u16>() } #[test] fn as_u32() { as_T::<u32>() } #[test] fn as_u64() { as_T::<u64>() } } #[test] fn it_can_write() { let mut storage = create_block(); &storage.as_mut()[..TEST_BYTES_LEN].copy_from_slice(&TEST_BYTES[..]); assert_eq!( &<PagedMemoryStorage as AsRef<[u8]>>::as_ref(&storage)[..TEST_BYTES_LEN], &TEST_BYTES[..] ); assert_eq!( <PagedMemoryStorage as AsRef<[u8]>>::as_ref(&storage)[..].len(), BLOCK_SIZE ); } #[test] fn it_shrinks_block() { let storage = create_block(); let mut storage = storage .realloc(BLOCK_SIZE / 2) .with_context(|_| "failed to shrink PagedMemoryStorage") .unwrap(); &storage.as_mut()[..TEST_BYTES_LEN].copy_from_slice(&TEST_BYTES[..]); assert_eq!( &<PagedMemoryStorage as AsRef<[u8]>>::as_ref(&storage)[..TEST_BYTES_LEN], &TEST_BYTES[..] ); assert_eq!( <PagedMemoryStorage as AsRef<[u8]>>::as_ref(&storage)[..].len(), BLOCK_SIZE / 2 ); } #[test] fn it_grows_block() { let storage = create_block(); let mut storage = storage .realloc(BLOCK_SIZE * 2) .with_context(|_| "failed to shrink PagedMemoryStorage") .unwrap(); &storage.as_mut()[..TEST_BYTES_LEN].copy_from_slice(&TEST_BYTES[..]); assert_eq!( &<PagedMemoryStorage as AsRef<[u8]>>::as_ref(&storage)[..TEST_BYTES_LEN], &TEST_BYTES[..] ); assert_eq!( <PagedMemoryStorage as AsRef<[u8]>>::as_ref(&storage)[..].len(), BLOCK_SIZE * 2 ); } }
true
cd1582309453455382767524057c2618298cfaa2
Rust
schizobulia/ave
/ave-video/src/page/home.rs
UTF-8
5,499
2.59375
3
[]
no_license
use crate::app::app_message::Message; use crate::app::state::home::HomeState; use crate::gstr; use crate::model::receive_msg::ReceiveMsg; use crate::model::vide_type::VideoContainerType; use ave_tool::file_tool::{get_filename, mkdir}; use iced::{ Align, Button, Column, Command, Container, Length, PickList, Row, Scrollable, Slider, Text, }; use iced_style::{button_style, container_style, pick_list_style, scrollable_style}; use std::path::PathBuf; //首页 pub fn render(home_state: &mut HomeState) -> Column<Message> { let pick_list = PickList::new( &mut home_state.pick_list, &VideoContainerType::ALL[..], Some(home_state.select_video_type), Message::LanguageSelected, ) .style(pick_list_style::PickList); Column::new() .spacing(15) .push( Column::new() .padding(5) .spacing(10) .push( Text::new( "请先选择需要最终转换的格式,然后选择文件,\ 软件会自动开始转换", ) .size(18), ) .push( Row::new() .padding(3) .align_items(Align::Center) .push(Text::new("压缩质量:").size(15)) .push( Slider::new( &mut home_state.quality_progress, 10.0..=1000.0, home_state.quality_val, Message::VideoQualityChanged, ) .step(1.00), ), ) .push( Row::new() .padding(3) .align_items(Align::Center) .push(Text::new("生成格式:").size(15)) .push(pick_list), ) .push( Row::new() .spacing(10) .align_items(Align::Center) .push( Button::new(&mut home_state.file_home_btn, Text::new("选择文件")) .padding(5) .style(button_style::Button::Primary) .on_press(Message::FileSelected), ) .push(Text::new(&home_state.create_video_path).size(18)), ), ) .push( Container::new( Scrollable::new(&mut home_state.scroll_comd_state) .padding(10) .width(Length::Fill) .height(Length::Fill) .style(scrollable_style::Scrollable) .push(Text::new(&home_state.msg_conversion_statue).size(16)), ) .height(Length::Units(500)) .height(Length::Fill) .style(container_style::Container::default()), ) } pub fn get_command( home_state: &mut HomeState, t_path: String, file_list: Vec<PathBuf>, ) -> Vec<Command<Message>> { let select_type = home_state.select_video_type; let quality_val = home_state.quality_val; let mut com_arr: Vec<Command<Message>> = Vec::new(); let mut index = 1; for file in file_list { let tmp_type = select_type.clone(); let filename = file.file_name().unwrap().to_string_lossy(); let create_path = get_create_path( t_path.clone(), home_state.select_video_type, filename.to_string(), ); com_arr.push(Command::perform( formatting_video(tmp_type, file.clone(), create_path, index, quality_val), Message::ReceiveMsg, )); index += 1; let old_msg = &home_state.msg_conversion_statue; home_state.msg_conversion_statue = format!( "{}{} 转换中...\r\n\ ", old_msg, filename ); } com_arr } //转换视频格式 async fn formatting_video( tmp_type: VideoContainerType, file: PathBuf, t_path: String, index: i32, quality_val: f32, ) -> ReceiveMsg { let filename: String = file.to_string_lossy().to_string(); let old_file_name = &get_filename(filename.clone()); let result = gstr::conversion::conversion_video( file.to_string_lossy().to_string().as_str(), format!( "{}//{}-{}.{}", t_path, old_file_name, index, tmp_type.to_string() ) .as_str(), quality_val as i32, tmp_type, ); let res: ReceiveMsg; if result.is_ok() { res = ReceiveMsg::new(filename, String::from("转换成功")); } else { res = ReceiveMsg::new(filename, String::from("转换失败")); } res } //对特殊视频格式做处理 //生成m3u8视频时 单独给每个视频创建文件夹 fn get_create_path(t_path: String, video_type: VideoContainerType, filename: String) -> String { match video_type { VideoContainerType::M3u8 => { let mut m3u8_dir = t_path.clone(); m3u8_dir.push_str("/"); m3u8_dir.push_str(filename.as_str()); mkdir(m3u8_dir) } _ => t_path, } }
true
bb363b1c3d5eec1533f90d888587f9be6bf3776d
Rust
kazyamaz200/bibi-zip-loader
/wasm/src/utils.rs
UTF-8
1,254
2.640625
3
[ "MIT" ]
permissive
use wasm_bindgen::prelude::*; pub fn set_panic_hook() { // When the `console_error_panic_hook` feature is enabled, we can call the // `set_panic_hook` function at least once during initialization, and then // we will get better error messages if our code ever panics. // // For more details see // https://github.com/rustwasm/console_error_panic_hook#readme #[cfg(feature = "console_error_panic_hook")] console_error_panic_hook::set_once(); } #[wasm_bindgen] extern { // Use `js_namespace` here to bind `console.log(..)` instead of just // `log(..)` #[wasm_bindgen(js_namespace = console)] pub fn log(s: &str); // The `console.log` is quite polymorphic, so we can bind it with multiple // signatures. Note that we need to use `js_name` to ensure we always call // `log` in JS. #[wasm_bindgen(js_namespace = console, js_name = log)] pub fn log_u32(a: u32); // Multiple arguments too! #[wasm_bindgen(js_namespace = console, js_name = log)] pub fn log_many(a: &str, b: &str); } macro_rules! console_log { // Note that this is using the `log` function imported above during // `bare_bones` ($($t:tt)*) => (crate::utils::log(&format_args!($($t)*).to_string())) }
true
ce2dfa97e4e5beb28df06be563ebb5258a0bd84d
Rust
wotsushi/competitive-programming
/etc/ttpc2019/c.rs
UTF-8
1,902
2.9375
3
[ "MIT" ]
permissive
#![allow(non_snake_case)] #![allow(unused_variables)] #![allow(dead_code)] fn main() { let (N, X): (usize, i64) = { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap() ) }; let a: Vec<i64> = { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|x| x.parse().unwrap()) .collect() }; let m = a.iter().filter(|&&b| b == -1).count(); let Y = a.iter().filter(|&&b| b >= 0).fold(0, |acc, &b| acc ^ b); let ans = if m >= 2 { let k = format!("{:b}", X).chars().count(); let l = format!("{:b}", Y).chars().count(); let i = (0..N).find(|&j| a[j] == -1).unwrap(); if k > l { let i2 = ((i + 1)..N).find(|&j| a[j] == -1).unwrap(); (0..N).map(|j| if a[j] >= 0 { a[j] } else if j == i { 1 << (k - 1) } else if j == i2 { (X ^ Y) - (1 << (k - 1)) } else { 0 }.to_string() ).collect::<Vec<_>>().join(" ") } else if k == l { (0..N).map(|j| if a[j] >= 0 { a[j] } else if j == i { X ^ Y } else { 0 }.to_string() ).collect::<Vec<_>>().join(" ") } else { "-1".to_string() } } else if m == 1 { if X ^ Y <= X { a.iter().map(|&b| if b >= 0 { b } else { X ^ Y }.to_string()).collect::<Vec<_>>().join(" ") } else { "-1".to_string() } } else { if X == Y { a.iter().map(std::string::ToString::to_string).collect::<Vec<_>>().join(" ") } else { "-1".to_string() } }; println!("{}", ans); }
true
118d759e339248f5772b3c7e4f6e34de8ae57212
Rust
IThawk/rust-project
/rust-master/src/test/ui/not-sync.rs
UTF-8
826
2.65625
3
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
use std::cell::{Cell, RefCell}; use std::rc::{Rc, Weak}; use std::sync::mpsc::{Receiver, Sender}; fn test<T: Sync>() {} fn main() { test::<Cell<i32>>(); //~^ ERROR `std::cell::Cell<i32>` cannot be shared between threads safely [E0277] test::<RefCell<i32>>(); //~^ ERROR `std::cell::RefCell<i32>` cannot be shared between threads safely [E0277] test::<Rc<i32>>(); //~^ ERROR `std::rc::Rc<i32>` cannot be shared between threads safely [E0277] test::<Weak<i32>>(); //~^ ERROR `std::rc::Weak<i32>` cannot be shared between threads safely [E0277] test::<Receiver<i32>>(); //~^ ERROR `std::sync::mpsc::Receiver<i32>` cannot be shared between threads safely [E0277] test::<Sender<i32>>(); //~^ ERROR `std::sync::mpsc::Sender<i32>` cannot be shared between threads safely [E0277] }
true
cfd4bbad4f7804387e872985ee9350401c09573d
Rust
yiransheng/relooper
/src/types.rs
UTF-8
4,899
3.171875
3
[]
no_license
use std::marker::PhantomData; use fixedbitset::FixedBitSet; use petgraph::graph::{DiGraph, IndexType, NodeIndex}; pub type DefaultIndex = u32; /// Id for shapes (loops and switches). #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct ShapeId<Ix = DefaultIndex>(Ix); #[derive(Default)] pub struct ShapeIdGen { counter: usize, } impl ShapeIdGen { pub fn next_shape_id(&mut self) -> ShapeId { let sid = ShapeId::new(self.counter); self.counter += 1; sid } } impl<Ix: IndexType> ShapeId<Ix> { /// Get a `usize` out of `ShapeId`. Which can be formatted into `loop` labels for example, /// depending on exact use case. #[inline] pub fn index(&self) -> usize { self.0.index() } #[inline] fn new(index: usize) -> Self { ShapeId(Ix::new(index)) } } pub type CFGraph<L, C> = DiGraph<Block<L>, Branch<C>, DefaultIndex>; /// Type alias for [`Relooper`](../struct.Relooper.html)'s internal block id. To get a `usize` out /// of it for formatting or AST construction, call `.index()` method on it. /// /// This type is based on /// [`NodeIndex`](https://docs.rs/petgraph/0.4.13/petgraph/graph/struct.NodeIndex.html) `struct`. pub type BlockId = NodeIndex<DefaultIndex>; #[derive(Debug, Clone)] pub struct BlockSet<Ix = BlockId> { inner: FixedBitSet, _idx_ty: PhantomData<Ix>, } impl<Ix: IndexType> BlockSet<NodeIndex<Ix>> { pub fn new_empty(size: usize) -> Self { BlockSet { inner: FixedBitSet::with_capacity(size), _idx_ty: PhantomData, } } // panics if index out of bound #[inline] pub fn insert(&mut self, idx: NodeIndex<Ix>) -> bool { self.inner.put(idx.index()) } pub fn extend<I>(&mut self, idx: I) where I: IntoIterator<Item = NodeIndex<Ix>>, { for i in idx { self.insert(i); } } // panics if index out of bound #[inline] pub fn remove(&mut self, idx: NodeIndex<Ix>) { self.inner.set(idx.index(), false) } #[inline] pub fn clear(&mut self) { self.inner.clear(); } pub fn contains(&self, idx: NodeIndex<Ix>) -> bool { self.inner[idx.index()] } #[inline] pub fn sample_one(&self) -> Option<NodeIndex<Ix>> { self.inner.ones().next().map(NodeIndex::new) } #[inline] pub fn take_one(&mut self) -> Option<NodeIndex<Ix>> { if let Some(i) = self.inner.ones().next() { self.inner.set(i, false); Some(NodeIndex::new(i)) } else { None } } #[inline] pub fn len(&self) -> usize { self.inner.count_ones(..) } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn iter<'a>(&'a self) -> impl Iterator<Item = NodeIndex<Ix>> + 'a { self.inner.ones().map(NodeIndex::new) } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum FlowType { Direct, Break, Continue, } // All branches in input CFG will eventually be registered to // some Simple shape pub enum Branch<C> { // a branch has been registered to a leaf(simple) shape Registered, // unprocessed branch, with optional condition of type C Raw(Option<C>), // processed branch with known ancestor (loop/simple/multi) // but not yet registered to a simple shape Processed(ProcessedBranch<C>), } impl<C> Branch<C> { pub fn take(&mut self) -> Option<ProcessedBranch<C>> { let b = ::std::mem::replace(self, Branch::Registered); if let Branch::Processed(b) = b { Some(b) } else { *self = b; None } } pub fn solipsize( &mut self, target: BlockId, flow_type: FlowType, ancestor: ShapeId, ) { let b = ::std::mem::replace(self, Branch::Registered); if let Branch::Raw(data) = b { let processed = ProcessedBranch { data, flow_type, ancestor, target, target_entry_type: EntryType::Checked, }; *self = Branch::Processed(processed); } else { *self = b; } } } #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum EntryType { Checked, Direct, } #[derive(Debug)] pub struct ProcessedBranch<C> { pub data: Option<C>, pub flow_type: FlowType, pub ancestor: ShapeId, pub target: BlockId, pub target_entry_type: EntryType, } pub enum Block<L> { Raw(L), // has registered to a simple shape Registered, } impl<L> Block<L> { pub fn take(&mut self) -> Option<L> { let b = ::std::mem::replace(self, Block::Registered); if let Block::Raw(b) = b { Some(b) } else { *self = b; None } } }
true
f58122cac84cfb0172ff9cc491bc44a30278e733
Rust
stm32-rs/stm32g4xx-hal
/src/dma/config.rs
UTF-8
2,957
3.53125
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
use super::Bits; /// Priority of the DMA stream, defaults to `Medium`. If two requests have /// the same software priority level, the stream with the lower number takes /// priority over the stream with the higher number. For example, Stream 2 /// takes priority over Stream 4. #[derive(Debug, Clone, Copy)] pub enum Priority { /// Low priority. Low, /// Medium priority. Medium, /// High priority. High, /// Very high priority. VeryHigh, } impl Default for Priority { fn default() -> Self { Priority::Medium } } impl Bits<u8> for Priority { fn bits(self) -> u8 { match self { Priority::Low => 0, Priority::Medium => 1, Priority::High => 2, Priority::VeryHigh => 3, } } } /// Contains the complete set of configuration for a DMA stream. #[derive(Debug, Default, Clone, Copy)] pub struct DmaConfig { pub(crate) priority: Priority, pub(crate) memory_increment: bool, pub(crate) peripheral_increment: bool, pub(crate) circular_buffer: bool, pub(crate) transfer_complete_interrupt: bool, pub(crate) half_transfer_interrupt: bool, pub(crate) transfer_error_interrupt: bool, pub(crate) double_buffer: bool, } impl DmaConfig { /// Set the priority. #[inline(always)] pub fn priority(mut self, priority: Priority) -> Self { self.priority = priority; self } /// Set the memory_increment. #[inline(always)] pub fn memory_increment(mut self, memory_increment: bool) -> Self { self.memory_increment = memory_increment; self } /// Set the peripheral_increment. #[inline(always)] pub fn peripheral_increment(mut self, peripheral_increment: bool) -> Self { self.peripheral_increment = peripheral_increment; self } /// Set the to use a circular_buffer. #[inline(always)] pub fn circular_buffer(mut self, circular_buffer: bool) -> Self { self.circular_buffer = circular_buffer; self } /// Set the transfer_complete_interrupt. #[inline(always)] pub fn transfer_complete_interrupt(mut self, transfer_complete_interrupt: bool) -> Self { self.transfer_complete_interrupt = transfer_complete_interrupt; self } /// Set the half_transfer_interrupt. #[inline(always)] pub fn half_transfer_interrupt(mut self, half_transfer_interrupt: bool) -> Self { self.half_transfer_interrupt = half_transfer_interrupt; self } /// Set the transfer_error_interrupt. #[inline(always)] pub fn transfer_error_interrupt(mut self, transfer_error_interrupt: bool) -> Self { self.transfer_error_interrupt = transfer_error_interrupt; self } /// Set the double_buffer. #[inline(always)] pub fn double_buffer(mut self, double_buffer: bool) -> Self { self.double_buffer = double_buffer; self } }
true
e15d8fe5d98c4e239542189e2cdd4487bcef07c3
Rust
Afterglow/aoc-2020
/day2-1/src/main.rs
UTF-8
999
3
3
[]
no_license
use regex::Regex; fn main() { let mut ok: usize = 0; let file = std::fs::read_to_string("input.txt").unwrap(); // 6-10 g: rhtwpsxrzgpgxhk let re = Regex::new(r"^(?P<from>[0-9]+)-(?P<to>[0-9]+) (?P<needle>\w): (?P<haystack>\S+)$") .unwrap(); for line in file.lines() { let captures = match re.captures(line) { Some(captures) => captures, None => { panic!("No match found for regex in '{}'", line) } }; let from: usize = captures.name("from").unwrap().as_str().parse().unwrap(); let to: usize = captures.name("to").unwrap().as_str().parse().unwrap(); let needle: char = captures.name("needle").unwrap().as_str().parse().unwrap(); let haystack = captures.name("haystack").unwrap().as_str(); let count = haystack.matches(needle).count(); if count >= from && count <= to { ok += 1; } } println!("Found {} matches", ok); }
true
3622ce9c0eec799f37eb1054bd9e99a63d74b1fa
Rust
lin20121221/Yazz
/src/ctrl_map.rs
UTF-8
10,286
3.203125
3
[ "MIT" ]
permissive
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self, set: usize, controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if !self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative => { // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); } MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn add_controller(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
true
eb1a21776b7683ff71ad472ffec89ff7705d7b85
Rust
nicooffee/map-app
/map-app/src/engine/engine.rs
UTF-8
4,569
2.84375
3
[]
no_license
use std::{ io::Stdout, io::stdout, io::Write, thread, time, sync::{Arc, Mutex, mpsc::*} }; use termion::{ input::TermRead, event::Key, color, async_stdin, raw::RawTerminal, raw::IntoRawMode, screen::AlternateScreen }; use super::window::screen::{ Screen, Panel, TextLine }; use super::structure::map::Map; use super::structure::direction::Dir; use super::structure::character::Character; use crate::engine::traits::printable::Printable; const DELAY: u64 = 10000; pub fn new() -> (Screen<RawTerminal<Stdout>>,Map) { let s_bg = color::Rgb(0,51,51); let s = Screen::new(AlternateScreen::from(stdout().into_raw_mode().unwrap()),s_bg, 20); let (main_w,main_h) = s.get_sizes(Panel::Main); let m = Map::new((main_w/2,main_w),(main_h/2,main_h)); (s,m) } pub fn run(screen: Screen<RawTerminal<Stdout>>,map: Map) { let (tx_character,rx_character) = channel(); //let (tx_info,rx_info) = channel(); let (tx_exit_main,rx_exit_main) = channel(); let (tx_exit_info,rx_exit_info) = channel(); let (tx_exit_char,rx_exit_char) = channel(); let send_closure = move || { tx_exit_main.send(true).unwrap(); tx_exit_info.send(true).unwrap(); tx_exit_char.send(true).unwrap(); }; let map = Arc::new(Mutex::new(map)); let screen = Arc::new(Mutex::new(screen)); let cl_map_1 = Arc::clone(&map); let cl_map_2 = Arc::clone(&map); let thr_stdin = thread::spawn(move || {run_stdin(tx_character,send_closure)}); let thr_main = thread::spawn(move || { let cl_screen = Arc::clone(&screen); run_main(rx_exit_main,cl_screen,cl_map_1); }); let thr_char = thread::spawn(move ||{ run_character(rx_exit_char,cl_map_2,rx_character); }); thr_stdin.join().unwrap(); thr_main.join().unwrap(); thr_char.join().unwrap(); } fn run_stdin<T: Fn() -> ()>( tx_character: Sender<Dir>, tx_exit: T ){ let stdin = async_stdin(); let mut it = stdin.keys(); loop { let b = it.next(); if let Some(event) = b { match event.unwrap() { Key::Char('q') => { tx_exit(); break; }, Key::Up => tx_character.send(Dir::Up).unwrap(), Key::Down => tx_character.send(Dir::Down).unwrap(), Key::Left => tx_character.send(Dir::Left).unwrap(), Key::Right => tx_character.send(Dir::Right).unwrap(), _ => {} } } thread::sleep(time::Duration::from_micros(DELAY/2)); } } fn run_info(){ } fn run_main( rx_exit: Receiver<bool>, screen: Arc<Mutex<Screen<RawTerminal<Stdout>>>>, map: Arc<Mutex<Map>> ){ let bg_default: color::Rgb; { let mut screen = screen.lock().unwrap(); screen.initialize(); screen.write_menu(TextLine::TITLE,"hola mundo"); let map = map.lock().unwrap(); bg_default = map.current_scenario().background_color(); screen.write_printable(map.current_scenario(),bg_default); screen.flush().unwrap(); } loop{ { let mut screen = screen.lock().unwrap(); { //Fix this screen.write_printable(map.lock().unwrap().character(),bg_default); } screen.flush().unwrap(); } if let Ok(_) = rx_exit.try_recv(){break;}; thread::sleep(time::Duration::from_micros(DELAY)); } } fn run_character( rx_exit: Receiver<bool>, map: Arc<Mutex<Map>>, rx_character: Receiver<Dir> ){ loop { { let mut map = map.lock().unwrap(); if let Ok(dir) = rx_character.try_recv(){ map.move_chr(dir); } } thread::sleep(time::Duration::from_micros(DELAY)); if let Ok(_) = rx_exit.try_recv(){break;}; } } /*try_recv loop { { let mut character = character.lock().unwrap(); if let Ok(dir) = rx_character.try_recv(){ character.move_chr(dir); } } thread::sleep(time::Duration::from_micros(DELAY)); if let Ok(_) = rx_exit.try_recv(){break;}; } */ /*recv loop { let dir = rx_character.recv().unwrap(); { let mut character = character.lock().unwrap(); character.move_chr(dir); } thread::sleep(time::Duration::from_micros(DELAY)); if let Ok(_) = rx_exit.try_recv(){break;}; } */
true
0edc369c6e64ac7ff0e2034233f8f8b3f54bea1c
Rust
utilForever/BOJ
/Rust/10632 - Unfair Game.rs
UTF-8
2,550
3.3125
3
[ "MIT" ]
permissive
use io::Write; use std::{cmp, io, str}; pub struct UnsafeScanner<R> { reader: R, buf_str: Vec<u8>, buf_iter: str::SplitAsciiWhitespace<'static>, } impl<R: io::BufRead> UnsafeScanner<R> { pub fn new(reader: R) -> Self { Self { reader, buf_str: vec![], buf_iter: "".split_ascii_whitespace(), } } pub fn token<T: str::FromStr>(&mut self) -> T { loop { if let Some(token) = self.buf_iter.next() { return token.parse().ok().expect("Failed parse"); } self.buf_str.clear(); self.reader .read_until(b'\n', &mut self.buf_str) .expect("Failed read"); self.buf_iter = unsafe { let slice = str::from_utf8_unchecked(&self.buf_str); std::mem::transmute(slice.split_ascii_whitespace()) } } } } fn main() { let (stdin, stdout) = (io::stdin(), io::stdout()); let mut scan = UnsafeScanner::new(stdin.lock()); let mut out = io::BufWriter::new(stdout.lock()); let (n, a, b) = ( scan.token::<usize>(), scan.token::<usize>(), scan.token::<usize>(), ); let mut stones = vec![0; n]; for i in 0..n { stones[i] = scan.token::<usize>(); } let min = cmp::min(a, b); let mut grundy = 0; let mut num_exceed_heaps = 0; for i in 0..n { grundy ^= stones[i] % (min + 1); if stones[i] > min { num_exceed_heaps += 1; } } if num_exceed_heaps == 0 || a == b { // Case 1: If each of heaps is less than min(a, b) or a == b, then the answer is the grundy number. writeln!(out, "{}", if grundy > 0 { "Hanako" } else { "Jiro" }).unwrap(); } else if a > b { // Case 2: If a > b and there are heaps that are greater than min(a, b), then the answer is Petyr. writeln!(out, "Hanako").unwrap(); } else { // Case 3: If a < b and there are heaps that are greater than min(a, b), then calculate the next situation. let max_stone = stones.iter().max().unwrap(); let next_grundy = grundy ^ (max_stone % (a + 1)); let remain = (((max_stone - next_grundy) % (a + 1)) + a + 1) % (a + 1); if (remain == 0 || remain > a || max_stone - remain > a) || (next_grundy != (max_stone - remain) % (a + 1)) { writeln!(out, "Jiro").unwrap(); } else { writeln!(out, "Hanako").unwrap(); } } }
true
ee6b7b0aba236600963051f2a0daec793d1457a4
Rust
LPGhatguy/aoc2018
/day-01/src/main.rs
UTF-8
787
3.140625
3
[]
no_license
use std::collections::HashSet; static INPUT: &str = include_str!("../input.txt"); fn part_one() { let result: i32 = INPUT .lines() .map(str::trim_right) .map(|v| v.parse::<i32>().unwrap()) .sum(); println!("part one: {:?}", result); } fn part_two() { let changes = INPUT .lines() .map(str::trim_right) .map(|v| v.parse::<i32>().unwrap()) .cycle(); let mut frequency = 0; let mut seen_frequencies = HashSet::new(); seen_frequencies.insert(frequency); for change in changes { frequency += change; if !seen_frequencies.insert(frequency) { println!("part two: {:?}", frequency); break; } } } fn main() { part_one(); part_two(); }
true
8d1123bb288701428c8ab1e5c345dfac6980d308
Rust
rome/tools
/crates/rome_js_formatter/src/js/any/declaration.rs
UTF-8
1,392
2.625
3
[ "MIT" ]
permissive
//! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file. use crate::prelude::*; use rome_js_syntax::AnyJsDeclaration; #[derive(Debug, Clone, Default)] pub(crate) struct FormatAnyJsDeclaration; impl FormatRule<AnyJsDeclaration> for FormatAnyJsDeclaration { type Context = JsFormatContext; fn fmt(&self, node: &AnyJsDeclaration, f: &mut JsFormatter) -> FormatResult<()> { match node { AnyJsDeclaration::JsClassDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::JsFunctionDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::JsVariableDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::TsEnumDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::TsTypeAliasDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::TsInterfaceDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::TsDeclareFunctionDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::TsModuleDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::TsExternalModuleDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::TsGlobalDeclaration(node) => node.format().fmt(f), AnyJsDeclaration::TsImportEqualsDeclaration(node) => node.format().fmt(f), } } }
true
14e3f17ddbfb62a8b61ca2e7ebc96b7e7d31f0bb
Rust
stanxii/vidl-rs
/src/youtube.rs
UTF-8
10,644
2.5625
3
[ "Unlicense" ]
permissive
use anyhow::{Context, Result}; use chrono::offset::TimeZone; use log::{debug, trace}; use crate::common::{Service, YoutubeID}; fn api_prefix() -> String { #[cfg(test)] let prefix: &str = &mockito::server_url(); #[cfg(not(test))] let prefix: &str = "https://invidio.us"; prefix.into() } /* [ { title: String, videoId: String, author: String, authorId: String, authorUrl: String, videoThumbnails: [ { quality: String, url: String, width: Int32, height: Int32 } ], description: String, descriptionHtml: String, viewCount: Int64, published: Int64, publishedText: String, lengthSeconds: Int32 paid: Bool, premium: Bool } ] */ #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] struct YTVideoInfo { title: String, video_id: String, video_thumbnails: Vec<YTThumbnailInfo>, description: String, length_seconds: i32, paid: bool, premium: bool, published: i64, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] struct YTThumbnailInfo { quality: Option<String>, url: String, width: i32, height: i32, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] struct YTChannelInfo { author: String, author_id: String, description: String, author_thumbnails: Vec<YTThumbnailInfo>, author_banners: Vec<YTThumbnailInfo>, } /// Important info about channel #[derive(Debug)] pub struct ChannelMetadata { pub title: String, pub thumbnail: String, pub description: String, } /// Important info about a video pub struct VideoInfo { pub id: String, pub url: String, pub title: String, pub description: String, pub thumbnail_url: String, pub published_at: chrono::DateTime<chrono::Utc>, } impl std::fmt::Debug for VideoInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "VideoInfo{{id: {:?}, title: {:?}, url: {:?}, published_at: {:?}}}", self.id, self.title, self.url, self.published_at, ) } } fn request_data<T: serde::de::DeserializeOwned + std::fmt::Debug>(url: &str) -> Result<T> { fn subreq<T: serde::de::DeserializeOwned + std::fmt::Debug>(url: &str) -> Result<T> { debug!("Retrieving URL {}", &url); let resp = attohttpc::get(&url).send()?; let text = resp.text()?; trace!("Raw response: {}", &text); let data: T = serde_json::from_str(&text) .with_context(|| format!("Failed to parse response from {}", &url))?; trace!("Raw deserialisation: {:?}", &data); Ok(data) } let mut tries = 0; let ret: Result<T> = loop { let resp = subreq(url); if let Ok(data) = resp { break Ok(data); } debug!("Retrying request to {} because {:?}", &url, &resp); if tries > 3 { break resp; } tries += 1; }; ret } /// Object to query data about given channel #[derive(Debug)] pub struct YoutubeQuery<'a> { chan_id: &'a YoutubeID, } impl<'a> YoutubeQuery<'a> { pub fn new(chan_id: &YoutubeID) -> YoutubeQuery { YoutubeQuery { chan_id } } pub fn get_metadata(&self) -> Result<ChannelMetadata> { let url = format!( "{prefix}/api/v1/channels/{chanid}", prefix = api_prefix(), chanid = self.chan_id.id ); let d: YTChannelInfo = request_data(&url)?; Ok(ChannelMetadata { title: d.author.clone(), thumbnail: d.author_thumbnails[0].url.clone(), description: d.description.clone(), }) } pub fn videos<'i>(&'i self) -> impl Iterator<Item = Result<VideoInfo>> + 'i { // GET /api/v1/channels/:ucid/videos?page=1 fn get_page(chanid: &str, page: i32) -> Result<Vec<VideoInfo>> { let url = format!( "{prefix}/api/v1/channels/videos/{chanid}?page={page}", prefix = api_prefix(), chanid = chanid, page = page, ); let data: Vec<YTVideoInfo> = request_data(&url)?; let ret: Vec<VideoInfo> = data .iter() .map(|d| VideoInfo { id: d.video_id.clone(), url: format!("http://youtube.com/watch?v={id}", id = d.video_id), title: d.title.clone(), description: d.description.clone(), thumbnail_url: d.video_thumbnails.first().unwrap().url.clone(), published_at: chrono::Utc.timestamp(d.published, 0), }) .collect(); Ok(ret) } let mut page_num = 1; use std::collections::VecDeque; let mut completed = false; let mut current_items: VecDeque<VideoInfo> = VecDeque::new(); let it = std::iter::from_fn(move || -> Option<Result<VideoInfo>> { if completed { return None; } if let Some(cur) = current_items.pop_front() { // Iterate through previously stored items Some(Ok(cur)) } else { // If nothing is stored, get next page of videos let data: Result<Vec<VideoInfo>> = get_page(&self.chan_id.id, page_num); page_num += 1; // Increment for future let nextup: Option<Result<VideoInfo>> = match data { // Something went wrong, return an error item Err(e) => { // Error state, prevent future iteration completed = true; // Return error Some(Err(e)) } Ok(new_items) => { if new_items.len() == 0 { // No more items, stop iterator None } else { current_items.extend(new_items); Some(Ok(current_items.pop_front().unwrap())) } } }; nextup } }); it } } /// Find channel ID either from a username or ID use crate::common::ChannelID; pub fn find_channel_id(name: &str, service: &Service) -> Result<ChannelID> { match service { Service::Youtube => { debug!("Looking up by username"); let url = format!( "{prefix}/api/v1/channels/{name}", prefix = api_prefix(), name = name ); debug!("Retrieving URL {}", &url); let resp = attohttpc::get(&url).send()?; let text = resp.text().unwrap(); trace!("Raw response: {}", &text); let data: YTChannelInfo = serde_json::from_str(&text) .with_context(|| format!("Failed to parse response from {}", &url))?; trace!("Raw deserialisation: {:?}", &data); Ok(ChannelID::Youtube(YoutubeID { id: data.author_id })) } Service::Vimeo => Err(anyhow::anyhow!("Not yet implemented!")), // FIXME: This method belongs outside of youtube.rs } } #[cfg(test)] mod test { use super::*; #[test] fn test_basic_find() -> Result<()> { let _m1 = mockito::mock("GET", "/api/v1/channels/thegreatsd") .with_body_from_file("testdata/channel_thegreatsd.json") .create(); let _m2 = mockito::mock("GET", "/api/v1/channels/UCUBfKCp83QT19JCUekEdxOQ") .with_body_from_file("testdata/channel_thegreatsd.json") // Same content .create(); let c = find_channel_id("thegreatsd", &crate::common::Service::Youtube)?; assert_eq!(c.id_str(), "UCUBfKCp83QT19JCUekEdxOQ"); assert_eq!(c.service(), crate::common::Service::Youtube); // Check same `ChannelID` is found by ID as by username let by_id = find_channel_id("UCUBfKCp83QT19JCUekEdxOQ", &crate::common::Service::Youtube)?; assert_eq!(by_id, c); Ok(()) } #[test] fn test_video_list() -> Result<()> { let mock_p1 = mockito::mock( "GET", "/api/v1/channels/videos/UCOYYX1Ucvx87A7CSy5M99yw?page=1", ) .with_body_from_file("testdata/channel_climb_page1.json") .create(); let mock_p2 = mockito::mock( "GET", "/api/v1/channels/videos/UCOYYX1Ucvx87A7CSy5M99yw?page=2", ) .with_body_from_file("testdata/channel_climb_page2.json") .create(); let cid = crate::common::YoutubeID { id: "UCOYYX1Ucvx87A7CSy5M99yw".into(), }; let yt = YoutubeQuery::new(&cid); let vids = yt.videos(); let result: Vec<super::VideoInfo> = vids .into_iter() .skip(58) // 60 videos per page, want to breach boundry .take(3) .collect::<Result<Vec<super::VideoInfo>>>()?; assert_eq!(result[0].title, "Vlog 013 - Excommunication"); assert_eq!(result[1].title, "Vlog 012 - Only in America!"); assert_eq!( result[2].title, "Vlog 011 - The part of the house no-one ever sees!" ); dbg!(result); mock_p1.expect(1); mock_p2.expect(1); Ok(()) } #[test] fn test_video_list_error() -> Result<()> { let mock_p1 = mockito::mock( "GET", "/api/v1/channels/videos/UCOYYX1Ucvx87A7CSy5M99yw?page=1", ) .with_body("garbagenonsense") .create(); let cid = crate::common::YoutubeID { id: "UCOYYX1Ucvx87A7CSy5M99yw".into(), }; let yt = YoutubeQuery::new(&cid); let mut vids = yt.videos(); assert!(vids.next().unwrap().is_err()); mock_p1.expect(1); assert!(vids.next().is_none()); Ok(()) } #[test] fn test_metadata() -> Result<()> { let _m1 = mockito::mock("GET", "/api/v1/channels/UCUBfKCp83QT19JCUekEdxOQ") .with_body_from_file("testdata/channel_thegreatsd.json") .create(); let cid = crate::common::YoutubeID { id: "UCUBfKCp83QT19JCUekEdxOQ".into(), }; let yt = YoutubeQuery::new(&cid); let meta = yt.get_metadata()?; assert_eq!(meta.title, "thegreatsd"); Ok(()) } }
true
5e735e4276f1a6d5da8ac41ebbeb31e246e71550
Rust
shybyte/exercism-rust
/isogram/src/lib.rs
UTF-8
394
3.453125
3
[]
no_license
use std::collections::HashSet; pub fn check(s: &str) -> bool { let letters = s.chars() .filter(|c| c.is_alphabetic()) .flat_map(|c| c.to_lowercase()); let mut letter_set = HashSet::new(); for letter in letters { if letter_set.contains(&letter) { return false; } else { letter_set.insert(letter); } } true }
true
07258e2084b85e760699fbbcbd600b0d6e851159
Rust
jrmaingo/rust-tutorials
/projects/area/src/main.rs
UTF-8
1,417
3.703125
4
[]
no_license
#[derive(Debug)] struct Rect { len: u32, wid: u32 } // return the area of the rectangle structure fn area(r: &Rect) -> u32 { r.len * r.wid } impl Rect { // return the area of the rectangle structure fn area(&self) -> u32 { self.len * self.wid } // return boolean for whether this instance can complety // contain the given parameter instance fn can_hold(&self, other: &Rect) -> bool { self.len > other.len && self.wid > other.wid } // constructor for square (associated function) fn square(size: u32) -> Rect { Rect { len: size, wid: size } } } // calculate area for rectangle represented with tuple fn tuple_area(dim: &(u32, u32)) -> u32 { dim.0 * dim.1 } // returns the area for rectangle represented by params fn param_area(len: u32, wid: u32) -> u32 { len * wid } fn main() { let rect = Rect { len: 5, wid: 7 }; println!("struct area: {}", area(&rect)); println!("debug rect: {:?}", &rect); println!("debug rect: {:#?}", &rect); println!("struct method area: {}", rect.area()); let rect2 = Rect::square(3); println!("rect can hold rect2: {}", rect.can_hold(&rect2)); println!("rect2 can hold rect: {}", rect2.can_hold(&rect)); let rect = (3, 6); println!("tuple area: {}", tuple_area(&rect)); let (len, wid) = (4, 5); println!("param area: {}", param_area(len, wid)); }
true
9147b14e44902df1acbe21e8426db8984b37a7cc
Rust
Schenk75/Learn-Rust
/leetcode-by-rust/LCOF/lcof17-打印从1到最大的n位数/src/main.rs
UTF-8
1,201
3.546875
4
[]
no_license
struct Solution; impl Solution { pub fn print_numbers(n: i32) -> Vec<i32> { let mut result = Vec::new(); let x = 10i32.saturating_pow(n as u32); for i in 1..x { result.push(i); } result } pub fn bn_print_numbers(n: i32) -> Vec<i32> { let mut result = Vec::new(); let mut num = Vec::new(); Self::dfs(0, n, &mut result, &mut num); result } fn dfs(x: i32, n: i32, result: &mut Vec<i32>, num: &mut Vec<char>) { if x == n { while num.len() != 0 && num[0] == '0' { num.remove(0); } if num.len() != 0 { let tmp: String = num.iter().collect(); result.push(tmp.parse().unwrap()); } return; } for i in vec!['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] { num.push(i); Self::dfs(x+1, n, result, num); if num.len() != 0 { num.remove(num.len()-1); } } } } fn main() { let n = 2; println!("{:?}", Solution::print_numbers(n)); println!("{:?}", Solution::bn_print_numbers(n)); }
true
10807b9f28620af74f8ccb94a4353935cfcd6935
Rust
rust-lang/rustfmt
/tests/target/issue-4926/enum_struct_field.rs
UTF-8
900
2.921875
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// rustfmt-struct_field_align_threshold: 30 // rustfmt-enum_discrim_align_threshold: 30 // rustfmt-imports_layout: HorizontalVertical #[derive(Default)] struct InnerStructA { bbbbbbbbb: i32, cccccccc: i32, } enum SomeEnumNamedD { E(InnerStructA), F { ggggggggggggggggggggggggg: bool, h: bool, }, } impl SomeEnumNamedD { fn f_variant() -> Self { Self::F { ggggggggggggggggggggggggg: true, h: true, } } } fn main() { let kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk = SomeEnumNamedD::f_variant(); let something_we_care_about = matches!( kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk, SomeEnumNamedD::F { ggggggggggggggggggggggggg: true, .. } ); if something_we_care_about { println!("Yup it happened"); } }
true
2ded54581d3bf80facc756e9c2dcbac44ed5938b
Rust
filipegoncalves/irc-tools
/src/protocol/mod.rs
UTF-8
2,770
2.8125
3
[ "MIT" ]
permissive
pub mod unreal; use cmd::IrcMsg; use conf::Config; use std::fmt::{Display, Formatter}; use std::fmt::Result as FmtResult; use std::rc::Rc; use std::cell::RefCell; /// A list of possible error types in the server-to-server protocol /// Any error that is not `Fatal` will yield a warning but keep the /// link active. `Fatal` errors drop the connection to the server. #[derive(Debug, PartialEq)] pub enum ProtoErrorKind { /// Command is missing one or more required parameters /// Example: receiving PRIVMSG with 0 parameters MissingParameter, /// Invalid parameter value /// Example: receiving a PING that needs to be forwarded InvalidParameter, /// A command that cannot / was not expected in this context. /// Example: receiving PASS when the link is already established. InvalidContext, /// Protocol version mismatch /// Example: Uplink runs UnrealIRCd with another protocol version ProtocolVMismatch, /// A fatal error that will cause the link to be terminated /// Example: Wrong link password / wrong server name Fatal } pub struct ProtocolError { pub kind: ProtoErrorKind, pub desc: &'static str, pub detail: Option<String> } pub enum IrcClientType { Regular, Service } pub trait ServerProtocol { //type IRCd; fn new(config: Rc<RefCell<Config>>) -> Self; fn introduce_msg(&self) -> String; fn introduce_client_msg(&self, ctype: IrcClientType, nick: &str, ident: &str, host: &str, gecos: &str) -> String; fn handle(&mut self, msg: &IrcMsg) -> Result<Option<String>, ProtocolError> { match &msg.command[..] { "PING" => self.handle_ping(msg), "PASS" => self.handle_pass(msg), _ => self.handle_generic(msg) } } fn handle_pass(&self, msg: &IrcMsg) -> Result<Option<String>, ProtocolError>; // TODO // When Rust supports struct inheritance, move handle_ping back here fn handle_ping(&self, msg: &IrcMsg) -> Result<Option<String>, ProtocolError>; fn handle_server(&self, msg: &IrcMsg) -> Result<Option<String>, ProtocolError>; #[allow(unused_variables)] fn handle_generic(&mut self, msg: &IrcMsg) -> Result<Option<String>, ProtocolError> { Ok(None) } } impl ProtocolError { fn new(errtype: ProtoErrorKind, descr: &'static str, details: Option<String>) -> ProtocolError { ProtocolError { kind: errtype, desc: descr, detail: details } } } impl Display for ProtocolError { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "[PROTOCOL ERROR] ({:?}): {} ({})", self.kind, self.desc, self.detail.as_ref().map_or("no details", |d| &d[..])) } }
true
4fe9758c3eb865a612efd410007f576229e964e0
Rust
DrStiev/rs-gfa2
/src/tag.rs
UTF-8
5,948
3.15625
3
[ "MIT" ]
permissive
/// file that tries to mimic the behaviour of the file optfields.rs /// optfields.rs find, parse and store all the different types of /// optional fields associated to each kind of lines. /// with the format GFA2 the optional field tag is been replaced by a /// simple tag element with 0 or N occurencies. /// So, I don't think this file could be useful as the original. use bstr::BString; use lazy_static::lazy_static; use regex::bytes::Regex; /// These type aliases are useful for configuring the parsers, as the /// type of the optional field container must be given when creating a /// GFAParser or GFA object. pub type OptionalFields = Vec<OptField>; pub type NoOptionalFields = (); /// An optional field a la SAM. Identified by its tag, which is any /// two characters matching [A-Za-z][A-Za-z0-9]. #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct OptField { pub tag: [u8; 2], pub value: OptFieldVal, } /// enum for representing each of the SAM optional field types. The /// `B` type, which denotes either an integer or float array, is split /// in two variants, and they ignore the size modifiers in the spec, /// instead always holding i64 or f32. #[derive(Debug, Clone, PartialEq, PartialOrd)] pub enum OptFieldVal { Z(BString), I(BString), F(BString), A(BString), J(BString), H(BString), B(BString), } impl OptField { /// Panics if the provided tag doesn't match the regex /// [A-Za-z0-9][A-Za-z0-9]. pub fn tag(t: &[u8]) -> [u8; 2] { assert_eq!(t.len(), 2); assert!(t[0].is_ascii_alphanumeric()); assert!(t[1].is_ascii_alphanumeric()); [t[0], t[1]] } /// Create a new OptField from a tag name and a value, panicking /// if the provided tag doesn't fulfill the requirements of /// OptField::tag(). pub fn new(tag: &[u8], value: OptFieldVal) -> Self { let tag = OptField::tag(tag); OptField { tag, value } } /// Parses the header and optional fields from a bytestring in the format\ /// ```<Header> <- {VN:Z:2.0}\t{TS:i:[-+]?[0-9]+}\t<tag>*``` /// ```<tag> <- <TAG>:<TYPE>:<VALUE> <- [A-Za-z0-9][A-Za-z0-9]:[ABHJZif]:[ -~]*``` pub fn parse(input: &[u8]) -> Option<Self> { lazy_static! { static ref RE: Regex = Regex::new(r"(?-u)([A-Za-z0-9][A-Za-z0-9]:[ABHJZif]:[ -~]*)*").unwrap(); } use OptFieldVal::*; let o_tag = input.get(0..=1)?; let o_type = input.get(3)?; let o_val = match o_type { b'A' => RE.find(input).map(|s| s.as_bytes().into()).map(A), b'i' => RE.find(input).map(|s| s.as_bytes().into()).map(I), b'f' => RE.find(input).map(|s| s.as_bytes().into()).map(F), b'Z' => RE.find(input).map(|s| s.as_bytes().into()).map(Z), b'J' => RE.find(input).map(|s| s.as_bytes().into()).map(J), b'H' => RE.find(input).map(|s| s.as_bytes().into()).map(H), b'B' => RE.find(input).map(|s| s.as_bytes().into()).map(B), _ => None, }?; Some(Self::new(o_tag, o_val)) } } /// The Display implementation produces spec-compliant strings in the /// ```<TAG>:<TYPE>:<VALUE>``` format, and can be parsed back using /// OptField::parse(). impl std::fmt::Display for OptField { fn fmt(&self, form: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use OptFieldVal::*; match &self.value { A(x) => write!(form, "{}", x), I(x) => write!(form, "{}", x), F(x) => write!(form, "{}", x), Z(x) => write!(form, "{}", x), J(x) => write!(form, "{}", x), H(x) => write!(form, "{}", x), B(x) => write!(form, "{}", x), } } } /// The OptFields trait describes how to parse, store, and query /// optional fields. Each of the GFA line types and the GFA struct /// itself are generic over the optional fields, so the choice of /// OptFields implementor can impact memory usage, which optional /// fields are parsed, and possibly more in the future pub trait OptFields: Sized + Default + Clone { /// Return the optional field with the given tag, if it exists. fn get_field(&self, tag: &[u8]) -> Option<&OptField>; /// Return a slice over all optional fields. NB: This may be /// replaced by an iterator or something else in the future fn fields(&self) -> &[OptField]; /// Given an iterator over bytestrings, each expected to hold one /// optional field (in the <TAG>:<TYPE>:<VALUE> format), parse /// them as optional fields to create a collection. Returns `Self` /// rather than `Option<Self>` for now, but this may be changed to /// become fallible in the future. fn parse<T>(input: T) -> Self where T: IntoIterator, T::Item: AsRef<[u8]>; } /// This implementation is useful for performance if we don't actually /// need any optional fields. () takes up zero space, and all /// methods are no-ops. impl OptFields for () { fn get_field(&self, _: &[u8]) -> Option<&OptField> { None } fn fields(&self) -> &[OptField] { &[] } fn parse<T>(_input: T) -> Self where T: IntoIterator, T::Item: AsRef<[u8]>, { } } /// Stores all the optional fields in a vector. `get_field` simply /// uses std::iter::Iterator::find(), but as there are only a /// relatively small number of optional fields in practice, it should /// be efficient enough. impl OptFields for Vec<OptField> { fn get_field(&self, tag: &[u8]) -> Option<&OptField> { self.iter().find(|o| o.tag == tag) } fn fields(&self) -> &[OptField] { self.as_slice() } fn parse<T>(input: T) -> Self where T: IntoIterator, T::Item: AsRef<[u8]>, { input .into_iter() .filter_map(|f| OptField::parse(f.as_ref())) .collect() } }
true
34970a6e75cdae0270c437a26c3818eac4d0d1e9
Rust
yskszk63/pwl
/src/segment.rs
UTF-8
1,013
3.0625
3
[ "MIT" ]
permissive
use crate::Color; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Group { GitStatus, } #[derive(Debug)] pub struct Builder { color: Color, text: String, group: Option<Group>, } impl Builder { pub fn group(&mut self, group: Group) -> &mut Self { self.group = Some(group); self } pub fn build(&self) -> Segment { Segment { color: self.color.clone(), text: self.text.clone(), group: self.group.clone(), } } } #[derive(Debug)] pub struct Segment { color: Color, text: String, group: Option<Group>, } impl Segment { pub fn builder(color: Color, text: impl ToString) -> Builder { Builder { color, text: text.to_string(), group: None, } } pub fn color(&self) -> &Color { &self.color } pub fn text(&self) -> &str { &self.text } pub fn group(&self) -> Option<&Group> { self.group.as_ref() } }
true
a61a3f8b42810f80197324c8a17b75cbf3d52be2
Rust
kmc-jp/cerussite
/cerussite-test-tool/src/main.rs
UTF-8
11,861
2.65625
3
[ "MIT" ]
permissive
#[macro_use] extern crate colored_print; extern crate atty; use colored_print::color::ConsoleColor; use colored_print::color::ConsoleColor::*; use std::env; use std::ffi::OsStr; use std::fmt; use std::fmt::Display; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; fn colorize() -> bool { use atty; use atty::Stream; atty::is(Stream::Stdout) } fn modified_file_name(path: &Path, suffix: &str, ext: Option<&str>) -> String { let name = path .file_stem() .expect("internal error: there are no files without name!") .to_str() .expect("internal error: file name cannot be represented in UTF-8."); let ext = ext.map(|x| format!(".{}", x)).unwrap_or(format!("")); format!("{}{}{}", name, suffix, ext) } enum CompilationResult { Success { ir_path: PathBuf, llvm_ir: String, cc_output: String, }, Failure { cc_output: String, }, } /// returns the result of compilation with clang (for reference) fn reference_compile(src_path: &Path) -> io::Result<CompilationResult> { let ir_path = src_path.with_file_name(modified_file_name(src_path, "_ref", Some("ll"))); // compile let output = Command::new("clang") .arg("-O0") .arg("-S") .arg("-emit-llvm") .arg("-o") .arg(ir_path.display().to_string()) .arg(src_path.display().to_string()) .output()?; let cc_output = String::from_utf8_lossy(&output.stderr).into_owned(); if !ir_path.exists() { return Ok(CompilationResult::Failure { cc_output }); } let mut llvm_ir = String::new(); File::open(&ir_path)?.read_to_string(&mut llvm_ir)?; Ok(CompilationResult::Success { ir_path, llvm_ir, cc_output, }) } /// returns the llvm_ir of compilation with our current compiler fn current_compile(src_path: &Path) -> io::Result<CompilationResult> { let ir_path = src_path.with_file_name(modified_file_name(src_path, "_cur", Some("ll"))); // compile let output = Command::new("cargo") .arg("run") .arg("--") .arg(src_path.display().to_string()) .output()?; let cc_output = String::from_utf8_lossy(&output.stderr).into_owned(); if output.stdout.is_empty() { // compilation failed. return Ok(CompilationResult::Failure { cc_output }); } File::create(&ir_path)?.write_all(&output.stdout)?; let llvm_ir = String::from_utf8_lossy(&output.stdout).into_owned(); Ok(CompilationResult::Success { ir_path, llvm_ir, cc_output, }) } enum AssemblyResult { Success { asm_output: String, exec_path: PathBuf, }, Failure { asm_output: String, }, Unreached, } fn compile_llvm_ir(src_path: &Path) -> io::Result<AssemblyResult> { let exec_path = if cfg!(windows) { src_path.with_extension("exe") } else { let file_name = src_path .file_stem() .expect("internal error: no file has no basename"); src_path.with_file_name(file_name) }; if !src_path.exists() { panic!("internal error: compilation has succeeded but no LLVM IR?"); } let output = Command::new("clang") .arg("-o") .arg(&exec_path) .arg(&src_path) .output()?; let asm_output = String::from_utf8_lossy(&output.stderr).into_owned(); if !exec_path.exists() { return Ok(AssemblyResult::Failure { asm_output }); } Ok(AssemblyResult::Success { asm_output, exec_path, }) } enum ExecutionResult { Success { status: Option<i32>, stdout: String, stderr: String, }, Unreached, } /// returns the execution of the binary placed in the specified path fn execute(path: &Path) -> io::Result<ExecutionResult> { if !path.exists() { return Ok(ExecutionResult::Success { status: None, stdout: String::new(), stderr: String::new(), }); } let mut child = Command::new(&path) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; let status = child.wait()?; let mut child_stdout = child .stdout .expect("internal error: failed to get child stdout."); let mut child_stderr = child .stderr .expect("internel error: failed to get child stderr."); let (mut stdout, mut stderr) = (String::new(), String::new()); child_stdout.read_to_string(&mut stdout)?; child_stderr.read_to_string(&mut stderr)?; let status = status.code(); Ok(ExecutionResult::Success { status, stdout, stderr, }) } fn print_heading(color: ConsoleColor, heading: &str) { colored_println!{ colorize(); color, "{} ", heading; } } fn print_output(retval: Option<i32>, output: &str) { colored_print!{ colorize(); Reset, "{}", output; } if let Some(code) = retval { colored_println!{ colorize(); Cyan, "return code"; Reset, ": {}", code; } } } fn print_stderr(stderr: impl Display) { colored_print!{ colorize(); LightMagenta, "{}", stderr; } } #[derive(Debug, Copy, Clone)] enum Version { Reference, Current, } impl Version { pub fn get_compiler_func(&self) -> fn(path: &Path) -> io::Result<CompilationResult> { match *self { Version::Reference => reference_compile, Version::Current => current_compile, } } } impl fmt::Display for Version { fn fmt(&self, b: &mut fmt::Formatter) -> fmt::Result { match *self { Version::Reference => write!(b, "Reference"), Version::Current => write!(b, " Current "), } } } struct Results { compilation: CompilationResult, assembly: AssemblyResult, execution: ExecutionResult, } fn do_for(version: Version, path: &Path) -> io::Result<Results> { let (compilation, assembly, execution); // explicitly denote borrowing region { compilation = (version.get_compiler_func())(&path)?; let ir_path = match compilation { failure @ CompilationResult::Failure { .. } => { return Ok(Results { compilation: failure, assembly: AssemblyResult::Unreached, execution: ExecutionResult::Unreached, }) } CompilationResult::Success { ref ir_path, .. } => ir_path.clone(), }; assembly = compile_llvm_ir(&ir_path)?; let exec_path = match assembly { failure @ AssemblyResult::Failure { .. } => { return Ok(Results { compilation: compilation, assembly: failure, execution: ExecutionResult::Unreached, }) } AssemblyResult::Success { ref exec_path, .. } => exec_path.clone(), AssemblyResult::Unreached => unreachable!(), }; execution = execute(&exec_path)?; } Ok(Results { compilation, assembly, execution, }) } fn judge(refr: &ExecutionResult, curr: &ExecutionResult) -> (bool, ConsoleColor, &'static str) { const OK: (bool, ConsoleColor, &str) = (true, Green, "OK"); const NG: (bool, ConsoleColor, &str) = (false, Red, "NG"); use ExecutionResult::Success; match (refr, curr) { ( Success { status: ref refr_status, stdout: ref refr_stdout, .. }, Success { status: ref curr_status, stdout: ref curr_stdout, .. }, ) => { if (refr_status, refr_stdout) == (curr_status, curr_stdout) { OK } else { NG } } _ => NG, } } fn print_for(version: Version, results: Results) { print_heading( LightGreen, &format!("==================== {} ====================", version), ); use {AssemblyResult as AR, CompilationResult as CR, ExecutionResult as ER}; print_heading(LightBlue, "> Compilation (C)"); match results.compilation { CR::Success { cc_output, llvm_ir, .. } => { print_stderr(&cc_output); print_output(None, &llvm_ir); } CR::Failure { cc_output, .. } => { print_stderr(&cc_output); return; } } print_heading(LightBlue, "> Compilation (LLVM IR)"); match results.assembly { AR::Success { asm_output, .. } => { print_stderr(&asm_output); } AR::Failure { asm_output, .. } => { print_stderr(&asm_output); return; } AR::Unreached => unreachable!(), } print_heading(LightBlue, "> Execution"); match results.execution { ER::Success { status, stdout, stderr, } => { print_stderr(&stderr); print_output(status, &stdout); } ER::Unreached => unreachable!(), } } fn main() -> io::Result<()> { let verbose = env::args().any(|arg| arg == "--verbose" || arg == "-v"); let test_src_dir: PathBuf = ["test", "ok"].iter().collect(); walk_dir( &test_src_dir, |path| path.extension().and_then(OsStr::to_str) != Some("c"), |path| { if verbose { colored_println! { colorize(); LightGreen, "Removing "; Reset, "{}", path.display(); } } fs::remove_file(&path) }, )?; let mut path_to_test: Vec<_> = env::args() .skip(1) .filter(|arg| !arg.starts_with("-")) .map(|file_name| test_src_dir.join(file_name)) .collect(); if path_to_test.is_empty() { path_to_test = walk_dir( &test_src_dir, |path| path.extension().and_then(OsStr::to_str) == Some("c"), |path| Ok(path.to_path_buf()), )?; } let mut any_fails = false; for path in path_to_test { colored_print!{ colorize(); LightGreen, " Testing "; Reset, "file "; Yellow, "{}", path.display(); Reset, " ... "; } if !path.exists() { println!("not found"); continue; } let refr = do_for(Version::Reference, &path)?; let curr = do_for(Version::Current, &path)?; let (status, color, judge) = judge(&refr.execution, &curr.execution); colored_println!{ colorize(); color, "{}", judge; } // print info when verbose mode or something fails if verbose || !status { print_for(Version::Reference, refr); print_for(Version::Current, curr); } any_fails |= !status; } if !any_fails { Ok(()) } else { Err(io::Error::new(io::ErrorKind::Other, "some test fails.")) } } fn walk_dir<T>( dir: &Path, path_filter: impl Fn(&Path) -> bool + Copy, cb: impl Fn(&Path) -> io::Result<T> + Copy, ) -> io::Result<Vec<T>> { let mut result = Vec::new(); for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if !path_filter(&path) { continue; } if path.is_dir() { walk_dir(&path, path_filter, cb)?; } else { result.push(cb(&path)?); } } Ok(result) }
true
881a5a1e4b36b8c23f84e7290c09d8b0811a10a6
Rust
aopicier/cryptopals-rust
/challenges/src/errors.rs
UTF-8
2,527
3.265625
3
[ "MIT" ]
permissive
use std::{error, fmt}; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>; #[derive(Debug, Clone)] pub enum ChallengeError { ComparisonFailed { // Can this be made generic? expected: String, actual: String, }, NotImplemented, ItemNotFound(String), Skipped(&'static str), } // This is important for other errors to wrap this one. impl error::Error for ChallengeError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { // Generic error, underlying cause isn't tracked. None } } impl fmt::Display for ChallengeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ChallengeError::ComparisonFailed { expected, actual } => write!( f, "Comparison failed. Expected: {}, found: {}", expected, actual ), ChallengeError::NotImplemented => write!(f, "Not implemented."), ChallengeError::ItemNotFound(item) => write!(f, "Item not found: {}", item), ChallengeError::Skipped(item) => write!(f, "Skipping: {}", item), } } } #[derive(Debug, Clone)] pub struct ConnectionFailed; // This is important for other errors to wrap this one. impl error::Error for ConnectionFailed { fn source(&self) -> Option<&(dyn error::Error + 'static)> { // Generic error, underlying cause isn't tracked. None } } impl fmt::Display for ConnectionFailed { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "connection failed") } } #[derive(Debug)] pub struct AnnotatedError { pub message: String, pub error: Box<dyn std::error::Error + Send + Sync + 'static>, } // This is important for other errors to wrap this one. impl error::Error for AnnotatedError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { // Generic error, underlying cause isn't tracked. Some(&*self.error) } } impl fmt::Display for AnnotatedError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.message) } } #[allow(clippy::needless_pass_by_value)] // False positive pub fn compare_eq<T>(x: T, y: T) -> Result<()> where T: Eq + std::fmt::Debug, { if x == y { Ok(()) } else { Err(ChallengeError::ComparisonFailed { expected: format!("{:?}", x), actual: format!("{:?}", y), } .into()) } }
true
e44736bcda02f03aefaaddbd49ef8a4c9396b383
Rust
irrustible/macaron
/macaron-impl/src/metagroups.rs
UTF-8
4,152
2.90625
3
[ "LLVM-exception", "Apache-2.0" ]
permissive
use crate::*; use proc_macro2::TokenStream; use quote::ToTokens; use smallvec::SmallVec; use std::{borrow::Cow, collections::HashMap, fmt::{self, Debug}}; use syn::{token, parse::{discouraged::Speculative, ParseStream, Result}}; #[derive(Clone)] pub struct MetaGroup<T> { pub dollar: token::Dollar, pub bracket: token::Bracket, pub name: Ident, pub paren: token::Paren, pub separator: Option<Separator>, pub multiplier: Multiplier, pub values: Vec<T>, } impl<T: ToTokens> ToTokens for MetaGroup<T> { fn to_tokens(&self, stream: &mut TokenStream) { self.dollar.to_tokens(stream); self.bracket.surround(stream, |stream| { self.name.to_tokens(stream); }); self.paren.surround(stream, |stream| { for v in self.values.iter() { v.to_tokens(stream); } }); if let Some(s) = &self.separator { s.to_tokens(stream); } self.multiplier.to_tokens(stream) } } impl<T> Debug for MetaGroup<T> { fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> { f.write_str("MetaGroup<T>") } } /// Matching a metagroup does not recurse into it. We must match it /// potentially many times according to its multiplier. #[derive(Clone, Debug)] pub struct MetaGroupMatch { pub name: Ident, pub multiplier: Multiplier, pub rounds: SmallVec<[RoundMatch; 1]>, } impl MetaGroup<Pattern> { pub fn parse_match(&self, stream: ParseStream) -> Result<Match> { let mut rounds: SmallVec<[RoundMatch; 1]> = SmallVec::new(); loop { match self.parse_match_round(stream) { Ok(round) => rounds.push(round), Err(e) => { if rounds.len() > 1 || self.multiplier.may_be_empty() { return Ok(Match::MetaGroup(MetaGroupMatch { name: self.name.clone(), multiplier: self.multiplier.clone(), rounds })); } else { return Err(e); } } } } } pub fn parse_match_round(&self, stream: ParseStream) -> Result<RoundMatch> { let fork = stream.fork(); let mut scope = Scope::Round(Cow::Owned(RoundMatch::default())); for p in self.values.iter() { let ret = p.parse_match(&fork, &mut scope)?; scope.round_mut().capture_match(ret.clone()); } stream.advance_to(&fork); Ok(scope.into_round().unwrap()) } pub fn parse_suffix(input: ParseStream) -> Result<(Option<Separator>, Multiplier)> { let l = input.lookahead1(); if let Ok(multiplier) = input.parse::<Multiplier>() { Ok((None,multiplier)) } else if let Ok(separator) = input.parse::<Separator>() { let multiplier = input.parse::<Multiplier>()?; Ok((Some(separator),multiplier)) } else { Err(l.error()) } } } #[derive(Clone, Default, Debug)] pub struct RoundMatch { pub matches: Vec<Match>, pub groups: HashMap<Ident, MetaGroupMatch>, pub fragments: HashMap<Ident, Fragment>, } impl RoundMatch { pub fn capture_match(&mut self, m: Match) { match &m { Match::Fragment(f) => self.capture_fragment(f.clone()), Match::MetaGroup(g) => self.capture_metagroup(g.clone()), _ => (), } self.matches.push(m); } pub fn capture_metagroup(&mut self, group: MetaGroupMatch) { self.groups.insert(group.name.clone(), group); } pub fn capture_fragment(&mut self, fragment: FragmentMatch) { if let Some(name) = fragment.name { self.fragments.insert(name, fragment.fragment); } } pub fn fragment(&self, name: &Ident) -> Option<&Fragment> { self.fragments.get(name) } pub fn group(&self, name: &Ident) -> Option<&MetaGroupMatch> { self.groups.get(name) } }
true
e816124b47f5fcd77071e517066dc7576a40a75a
Rust
StupidHackTH/stupid-hack-5-api-challenge
/code/src/modules/not_found/controllers.rs
UTF-8
2,400
2.609375
3
[]
no_license
use actix_web::{HttpResponse, http::header}; const NOT_FOUND: &'static str = r#" <!DOCTYPE HTML> <html lang="en"> <head> <title>Not found</title> <meta charset="utf8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * { box-sizing: border-box; } html, body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } #page { display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; height: 100vh; margin: 0; padding: 0 20px; } #image { display: block; width: 100%; max-width: 460px; margin: 0 0 20px 0; padding: 0; object-fit: contain; object-position: center; border-radius: 8px; box-shadow: 0 4px 16px rgba(0,0,0,.125); } #title { font-size: 32px; font-weight: 500; color: #374151; margin: 20px 0; } .link { color: #007aff; text-decoration: no-underline; padding: 2px 6px; text-decoration: none; border-radius: 4px; transition: background-color .2s ease-out; } .link:hover, .link:focus { background-color: rgba(0,123,255,.1); } #docs { font-size: 21px; padding: 12px 32px; } </style> </head> <body id="page"> <img id="image" src="https://user-images.githubusercontent.com/35027979/118144418-a38b9680-b436-11eb-9649-f54c8bbf5346.JPG" alt="Error cats" /> <h1 id="title">Not found</h1> <a id="docs" class="link" href="/docs" title="Click to view documentation">Documentation</a> </body> </html> "#; pub async fn not_found() -> HttpResponse { HttpResponse::Ok() .append_header(header::ContentType::html()) .body(NOT_FOUND) }
true
c9deb8245fb8e88d41caf1abad8a7c199d4c7ffb
Rust
Thearas/rust-analyzer
/crates/ra_analysis/src/descriptors/module/scope.rs
UTF-8
3,589
3.3125
3
[ "MIT", "Apache-2.0" ]
permissive
//! Backend for module-level scope resolution & completion use ra_syntax::{ast, AstNode, SmolStr}; use crate::syntax_ptr::LocalSyntaxPtr; /// `ModuleScope` contains all named items declared in the scope. #[derive(Debug, PartialEq, Eq)] pub(crate) struct ModuleScope { entries: Vec<Entry>, } /// `Entry` is a single named declaration iside a module. #[derive(Debug, PartialEq, Eq)] pub(crate) struct Entry { ptr: LocalSyntaxPtr, kind: EntryKind, name: SmolStr, } #[derive(Debug, PartialEq, Eq)] enum EntryKind { Item, Import, } impl ModuleScope { pub(super) fn new<'a>(items: impl Iterator<Item = ast::ModuleItem<'a>>) -> ModuleScope { let mut entries = Vec::new(); for item in items { let entry = match item { ast::ModuleItem::StructDef(item) => Entry::new(item), ast::ModuleItem::EnumDef(item) => Entry::new(item), ast::ModuleItem::FnDef(item) => Entry::new(item), ast::ModuleItem::ConstDef(item) => Entry::new(item), ast::ModuleItem::StaticDef(item) => Entry::new(item), ast::ModuleItem::TraitDef(item) => Entry::new(item), ast::ModuleItem::TypeDef(item) => Entry::new(item), ast::ModuleItem::Module(item) => Entry::new(item), ast::ModuleItem::UseItem(item) => { if let Some(tree) = item.use_tree() { collect_imports(tree, &mut entries); } continue; } ast::ModuleItem::ExternCrateItem(_) | ast::ModuleItem::ImplItem(_) => continue, }; entries.extend(entry) } ModuleScope { entries } } pub fn entries(&self) -> &[Entry] { self.entries.as_slice() } } impl Entry { fn new<'a>(item: impl ast::NameOwner<'a>) -> Option<Entry> { let name = item.name()?; Some(Entry { name: name.text(), ptr: LocalSyntaxPtr::new(name.syntax()), kind: EntryKind::Item, }) } fn new_import(path: ast::Path) -> Option<Entry> { let name_ref = path.segment()?.name_ref()?; Some(Entry { name: name_ref.text(), ptr: LocalSyntaxPtr::new(name_ref.syntax()), kind: EntryKind::Import, }) } pub fn name(&self) -> &SmolStr { &self.name } pub fn ptr(&self) -> LocalSyntaxPtr { self.ptr } } fn collect_imports(tree: ast::UseTree, acc: &mut Vec<Entry>) { if let Some(use_tree_list) = tree.use_tree_list() { return use_tree_list .use_trees() .for_each(|it| collect_imports(it, acc)); } if let Some(path) = tree.path() { acc.extend(Entry::new_import(path)); } } #[cfg(test)] mod tests { use super::*; use ra_syntax::{ast::ModuleItemOwner, SourceFileNode}; fn do_check(code: &str, expected: &[&str]) { let file = SourceFileNode::parse(&code); let scope = ModuleScope::new(file.ast().items()); let actual = scope.entries.iter().map(|it| it.name()).collect::<Vec<_>>(); assert_eq!(expected, actual.as_slice()); } #[test] fn test_module_scope() { do_check( " struct Foo; enum Bar {} mod baz {} fn quux() {} use x::{ y::z, t, }; type T = (); ", &["Foo", "Bar", "baz", "quux", "z", "t", "T"], ) } }
true
05e3cffd3b85febc73cb4691a59bbe947a653e34
Rust
aep000/ReactiveDB
/reactive_db/src/storage/storage_manager.rs
UTF-8
9,558
2.578125
3
[]
no_license
use crate::utilities::max_size_hash_map::MaxSizeHashMap; use crate::io::Cursor; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::cmp; use std::collections::BinaryHeap; use std::collections::HashSet; use std::fs::File; use std::fs::OpenOptions; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::io::BufWriter; use std::io::SeekFrom; use std::io::{Error, ErrorKind}; use super::storage_engine::StorageEngine; const CACHE_SIZE: usize = 100; const DATA_BLOCK_SIZE: u32 = 100; const REFERENCE_BLOCK_SIZE: u32 = 4; const TOTAL_BLOCK_SIZE: u32 = DATA_BLOCK_SIZE + REFERENCE_BLOCK_SIZE; pub struct StorageManager { pub file_name: String, pub open_blocks: BinaryHeap<isize>, pub closed_blocks: HashSet<u32>, pub number_of_blocks: u32, pub session_open: bool, pub open_file: Option<File>, cache: MaxSizeHashMap<u32, Vec<u8>> } impl StorageEngine for StorageManager { fn start_read_session(&mut self) -> io::Result<()> { self.session_open = true; self.open_file = Some(OpenOptions::new().read(true).open(&self.file_name)?); return Ok(()); } fn start_write_session(&mut self) -> io::Result<()> { self.session_open = true; self.open_file = Some( OpenOptions::new() .read(true) .write(true) .create(true) .open(&self.file_name)?, ); return Ok(()); } fn end_session(&mut self) { self.session_open = false; self.open_file = None; } fn allocate_block(&mut self) -> u32 { match self.open_blocks.pop() { Some(n) => { let block = (-n) as u32; if self.closed_blocks.contains(&block) { return self.allocate_block(); } return block; } None => { self.number_of_blocks += 1; return self.number_of_blocks; } } } fn write_data(&mut self, data: Vec<u8>, starting_block: Option<u32>) -> io::Result<u32> { //let mut compressed = vec![]; //BzEncoder::new(data.as_slice(), Compression::Default) // .read_to_end(&mut compressed) // .unwrap(); //let data = compressed; self.start_write_session()?; let root_block: u32 = match starting_block { Some(n) => { if self.number_of_blocks <= n { self.number_of_blocks += 1; } self.closed_blocks.insert(n); n } None => self.allocate_block(), }; let mut cursor = 0; let mut current_block = root_block; while cursor < data.len() { let end = cursor + (DATA_BLOCK_SIZE as usize); let mut next_ref = 0; let mut next_ref_to_write = vec![0; REFERENCE_BLOCK_SIZE as usize]; if end < data.len() { let mut endian_rep = vec![]; next_ref = self.allocate_block(); endian_rep.write_u32::<BigEndian>(next_ref)?; next_ref_to_write = vec![0; REFERENCE_BLOCK_SIZE as usize - endian_rep.len()]; next_ref_to_write.extend(endian_rep); }; let mut to_write = data[cursor..cmp::min(end, data.len())].to_vec(); to_write.extend(next_ref_to_write); self.write_block(current_block, to_write)?; cursor = end; current_block = next_ref; } return Ok(root_block); } fn read_data(&mut self, starting_block: u32) -> io::Result<Vec<u8>> { let mut block_to_read: usize = starting_block as usize; let mut output = vec![]; while block_to_read != 0 { let raw_block = self.read_block(block_to_read as u32)?; if raw_block.len() <= DATA_BLOCK_SIZE as usize { return Err(Error::new(ErrorKind::Other, "Error datablock too small")); } let data_block = &raw_block[..DATA_BLOCK_SIZE as usize].to_vec(); let next_block_raw = raw_block[(DATA_BLOCK_SIZE) as usize..].to_vec(); block_to_read = Cursor::new(next_block_raw).read_u32::<BigEndian>().unwrap() as usize; output.extend(data_block); } if output == vec![0; output.len()] { return Ok(output); } //let mut decompressed = vec![]; //println!("{:?}", output); //BzDecoder::new(output.as_slice()) // .read_to_end(&mut decompressed) // .unwrap(); return Ok(trim(&output)); } fn delete_data(&mut self, starting_block: u32) -> io::Result<()> { let mut block_to_read: usize = starting_block as usize; while block_to_read != 0 { let raw_block = self.read_block(block_to_read as u32)?; let next_block_raw = raw_block[(DATA_BLOCK_SIZE) as usize..].to_vec(); self.delete_block(block_to_read as u32)?; if block_to_read != 1 && block_to_read != 0 { self.open_blocks.push(-(block_to_read as isize)); self.closed_blocks.remove(&(block_to_read as u32)); } block_to_read = Cursor::new(next_block_raw).read_u32::<BigEndian>().unwrap() as usize; } return Ok(()); } fn is_empty(&mut self, block: u32) -> io::Result<bool> { if block > self.number_of_blocks { return Ok(true); } let block = self.read_block(block)?; return Ok(block == vec![0; TOTAL_BLOCK_SIZE as usize]); } fn get_file_name(&mut self) -> String { self.file_name.clone() } } impl StorageManager { pub fn new(file_name: String) -> io::Result<StorageManager> { print!("V1 detected"); let mut manager = StorageManager { file_name: file_name, open_blocks: BinaryHeap::new(), closed_blocks: HashSet::new(), number_of_blocks: 0, session_open: false, open_file: None, cache: MaxSizeHashMap::new(CACHE_SIZE) }; manager.start_write_session()?; manager.update_open_blocks()?; manager.end_session(); return Ok(manager); } // Write to a specific block fn write_block(&mut self, block_number: u32, mut data: Vec<u8>) -> io::Result<()> { if !self.session_open { return Err(Error::new(ErrorKind::Other, "Session not open")); } let mut file = self.open_file.as_ref().unwrap(); file.seek(SeekFrom::Start((block_number * TOTAL_BLOCK_SIZE) as u64))?; let mut writer = BufWriter::new(file); let to_write: Vec<u8> = vec![0; TOTAL_BLOCK_SIZE as usize - data.len()]; data.extend(to_write); self.cache.insert(block_number, data.clone()); writer.write_all(&data)?; writer.flush()?; return Ok(()); } // Read a specific block fn read_block(&mut self, block_number: u32) -> io::Result<Vec<u8>> { if !self.session_open { return Err(Error::new(ErrorKind::Other, "Session not open")); } let is_in_cache = match self.cache.get(&block_number) { Some(block) => { return Ok(block.clone()) }, None => false }; let mut file = self.open_file.as_ref().unwrap(); file.seek(SeekFrom::Start((block_number * TOTAL_BLOCK_SIZE) as u64))?; let mut reader = BufReader::with_capacity(TOTAL_BLOCK_SIZE as usize, file); let buffer = reader.fill_buf()?; if !is_in_cache { self.cache.insert(block_number, buffer.to_vec()); } return Ok(buffer.to_vec()); } //Delete specific block fn delete_block(&mut self, block_number: u32) -> io::Result<()> { if !self.session_open { return Err(Error::new(ErrorKind::Other, "Session not open")); } self.cache.remove(block_number); let mut file = self.open_file.as_ref().unwrap(); file.seek(SeekFrom::Start((block_number * TOTAL_BLOCK_SIZE) as u64))?; let fill = vec![0; TOTAL_BLOCK_SIZE as usize]; self.write_block(block_number, fill)?; return Ok(()); } fn update_open_blocks(&mut self) -> io::Result<()> { let file = self.open_file.as_ref().unwrap(); let mut open_blocks = vec![]; let empty_block: Vec<u8> = vec![0; TOTAL_BLOCK_SIZE as usize]; let file_len = file.metadata()?.len(); let num_blocks = file_len / (TOTAL_BLOCK_SIZE as u64); for n in 2..num_blocks { let block = self.read_block(n as u32)?; if block == empty_block { open_blocks.push(n as u32); } } for block in open_blocks { self.open_blocks.push(-(block as isize)); } self.number_of_blocks = num_blocks as u32; return Ok(()); } } // trims tail off data fn trim(vector: &[u8]) -> Vec<u8> { let mut started_tail = false; let mut output: Vec<u8> = vec![]; let mut c = 0; while !started_tail && c < vector.len() { if vector[c] == 0 { started_tail = true; for v in vector[c..].to_vec() { if v != 0 { started_tail = false; } } } else { output.push(vector[c]); } c += 1; } return output; }
true
3e8d7e2b8de12dbe032e85bce3806fd5532f67c1
Rust
Logicalshift/flowbetween
/user_interfaces/cocoa_pipe/src/action.rs
UTF-8
7,828
3.21875
3
[ "Apache-2.0" ]
permissive
use flo_ui::*; use flo_canvas::{Draw, Color}; use super::view_type::*; /// /// Represents a property binding in a Cocoa application /// #[derive(Clone, PartialEq, Debug)] pub enum AppProperty { Nothing, Bool(bool), Int(i32), Float(f64), String(String), /// Property is bound to a property ID in the view model Bind(usize, usize) } /// /// Represents a position coordinate /// #[derive(Clone, PartialEq, Debug)] pub enum AppPosition { At(f64), Floating(AppProperty, f64), Offset(f64), Stretch(f64), Start, End, After } /// /// Represents the bounds of a particular control /// #[derive(Clone, PartialEq, Debug)] pub struct AppBounds { pub x1: AppPosition, pub y1: AppPosition, pub x2: AppPosition, pub y2: AppPosition } /// /// Enumeration of possible actions that can be performed by a Cocoa application /// #[derive(Clone, PartialEq, Debug)] pub enum AppAction { /// Creates a new window with the specified ID CreateWindow(usize), /// Sends an action to a window Window(usize, WindowAction), /// Creates a new view of the specified type CreateView(usize, ViewType), /// Deletes the view with the specified ID DeleteView(usize), /// Performs an action on the specified view View(usize, ViewAction), /// Creates a viewmodel with a particular ID CreateViewModel(usize), /// Removes the viewmodel with the specified ID DeleteViewModel(usize), /// Performs an action on the specified view model ViewModel(usize, ViewModelAction) } /// /// Enumeration of possible actions that can be performed by a Cocoa Window /// #[derive(Clone, PartialEq, Debug)] pub enum WindowAction { /// Ensures that this window is displayed on screen Open, /// Sets the root view of the window to be the specified view SetRootView(usize), /// Requests a tick next time the user is given control of the application RequestTick, } /// /// Enumeration of possible actions that can be performed by a Cocoa View /// #[derive(Clone, PartialEq, Debug)] pub enum ViewAction { /// Requests a particular event type from this view RequestEvent(ViewEvent, String), /// Removes the view from its superview RemoveFromSuperview, /// Adds the view with the specified ID as a subview of this view AddSubView(usize), /// Inserts a new subview before an existing subview. The first argument is the view ID, the second is the index to add it at InsertSubView(usize, usize), /// Sets the bounds of the view for layout SetBounds(AppBounds), /// Sets the Z-Index of the view SetZIndex(f64), /// Sets the colour of any text or similar element the view might contain SetForegroundColor(Color), /// Sets the background colour of this view SetBackgroundColor(Color), /// Sets the text to display in a control SetText(AppProperty), /// Sets the image to display in a control SetImage(Resource<Image>), /// Sets the font size in pixels SetFontSize(f64), /// Sets the text alignment SetTextAlignment(TextAlign), /// Sets the font weight SetFontWeight(f64), /// Sets the minimum size of the scroll area (if the view is a scrolling type) SetScrollMinimumSize(f64, f64), /// Specifies the visibility of the horizontal scroll bar SetHorizontalScrollBar(ScrollBarVisibility), /// Specifies the visibility of the vertical scroll bar SetVerticalScrollBar(ScrollBarVisibility), /// Specifies the padding around the view SetPadding(f64, f64, f64, f64), /// Specifies whether or not the view should respond to clicks/pointer events SetClickThrough(bool), /// Sets the ID for this view SetId(String), /// Draws on the canvas for this view Draw(Vec<Draw>), /// Draws on the hardware-accellerated canvas for this view DrawGpu(Vec<Draw>), /// Sets part of the state of this view SetState(ViewStateUpdate), /// Performs an action that relates to a pop-up view Popup(ViewPopupAction) } /// /// Actions that update the state of the view (how it is displayed, or what it is displaying) /// #[derive(Clone, PartialEq, Debug)] pub enum ViewStateUpdate { /// Boolean indicating if this view is selected or not Selected(AppProperty), /// Boolean indicating if this view has a badge attached to it Badged(AppProperty), /// Boolean indicating if this view is enabled for interaction or greyed out Enabled(AppProperty), /// Property indicating the value for this view Value(AppProperty), /// Property indicating the range of valid values for this view Range(AppProperty, AppProperty), /// If this view is new, the priority with which to steal focus FocusPriority(AppProperty), /// Prevents this view from moving within a scroll view FixScrollAxis(FixedAxis), /// Sets the choices for the menus for this view MenuChoices(Vec<String>), /// Adds a class name to this view (used as a hint to change rendering styles) AddClass(String) } /// /// Actions relating to a pop-up view /// #[derive(Clone, PartialEq, Debug)] pub enum ViewPopupAction { /// Updates the property that specifies whether or not this popup is on screen or not Open(AppProperty), /// Sets the direction the popup is offset from the original view SetDirection(PopupDirection), /// Sets the size of the popup window in pixels SetSize(f64, f64), /// Sets the number of pixels betweem the popup and the center of the target view SetOffset(f64) } #[derive(Clone, Copy, PartialEq, Debug, FromPrimitive, ToPrimitive)] pub enum AppPaintDevice { MouseLeft = 0, MouseMiddle = 1, MouseRight = 2, Pen = 3, Eraser = 4, Touch = 5 } impl AppPaintDevice { /// /// Converts an AppPaintDevice into a UI paint device /// pub fn into_paint_device(&self) -> PaintDevice { match self { AppPaintDevice::MouseLeft => PaintDevice::Mouse(MouseButton::Left), AppPaintDevice::MouseMiddle => PaintDevice::Mouse(MouseButton::Middle), AppPaintDevice::MouseRight => PaintDevice::Mouse(MouseButton::Right), AppPaintDevice::Pen => PaintDevice::Pen, AppPaintDevice::Eraser => PaintDevice::Eraser, AppPaintDevice::Touch => PaintDevice::Touch } } } /// /// Events that can be requested from a view /// #[derive(Clone, PartialEq, Debug)] pub enum ViewEvent { /// User has clicked the control contained within this view Click, /// User has selected the menu option with the specified index (treated as a click event) ClickOption(usize), /// Send event when the user clicks in a view that's not either this view or a subview Dismiss, /// Send events when the view is scrolled, indicating which area is visible VirtualScroll(f64, f64), /// Send events for painting actions on this view Paint(AppPaintDevice), /// Send actions for dragging this view Drag, /// Send events when this view is focused Focused, /// Event sent when the value is being changed EditValue, /// Event sent when the value has been edited SetValue, /// Event sent when some EditValues were sent but the editing was cancelled CancelEdit, /// Event sent when the control's size has changed Resize, } /// /// Enumerationof possible actions for a viewmodel /// #[derive(Clone, PartialEq, Debug)] pub enum ViewModelAction { /// Creates a new viewmodel property with the specified ID CreateProperty(usize), /// Sets the value of a property to the specified value SetPropertyValue(usize, PropertyValue) }
true
a447faae286b21fe46e00c137e87c7937ed1649a
Rust
Alpvax/rust-aoc-2015
/src/bin/day6.rs
UTF-8
3,725
3.203125
3
[]
no_license
use rust_2015::read_lines; use fancy_regex::Regex; use std::collections::HashMap; fn main() { let pattern = Regex::new(r"(?:(?P<toggle>toggle)|turn (?:(?P<on>on)|(?P<off>off))) (?P<fx>\d+),(?P<fy>\d+) through (?P<tx>\d+),(?P<ty>\d+)").unwrap(); let mut map1: HashMap<CoOrd, bool> = HashMap::new(); let mut map2: HashMap<CoOrd, i32> = HashMap::new(); for ranged_op in read_lines("puzzle-input/6.0.txt", |s| s).map(|s| RangedOperation::new(&pattern, &s)) { ranged_op.apply_1(&mut map1); ranged_op.apply_2(&mut map2); } println!("{}", map1.values().filter(|b| **b).count()); println!("{}", map2.values().sum::<i32>()); //println!("{:?}", CoOrdRange::new(2, 3, 5, 4).iter().collect::<Vec<_>>()); /*println!("{:?}", RangedOperation::new(&pattern, "turn on 0,0 through 999,999")); println!("{:?}", RangedOperation::new(&pattern, "toggle 0,0 through 999,0")); println!("{:?}", RangedOperation::new(&pattern, "turn off 499,499 through 500,500"));*/ /*RangedOperation { op: Op::On, range: CoOrdRange::new(0, 0, 2, 2)}.apply(&mut map); println!("{:?}", map); RangedOperation { op: Op::Toggle, range: CoOrdRange::new(1, 1, 3, 2)}.apply(&mut map); println!("{:?}", map);*/ } #[derive(Debug)] struct RangedOperation { op: Op, range: CoOrdRange, } impl RangedOperation { fn new(pattern: &Regex, s: &str) -> RangedOperation { let captures = pattern.captures(s).expect("Regex parsing error").expect("No match found"); let op = if let Some(_) = captures.name("toggle") { Op::Toggle } else if let Some(_) = captures.name("on") { Op::On } else { Op::Off }; let range = CoOrdRange::new( captures.name("fx").unwrap().as_str().parse().unwrap(), captures.name("fy").unwrap().as_str().parse().unwrap(), captures.name("tx").unwrap().as_str().parse().unwrap(), captures.name("ty").unwrap().as_str().parse().unwrap(), ); RangedOperation { op, range } } fn apply_1(&self, map: &mut HashMap<CoOrd, bool>) { for c in self.range.iter() { let e = map.entry(c).or_insert(false); *e = match self.op { Op::On => true, Op::Off => false, Op::Toggle => !*e } } } fn apply_2(&self, map: &mut HashMap<CoOrd, i32>) { for c in self.range.iter() { let e = map.entry(c).or_insert(0); *e = std::cmp::max(0, *e + match self.op { Op::On => 1, Op::Off => -1, Op::Toggle => 2 }); } } } #[derive(Debug)] enum Op { On, Off, Toggle, } #[derive(Debug, Hash, Eq, PartialEq)] struct CoOrd { x: u32, y: u32, } #[derive(Debug)] struct CoOrdRange { from: CoOrd, to: CoOrd, } impl CoOrdRange { fn new(fx: u32, fy: u32, tx: u32, ty: u32) -> CoOrdRange { CoOrdRange { from: CoOrd { x: fx, y: fy }, to: CoOrd { x: tx, y: ty }, } } fn iter(&self) -> RangeIter { RangeIter { range: self, x: self.from.x, y: self.from.y, } } } struct RangeIter<'a> { range: &'a CoOrdRange, x: u32, y: u32, } impl<'a> Iterator for RangeIter<'a> { type Item = CoOrd; fn next(&mut self) -> Option<CoOrd> { let x = self.x; let y = self.y; if x < self.range.to.x { self.x += 1; } else { self.x = self.range.from.x; self.y += 1; } return if y > self.range.to.y { None } else { Some(CoOrd { x, y }) }; } }
true
d1dff7f6bf7e2ac8584274748e8c05d8f41e0e52
Rust
kenoss/frum
/src/commands/completions.rs
UTF-8
11,529
2.53125
3
[ "MIT" ]
permissive
use crate::cli::build_cli; use crate::command::Command; use crate::config::FrumConfig; use crate::outln; use crate::shell::{infer_shell, AVAILABLE_SHELLS}; use crate::version::{is_dotfile, Version}; use clap::Shell; use thiserror::Error; const USE_COMMAND_REGEX: &str = r#"opts=" -h -V --help --version "#; const INSTALL_COMMAND_REGEX: &str = r#"opts=" -l -h -V --list --help --version "#; const UNINSTALL_COMMAND_REGEX: &str = r#"opts=" -h -V --help --version "#; const LOCAL_COMMAND_REGEX: &str = r#"opts=" -h -V --help --version "#; #[derive(Debug)] enum FrumCommand { Install, Uninstall, Local, Global, None, } #[derive(Error, Debug)] pub enum FrumError { #[error( "{}\n{}\n{}\n{}", "Can't infer shell!", "frum can't infer your shell based on the process tree.", "Maybe it is unsupported? we support the following shells:", shells_as_string() )] CantInferShell, #[error(transparent)] IoError(#[from] std::io::Error), #[error(transparent)] SemverError(#[from] semver::SemVerError), } pub struct Completions { pub shell: Option<Shell>, pub list: bool, } impl Command for Completions { type Error = FrumError; fn apply(&self, config: &FrumConfig) -> Result<(), Self::Error> { if self.list { for entry in config .versions_dir() .read_dir() .map_err(FrumError::IoError)? { let entry = entry.map_err(FrumError::IoError)?; if is_dotfile(&entry) { continue; } let path = entry.path(); let filename = path .file_name() .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound)) .map_err(FrumError::IoError)? .to_str() .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound)) .map_err(FrumError::IoError)?; let version = Version::parse(filename).map_err(FrumError::SemverError)?; outln!(config#Info, "{} {}", " ", version); } return Ok(()); } let shell = self .shell .or_else(|| infer_shell().map(Into::into)) .ok_or(FrumError::CantInferShell)?; print!("{}", customize_completions(shell)); Ok(()) } } fn customize_completions(shell: Shell) -> String { let mut buffer = Vec::new(); build_cli().gen_completions_to(env!("CARGO_PKG_NAME"), shell, &mut buffer); let string = String::from_utf8(buffer).unwrap(); let string_split = string.split('\n'); let mut completions = String::new(); let mut subcommand = FrumCommand::None; let use_command_regex = regex::Regex::new(format!(r#"(\s+){}{} "#, USE_COMMAND_REGEX, "<version>").as_str()) .unwrap(); let install_command_regex = regex::Regex::new(format!(r#"(\s+){}{} "#, INSTALL_COMMAND_REGEX, "<version>").as_str()) .unwrap(); let uninstall_command_regex = regex::Regex::new(format!(r#"(\s+){}{} "#, UNINSTALL_COMMAND_REGEX, "<version>").as_str()) .unwrap(); let local_command_regex = regex::Regex::new(format!(r#"(\s+){}{} "#, LOCAL_COMMAND_REGEX, "<version>").as_str()) .unwrap(); match shell { Shell::Zsh => { for (index, line) in string_split.clone().enumerate() { if index == string_split.clone().count() - 1 { break; } subcommand = match line { "(local)" => FrumCommand::Local, "(global)" => FrumCommand::Global, "(install)" => FrumCommand::Install, "(uninstall)" => FrumCommand::Uninstall, _ => subcommand, }; completions.push_str( format!( "{}\n", match subcommand { FrumCommand::Local => match line { "(local)" => r#"(local) if [ "$(frum completions --list)" != '' ]; then local_args='::version:_values 'version' $(frum completions --list)' else local_args='--version[Prints version information]' fi"# .to_string(), r#"'::version:_files' \"# => r#""${local_args}" \"#.to_string(), _ => line.to_string(), }, FrumCommand::Global => match line { r#"':version:_files' \"# => r#"':version:_values 'version' $(frum completions --list)' \"# .to_string(), _ => line.to_string(), }, FrumCommand::Install => match line { r#"'::configure_opts -- Options passed to ./configure:_files' \"# => continue, r#"'::version:_files' \"# => r#"'::version:_values 'version' $(frum install -l)' \"# .to_string(), _ => line.to_string(), }, FrumCommand::Uninstall => match line { r#"':version:_files' \"# => r#"':version:_values 'version' $(frum completions --list)' \"# .to_string(), _ => line.to_string(), }, FrumCommand::None => line.to_string(), } ) .as_str(), ); } completions } Shell::Bash => { for (index, line) in string_split.clone().enumerate() { if index == string_split.clone().count() - 1 { break; } subcommand = if line.ends_with("frum__local)") { FrumCommand::Local } else if line.ends_with("frum__global)") { FrumCommand::Global } else if line.ends_with("frum__install)") { FrumCommand::Install } else if line.ends_with("frum__uninstall)") { FrumCommand::Uninstall } else { subcommand }; completions.push_str( format!( "{}\n", match subcommand { FrumCommand::Local => if local_command_regex.is_match(line) { format!( r#"{}{}$(frum completions --list) ""#, local_command_regex .captures(line) .unwrap() .get(1) .unwrap() .as_str(), LOCAL_COMMAND_REGEX ) } else { line.to_string() }, FrumCommand::Global => if use_command_regex.is_match(line) { format!( r#"{}{}$(frum completions --list) ""#, use_command_regex .captures(line) .unwrap() .get(1) .unwrap() .as_str(), USE_COMMAND_REGEX ) } else { line.to_string() }, FrumCommand::Install => if install_command_regex.is_match(line) { format!( r#"{}{}$(frum install -l) ""#, install_command_regex .captures(line) .unwrap() .get(1) .unwrap() .as_str(), INSTALL_COMMAND_REGEX ) } else { line.to_string() }, FrumCommand::Uninstall => if uninstall_command_regex.is_match(line) { format!( r#"{}{}$(frum completions --list) ""#, uninstall_command_regex .captures(line) .unwrap() .get(1) .unwrap() .as_str(), UNINSTALL_COMMAND_REGEX ) } else { line.to_string() }, FrumCommand::None => line.to_string(), } ) .as_str(), ); } completions } _ => string, } } fn shells_as_string() -> String { AVAILABLE_SHELLS .iter() .map(|x| format!("* {}", x)) .collect::<Vec<_>>() .join("\n") } #[cfg(test)] mod test { use super::customize_completions; use clap::Shell; use difference::assert_diff; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; #[test] fn test_zsh_completions() { let file = File::open("completions/frum.zsh").unwrap(); let mut buf_reader = BufReader::new(file); let mut expected = String::new(); buf_reader.read_to_string(&mut expected).unwrap(); let actual = customize_completions(Shell::Zsh); assert_diff!(actual.as_str(), expected.as_str(), "\n", 0); } #[test] fn test_bash_completions() { let file = File::open("completions/frum.bash").unwrap(); let mut buf_reader = BufReader::new(file); let mut expected = String::new(); buf_reader.read_to_string(&mut expected).unwrap(); let actual = customize_completions(Shell::Bash); assert_diff!(actual.as_str(), expected.as_str(), "\n", 0); } }
true
15868ca87c8cd504fa1f5fdcae2ae78d950d6135
Rust
cmaves/rustbus
/rustbus_derive_test/src/lib.rs
UTF-8
1,926
2.796875
3
[ "MIT" ]
permissive
#[test] fn test_derive() { use rustbus::message_builder::MessageBuilder; use rustbus_derive::{Marshal, Signature, Unmarshal}; #[derive(Marshal, Unmarshal, Signature, Default, Debug, Eq, PartialEq)] struct A { y: u32, x: u64, strct: (u8, u8, String), raw_data: Vec<u8>, sub: SubTypeA, } #[derive(Marshal, Unmarshal, Signature, Default, Debug, Eq, PartialEq)] struct SubTypeA { x: u8, y: u16, z: u32, w: u64, s: String, } #[derive(Marshal, Unmarshal, Signature, Default, Debug, Eq, PartialEq)] struct B<'a> { y: u32, x: u64, strct: (u8, u8, &'a str), raw_data: &'a [u8], sub: SubTypeB<'a>, } #[derive(Marshal, Unmarshal, Signature, Default, Debug, Eq, PartialEq)] struct SubTypeB<'a> { x: u8, y: u16, z: u32, w: u64, s: &'a str, } let a = A { y: 0xAAAAAAAA, x: 0xBBBBBBBBBBBBBBBB, strct: (1, 2, "ABCD".into()), raw_data: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0], sub: SubTypeA { x: 0, y: 1, z: 3, w: 4, s: "AA".into(), }, }; // create a signal with the MessageBuilder API let mut sig = MessageBuilder::new() .signal("io.killing.spark", "TestSignal", "/io/killing/spark") .build(); // add a parameter to the signal sig.body.push_param(&a).unwrap(); assert_eq!(a, sig.body.parser().get::<A>().unwrap()); let b = B { x: a.x, y: a.y, raw_data: &a.raw_data, strct: (a.strct.0, a.strct.1, &a.strct.2), sub: SubTypeB { x: a.sub.x, y: a.sub.y, z: a.sub.z, w: a.sub.w, s: &a.sub.s, }, }; assert_eq!(b, sig.body.parser().get::<B>().unwrap()); }
true
c53468ec489512e652786e0f7e16a3eed8ce8ef7
Rust
dimes/violetta
/src/entities/mod.rs
UTF-8
789
3.0625
3
[]
no_license
use components::Component; use std::any::Any; use std::collections::HashMap; #[derive(Debug)] pub struct Entity { id: u64, components: HashMap<&'static str, Box<Any>>, } impl Entity { pub fn new(id: u64) -> Entity { return Entity { id: id, components: HashMap::new(), }; } pub fn get_component<T: Component + Any>(&mut self, name: &'static str) -> Option<&mut T> { let component = self.components.get_mut(name); match component { Some(component) => component.as_mut().downcast_mut(), None => None, } } pub fn set_component<T: Component + Any>(&mut self, component: Box<T>) { self.components .insert(component.name(), component as Box<Any>); } }
true
40661d120e5d39e726bca669a56ce561f9ab442d
Rust
viechang/TimeClue
/src/main.rs
UTF-8
523
3.109375
3
[]
no_license
#[macro_use] extern crate lazy_static; fn say_what(name: &str, func: fn(&str)) { func(name); } fn test(string: &str) { println!("{}", string); } fn foo(_: &str) { println!("foobar."); } lazy_static!{ static ref VEC: Vec<(&'static str, fn(&str))> = vec![ ("Hello, Rust!", test), ("null", foo) ]; } fn main() { // let vec: Vec<(&str, fn(&str))> = vec![ // ("Hello, Rust!", test), // ("null", foo) // ]; for i in VEC.iter() { say_what(i.0, i.1); } }
true
171aca2a8e5edb06f0a14f5e129444df3204132f
Rust
klausklemens/render_frog
/src/util/color.rs
UTF-8
309
3.140625
3
[]
no_license
pub struct ColorRGB { pub r: u8, pub g: u8, pub b: u8, } impl ColorRGB { pub fn new(r: u8, g: u8, b: u8) -> ColorRGB { ColorRGB { r, g, b, } } pub fn clone(&self) -> ColorRGB { ColorRGB::new(self.r, self.g, self.b) } }
true
17fbc73f53a814932b35e1945522492e1888206c
Rust
redox-os/pkgar
/pkgar-keys/src/lib.rs
UTF-8
13,280
2.546875
3
[ "MIT" ]
permissive
mod error; use std::fs::{self, File, OpenOptions}; use std::io::{self, stdin, stdout, Write}; use std::ops::Deref; use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use error_chain::bail; use hex::FromHex; use lazy_static::lazy_static; use seckey::SecBytes; use serde::{Deserialize, Serialize}; use sodiumoxide::crypto::{ pwhash, secretbox, sign, }; use termion::input::TermRead; pub use crate::error::{ErrorKind, Error, ResultExt}; lazy_static! { static ref HOMEDIR: PathBuf = { dirs::home_dir() .unwrap_or("./".into()) }; /// The default location for pkgar to look for the user's public key. /// /// Defaults to `$HOME/.pkgar/keys/id_ed25519.pub.toml`. If `$HOME` is /// unset, `./.pkgar/keys/id_ed25519.pub.toml`. pub static ref DEFAULT_PUBKEY: PathBuf = { Path::join(&HOMEDIR, ".pkgar/keys/id_ed25519.pub.toml") }; /// The default location for pkgar to look for the user's secret key. /// /// Defaults to `$HOME/.pkgar/keys/id_ed25519.toml`. If `$HOME` is unset, /// `./.pkgar/keys/id_ed25519.toml`. pub static ref DEFAULT_SECKEY: PathBuf = { Path::join(&HOMEDIR, ".pkgar/keys/id_ed25519.toml") }; } mod ser { use hex::FromHex; use serde::{Deserialize, Deserializer}; use serde::de::Error; use sodiumoxide::crypto::{pwhash, secretbox, sign}; //TODO: Macro? pub(crate) fn to_salt<'d, D: Deserializer<'d>>(deser: D) -> Result<pwhash::Salt, D::Error> { String::deserialize(deser) .and_then(|s| <[u8; 32]>::from_hex(s) .map(|val| pwhash::Salt(val) ) .map_err(|err| Error::custom(err.to_string()) ) ) } pub(crate) fn to_nonce<'d, D: Deserializer<'d>>(deser: D) -> Result<secretbox::Nonce, D::Error> { String::deserialize(deser) .and_then(|s| <[u8; 24]>::from_hex(s) .map(|val| secretbox::Nonce(val) ) .map_err(|err| Error::custom(err.to_string()) ) ) } pub(crate) fn to_pubkey<'d, D: Deserializer<'d>>(deser: D) -> Result<sign::PublicKey, D::Error> { String::deserialize(deser) .and_then(|s| <[u8; 32]>::from_hex(s) .map(|val| sign::PublicKey(val) ) .map_err(|err| Error::custom(err.to_string()) ) ) } } /// Standard pkgar public key format definition. Use serde to serialize/deserialize /// files into this struct (helper methods available). #[derive(Deserialize, Serialize)] pub struct PublicKeyFile { #[serde(serialize_with = "hex::serialize", deserialize_with = "ser::to_pubkey")] pub pkey: sign::PublicKey, } impl PublicKeyFile { /// Parse a `PublicKeyFile` from `file` (in toml format). pub fn open(file: impl AsRef<Path>) -> Result<PublicKeyFile, Error> { let content = fs::read_to_string(&file) .chain_err(|| file.as_ref() )?; toml::from_str(&content) .chain_err(|| file.as_ref() ) } /// Write `self` serialized as toml to `w`. pub fn write(&self, mut w: impl Write) -> Result<(), Error> { w.write_all(toml::to_string(self)?.as_bytes())?; Ok(()) } /// Shortcut to write the public key to `file` pub fn save(&self, file: impl AsRef<Path>) -> Result<(), Error> { self.write( File::create(&file) .chain_err(|| file.as_ref() )? ).chain_err(|| file.as_ref() ) } } enum SKey { Cipher([u8; 80]), Plain(sign::SecretKey), } impl SKey { fn encrypt(&mut self, passwd: Passwd, salt: pwhash::Salt, nonce: secretbox::Nonce) { if let SKey::Plain(skey) = self { if let Some(passwd_key) = passwd.gen_key(salt) { let mut buf = [0; 80]; buf.copy_from_slice(&secretbox::seal(skey.as_ref(), &nonce, &passwd_key)); *self = SKey::Cipher(buf); } } } fn decrypt(&mut self, passwd: Passwd, salt: pwhash::Salt, nonce: secretbox::Nonce) -> Result<(), Error> { if let SKey::Cipher(ciphertext) = self { if let Some(passwd_key) = passwd.gen_key(salt) { let skey_plain = secretbox::open(ciphertext.as_ref(), &nonce, &passwd_key) .map_err(|_| ErrorKind::PassphraseIncorrect )?; *self = SKey::Plain(sign::SecretKey::from_slice(&skey_plain) .ok_or(ErrorKind::KeyInvalid)?); } else { *self = SKey::Plain(sign::SecretKey::from_slice(&ciphertext[..64]) .ok_or(ErrorKind::KeyInvalid)?); } } Ok(()) } /// Returns `None` if encrypted fn skey(&self) -> Option<sign::SecretKey> { match &self { SKey::Plain(skey) => Some(skey.clone()), SKey::Cipher(_) => None, } } } impl AsRef<[u8]> for SKey { fn as_ref(&self) -> &[u8] { match self { SKey::Cipher(buf) => buf.as_ref(), SKey::Plain(skey) => skey.as_ref(), } } } impl FromHex for SKey { type Error = hex::FromHexError; fn from_hex<T: AsRef<[u8]>>(buf: T) -> Result<SKey, hex::FromHexError> { let bytes = hex::decode(buf)?; // Public key is only 64 bytes... if bytes.len() == 64 { Ok(SKey::Plain(sign::SecretKey::from_slice(&bytes) .expect("Somehow not the right number of bytes"))) } else { let mut buf = [0; 80]; buf.copy_from_slice(&bytes); Ok(SKey::Cipher(buf)) } } } /// Standard pkgar private key format definition. Use serde. /// Internally, this struct stores the encrypted state of the private key as an enum. /// Manipulate the state using the `encrypt()`, `decrypt()` and `is_encrypted()`. #[derive(Deserialize, Serialize)] pub struct SecretKeyFile { #[serde(serialize_with = "hex::serialize", deserialize_with = "ser::to_salt")] salt: pwhash::Salt, #[serde(serialize_with = "hex::serialize", deserialize_with = "ser::to_nonce")] nonce: secretbox::Nonce, #[serde(with = "hex")] skey: SKey, } impl SecretKeyFile { /// Generate a keypair with all the nessesary info to save both keys. You /// must call `save()` on each object to persist them to disk. pub fn new() -> (PublicKeyFile, SecretKeyFile) { let (pkey, skey) = sign::gen_keypair(); let pkey_file = PublicKeyFile { pkey }; let skey_file = SecretKeyFile { salt: pwhash::gen_salt(), nonce: secretbox::gen_nonce(), skey: SKey::Plain(skey), }; (pkey_file, skey_file) } /// Parse a `SecretKeyFile` from `file` (in toml format). pub fn open(file: impl AsRef<Path>) -> Result<SecretKeyFile, Error> { let content = fs::read_to_string(&file) .chain_err(|| file.as_ref() )?; toml::from_str(&content) .chain_err(|| file.as_ref() ) } /// Write `self` serialized as toml to `w`. pub fn write(&self, mut w: impl Write) -> Result<(), Error> { w.write_all(toml::to_string(&self)?.as_bytes())?; Ok(()) } /// Shortcut to write the secret key to `file`. /// /// Make sure to call `encrypt()` in order to encrypt /// the private key, otherwise it will be stored as plain text. pub fn save(&self, file: impl AsRef<Path>) -> Result<(), Error> { self.write( OpenOptions::new() .write(true) .create(true) .mode(0o600) .open(&file) .chain_err(|| file.as_ref() )? ).chain_err(|| file.as_ref() ) } /// Ensure that the internal state of this struct is encrypted. /// Note that if passwd is empty, this function is a no-op. pub fn encrypt(&mut self, passwd: Passwd) { self.skey.encrypt(passwd, self.salt, self.nonce) } /// Ensure that the internal state of this struct is decrypted. /// If the internal state is already decrypted, this function is a no-op. pub fn decrypt(&mut self, passwd: Passwd) -> Result<(), Error> { self.skey.decrypt(passwd, self.salt, self.nonce) } /// Status of the internal state. pub fn is_encrypted(&self) -> bool { match self.skey { SKey::Cipher(_) => true, SKey::Plain(_) => false, } } /// Returns `None` if the secret key is encrypted. pub fn key(&mut self) -> Option<sign::SecretKey> { match &self.skey { SKey::Plain(skey) => Some(skey.clone()), SKey::Cipher(_) => None, } } /// Returns `None` if the secret key is encrypted. pub fn public_key_file(&self) -> Option<PublicKeyFile> { Some(PublicKeyFile { pkey: self.skey.skey()?.public_key(), }) } } /// Secure in-memory representation of a password. pub struct Passwd { bytes: SecBytes, } impl Passwd { /// Create a new `Passwd` and zero the old string. pub fn new(passwd: &mut String) -> Passwd { let pwd = Passwd { bytes :SecBytes::with( passwd.len(), |buf| buf.copy_from_slice(passwd.as_bytes()) ), }; unsafe { seckey::zero(passwd.as_bytes_mut()); } pwd } /// Prompt the user for a `Passwd` on stdin. pub fn prompt(prompt: impl AsRef<str>) -> Result<Passwd, Error> { let stdout = stdout(); let mut stdout = stdout.lock(); let stdin = stdin(); let mut stdin = stdin.lock(); stdout.write_all(prompt.as_ref().as_bytes())?; stdout.flush()?; let mut passwd = stdin.read_passwd(&mut stdout)? .ok_or(ErrorKind::Io( io::Error::new( io::ErrorKind::UnexpectedEof, "Invalid Password Input", ) ))?; println!(); Ok(Passwd::new(&mut passwd)) } /// Prompt for a password on stdin and confirm it. For configurable /// prompts, use [`Passwd::prompt`](struct.Passwd.html#method.prompt). pub fn prompt_new() -> Result<Passwd, Error> { let passwd = Passwd::prompt( "Please enter a new passphrase (leave empty to store the key in plaintext): " )?; let confirm = Passwd::prompt("Please re-enter the passphrase: ")?; if passwd != confirm { bail!(ErrorKind::PassphraseMismatch); } Ok(passwd) } /// Get a key for symmetric key encryption from a password. fn gen_key(&self, salt: pwhash::Salt) -> Option<secretbox::Key> { if self.bytes.read().len() > 0 { let mut key = secretbox::Key([0; secretbox::KEYBYTES]); let secretbox::Key(ref mut binary_key) = key; pwhash::derive_key( binary_key, &self.bytes.read(), &salt, pwhash::OPSLIMIT_INTERACTIVE, pwhash::MEMLIMIT_INTERACTIVE, ).expect("Failed to get key from password"); Some(key) } else { None } } } impl PartialEq for Passwd { fn eq(&self, other: &Passwd) -> bool { self.bytes.read().deref() == other.bytes.read().deref() } } impl Eq for Passwd {} /// Generate a new keypair. The new keys will be saved to `file`. The user /// will be prompted on stdin for a password, empty passwords will cause the /// secret key to be stored in plain text. Note that parent /// directories will not be created. pub fn gen_keypair(pkey_path: &Path, skey_path: &Path) -> Result<(PublicKeyFile, SecretKeyFile), Error> { let passwd = Passwd::prompt_new() .chain_err(|| skey_path )?; let (pkey_file, mut skey_file) = SecretKeyFile::new(); skey_file.encrypt(passwd); skey_file.save(skey_path)?; pkey_file.save(pkey_path)?; println!("Generated {} and {}", pkey_path.display(), skey_path.display()); Ok((pkey_file, skey_file)) } fn prompt_skey(skey_path: &Path, prompt: impl AsRef<str>) -> Result<SecretKeyFile, Error> { let mut key_file = SecretKeyFile::open(skey_path)?; if key_file.is_encrypted() { let passwd = Passwd::prompt(&format!("{} {}: ", prompt.as_ref(), skey_path.display())) .chain_err(|| skey_path )?; key_file.decrypt(passwd) .chain_err(|| skey_path )?; } Ok(key_file) } /// Get a SecretKeyFile from a path. If the file is encrypted, prompt for a password on stdin. pub fn get_skey(skey_path: &Path) -> Result<SecretKeyFile, Error> { prompt_skey(skey_path, "Passphrase for") } /// Open, decrypt, re-encrypt with a different passphrase from stdin, and save the newly encrypted /// secret key at `skey_path`. pub fn re_encrypt(skey_path: &Path) -> Result<(), Error> { let mut skey_file = prompt_skey(skey_path, "Old passphrase for")?; let passwd = Passwd::prompt_new() .chain_err(|| skey_path )?; skey_file.encrypt(passwd); skey_file.save(skey_path) }
true
a2d19a89cab1140e68bc47a44600a81803745bf2
Rust
teddyzhu/clobber
/src/tcp.rs
UTF-8
10,415
3.171875
3
[ "MIT" ]
permissive
//! # TCP handling //! //! This file contains the TCP handling for `clobber`. The loop here is that we connect, write, //! and then read. If the client is in repeat mode then it will repeatedly write/read while the //! connection is open. //! //! ## Performance Notes //! //! ### Perform allocations at startup //! //! The pool of connections is created up front, and then connections begin sending requests //! to match the defined rate. (Or in the case of no defined, they start immediately.) In general //! we try to to limit significant allocations to startup rather than doing them on the fly. //! More specifically, you shouldn't see any of these behaviors inside the tight `while` loop //! inside the `connection()` method. //! //! ### Limit open ports and files //! //! Two of the key limiting factors for high TCP client throughput are running out of ports, or //! opening more files than the underlying OS will allow. `clobber` tries to minimize issues here //! by giving users control over the max connections. (It's also a good idea to check out your //! specific `ulimit -n` settings and raise the max number of open files.) //! //! #### Avoid cross-thread communication //! This library uses no cross-thread communication via `std::sync` or `crossbeam`. All futures //! are executed on a `LocalPool`, and the number of OS threads used is user configurable. This //! has a number of design impacts. For example, it becomes more difficult to aggregate what each //! connection is doing. This is simple if you just pass the results to a channel, but this has a //! non-trivial impact on performance. //! //! *Note: This is currently violated by the way we accomplish rate limiting, which relies on a //! global thread that manages timers. This ends up putting disproportionate load on that thread at //! some point. But if you're relying on rate limiting you're trying to slow it down, so we're //! putting this in the 'feature' column. (If anyone would like to contribute a thread-local //! futures timer it'd be a great contribution to the Rust community!) //! use std::net::SocketAddr; use std::time::Instant; use async_std::io::{self}; use async_std::net::{TcpStream}; use async_std::prelude::*; // I'd like to remove this dependency, but async-std doesn't currently have a LocalPool executor // todo: Revisit use futures::executor::LocalPool; use futures::task::SpawnExt; use futures_timer::Delay; use log::{debug, error, info, warn}; use crate::{Config}; use byte_mutator::ByteMutator; use byte_mutator::fuzz_config::FuzzConfig; /// The overall test runner /// /// This method contains the main core loop. /// /// `clobber` will create `connections` number of async futures, distribute them across `threads` /// threads (defaults to num_cpus), and each future will perform requests in a tight loop. If /// there is a `rate` specified, there will be an optional delay to stay under the requested rate. /// The futures are driven by a LocalPool executor, and there is no cross-thread synchronization /// or communication with the default config. Note: for maximum performance avoid use of the /// `rate`, `connect_timeout`, and `read_timeout` options. /// pub fn clobber(config: Config, message: Vec<u8>) -> std::io::Result<()> { info!("Starting: {:#?}", config); let mut threads = Vec::with_capacity(config.num_threads() as usize); // configure fuzzing if a file has been provided in the config let message = match &config.fuzz_path { None => ByteMutator::new(&message), Some(path) => { match FuzzConfig::from_file(&path) { Ok(fuzz_config) => ByteMutator::new_from_config(&message, fuzz_config), Err(e) => { return Err(e) }, } }, }; for _ in 0..config.num_threads() { // per-thread clones let message = message.clone(); let config = config.clone(); // start OS thread which will contain a chunk of connections let thread = std::thread::spawn(move || { let mut pool = LocalPool::new(); let mut spawner = pool.spawner(); // all connection futures are spawned up front for i in 0..config.connections_per_thread() { // per-connection clones let message = message.clone(); let config = config.clone(); spawner .spawn(async move { if config.rate.is_some() { Delay::new(i * config.connection_delay()); } connection(message, config) .await .expect("Failed to run connection"); }).unwrap(); } pool.run(); }); threads.push(thread); } for handle in threads { handle.join().unwrap(); } Ok(()) } /// Handles a single connection /// /// This method infinitely loops, performing a connect/write/read transaction against the /// configured target. If `repeat` is true in `config`, the loop will keep the connection alive. /// Otherwise, it will drop the connection after successfully completing a read, and then it will /// start over and reconnect. If it does not successfully read, it will block until the underlying /// TCP read fails unless `read-timeout` is configured. /// /// This is a long-running function that will continue making calls until it hits a time or total /// loop count limit. /// /// todo: This ignores both read-timeout and repeat async fn connection(mut message: ByteMutator, config: Config) -> io::Result<()> { let start = Instant::now(); let mut count = 0; let mut loop_complete = |config:&Config| { count += 1; if let Some(duration) = config.duration { if Instant::now() >= start + duration { return true; } } if let Some(limit) = config.limit_per_connection() { if count > limit { return true; } } false }; let should_delay = |elapsed, config: &Config| { match config.rate { Some(_) => { if elapsed < config.connection_delay() { true } else { warn!("running behind; consider adding more connections"); false } } None => false, } }; // This is the guts of the application; the tight loop that executes requests let mut read_buffer = [0u8; 1024]; // todo variable size? :( while !loop_complete(&config) { // todo: add optional timeouts back let request_start = Instant::now(); if let Ok(mut stream) = connect(&config.target).await { // one write/read transaction per repeat for _ in 0..config.repeat { if write(&mut stream, message.read()).await.is_ok() { read(&mut stream, &mut read_buffer).await.ok(); } } // todo: analysis // advance mutator state (no-op with no fuzzer config) message.next(); } if config.rate.is_some() { let elapsed = Instant::now() - request_start; if should_delay(elapsed, &config) { Delay::new(config.connection_delay() - elapsed) .await .unwrap(); } } } Ok(()) } /// Connects to the provided address, logs, returns Result<TcpStream, io::Error> async fn connect(addr: &SocketAddr) -> io::Result<TcpStream> { match TcpStream::connect(addr).await { Ok(stream) => { debug!("connected to {}", addr); Ok(stream) } Err(e) => { if e.kind() != io::ErrorKind::TimedOut { error!("unknown connect error: '{}'", e); } Err(e) } } } /// Writes provided buffer to the provided address, logs, returns Result<bytes_written, io::Error> async fn write(stream: &mut TcpStream, buf: &[u8]) -> io::Result<usize> { match stream.write_all(buf).await { Ok(_) => { let n = buf.len(); debug!("{} bytes written", n); Ok(n) } Err(e) => { error!("write error: '{}'", e); Err(e) } } } /// Reads from stream, logs, returns Result<num_bytes_read, io::Error> async fn read(stream: &mut TcpStream, mut read_buffer: &mut [u8]) -> io::Result<usize> { match stream.read(&mut read_buffer).await { Ok(n) => { debug!("{} bytes read ", n); Ok(n) } Err(e) => { error!("read error: '{}'", e); Err(e) } } // todo: Do something with the read_buffer? // todo: More verbose logging; dump to stdout, do post-run analysis on demand } #[cfg(test)] mod tests { use super::*; use crate::server::echo_server; #[test] fn test_connect() { let result = async_std::task::block_on(async { let addr = echo_server().unwrap(); let result = connect(&addr).await; result }); assert!(result.is_ok()); } #[test] fn test_write() { let addr = echo_server().unwrap(); let input = "test".as_bytes(); let want = input.len(); let result = async_std::task::block_on(async move { let mut stream = connect(&addr).await?; let bytes_written = write(&mut stream, &input).await?; Ok::<_, io::Error>(bytes_written) }); assert!(result.is_ok()); assert_eq!(result.unwrap(), want); } #[test] fn test_read() { let addr = echo_server().unwrap(); let input = "test\n\r\n".as_bytes(); let want = input.len(); let result = async_std::task::block_on(async move { let mut stream = connect(&addr).await?; let mut read_buffer = [0u8; 1024]; let _ = write(&mut stream, &input).await?; let bytes_read = read(&mut stream, &mut read_buffer).await?; Ok::<_, io::Error>(bytes_read) }); assert!(result.is_ok()); assert_eq!(want, result.unwrap()); } }
true
9e2d664427a4944608af856527c194b958118494
Rust
k-start/untitled_os
/src/keyboard.rs
UTF-8
824
2.640625
3
[]
no_license
use crate::print; use lazy_static::lazy_static; use pc_keyboard::{layouts, DecodedKey, HandleControl, ScancodeSet1}; use spin::Mutex; lazy_static! { static ref KEYBOARD: Mutex<pc_keyboard::Keyboard<layouts::Us104Key, ScancodeSet1>> = Mutex::new( pc_keyboard::Keyboard::new(layouts::Us104Key, ScancodeSet1, HandleControl::Ignore) ); } pub fn key_pressed() { let mut keyboard = KEYBOARD.lock(); let scancode = crate::inb(0x60); if let Ok(Some(key_event)) = keyboard.add_byte(scancode) { if let Some(key) = keyboard.process_keyevent(key_event) { match key { DecodedKey::Unicode(character) => print!("{}", character), // DecodedKey::RawKey(key) => print!("{:?}", key), DecodedKey::RawKey(_) => {} } } } }
true
3c436d090197fb29c39d7461cbac3a1b94705709
Rust
bottlerocket-os/bottlerocket
/tools/pubsys/src/aws/mod.rs
UTF-8
1,144
2.546875
3
[ "Apache-2.0", "MIT" ]
permissive
use aws_sdk_ec2::config::Region; use aws_sdk_ec2::types::ArchitectureValues; #[macro_use] pub(crate) mod client; pub(crate) mod ami; pub(crate) mod promote_ssm; pub(crate) mod publish_ami; pub(crate) mod ssm; pub(crate) mod validate_ami; pub(crate) mod validate_ssm; /// Builds a Region from the given region name. fn region_from_string(name: &str) -> Region { Region::new(name.to_owned()) } /// Parses the given string as an architecture, mapping values to the ones used in EC2. pub(crate) fn parse_arch(input: &str) -> Result<ArchitectureValues> { match input { "x86_64" | "amd64" => Ok(ArchitectureValues::X8664), "arm64" | "aarch64" => Ok(ArchitectureValues::Arm64), _ => error::ParseArchSnafu { input, msg: "unknown architecture", } .fail(), } } mod error { use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(super)))] pub(crate) enum Error { #[snafu(display("Failed to parse arch '{}': {}", input, msg))] ParseArch { input: String, msg: String }, } } type Result<T> = std::result::Result<T, error::Error>;
true
ec0279a404025635dd074621246d39d799ae535f
Rust
veer66/khatson
/chawuek/src/lib.rs
UTF-8
4,010
2.78125
3
[ "Apache-2.0", "MIT" ]
permissive
use anyhow::Result; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::path::Path; use tch::jit::IValue; use tch::CModule; use tch::Tensor; use thiserror::Error; #[allow(dead_code)] pub fn cargo_dir() -> &'static Path { Path::new(env!("CARGO_MANIFEST_DIR")) } #[derive(Error, Debug)] pub enum ChawuekError { #[error("Cannot open the character map file")] CannotOpenCharMapFile, #[error("Cannot parse the character map")] CannotParseCharMapFile, #[error("Cannot find special symbol `{0}` in the character map")] CannotFindSpecialSymbolInCharMap(String), #[error("Cannot get character from string `{0}`")] CannotCharFromString(String), #[error("The module returned an invalid value.")] ModuleReturnedAnInvalidValue, } #[derive(Debug)] struct CharToXi { punc_i: i64, unk_i: i64, pad_i: i64, char_ix_map: HashMap<char, i64>, } impl CharToXi { fn get_special_symbol(imm: &HashMap<String, i64>, sym: &str) -> Result<i64> { Ok(*imm .get(sym) .ok_or_else(|| ChawuekError::CannotFindSpecialSymbolInCharMap(sym.to_owned()))?) } pub fn load_char_map() -> Result<CharToXi> { let char_map_path = Path::new(concat!( env!("CARGO_MANIFEST_DIR"), "/data/attacut-c/characters.json" )); let f = File::open(char_map_path).map_err(|_| ChawuekError::CannotOpenCharMapFile)?; let reader = BufReader::new(f); let imm: HashMap<String, i64> = serde_json::from_reader(reader).map_err(|_| ChawuekError::CannotParseCharMapFile)?; let punc_i = Self::get_special_symbol(&imm, "<PUNC>")?; let pad_i = Self::get_special_symbol(&imm, "<PAD>")?; let unk_i = Self::get_special_symbol(&imm, "<UNK>")?; let mut char_ix_map: HashMap<char, i64> = HashMap::new(); for (k, v) in imm { let k: Vec<char> = k.chars().collect(); if k.len() == 1 { char_ix_map.insert(k[0], v); } } Ok(CharToXi { punc_i, pad_i, unk_i, char_ix_map, }) } pub fn to_xi(&self, ch: &char) -> i64 { if ch.is_ascii_punctuation() { self.punc_i } else { *self.char_ix_map.get(ch).unwrap_or(&self.unk_i) } } } pub struct Chawuek { model: CModule, char_to_xi: CharToXi, } impl Chawuek { pub fn new() -> Result<Chawuek> { let model_path = Path::new(concat!( env!("CARGO_MANIFEST_DIR"), "/data/attacut-c/model.pt" )); let model = CModule::load(model_path)?; let char_to_xi = CharToXi::load_char_map()?; Ok(Chawuek { model, char_to_xi }) } pub fn tokenize(&self, txt: &str) -> Result<Vec<String>> { let chars: Vec<char> = txt.chars().collect(); let ch_ix: Vec<i64> = chars.iter().map(|ch| self.char_to_xi.to_xi(&ch)).collect(); let features = Tensor::of_slice(&ch_ix).view([1, -1]); let seq_lengths = [ch_ix.len() as i64]; let seq_lengths = Tensor::of_slice(&seq_lengths); let ivalue = IValue::Tuple(vec![IValue::Tensor(features), IValue::Tensor(seq_lengths)]); let out = self.model.forward_is(&[ivalue]).unwrap(); let pred_threshold = 0.5; if let IValue::Tensor(out) = out { let probs = Vec::<f32>::from(out.sigmoid()); let mut buf = String::new(); buf.push(chars[0]); let mut toks = vec![]; for (p, ch) in probs.into_iter().zip(chars.iter()).skip(1) { if p > pred_threshold { toks.push(buf); buf = String::new(); } buf.push(*ch); } toks.push(buf); Ok(toks) } else { Err(anyhow::Error::new( ChawuekError::ModuleReturnedAnInvalidValue, )) } } }
true
fe93129d18ef141b1896a9eb2544ac6ec7d9462f
Rust
psinghal20/linkerd2-proxy
/linkerd/http-box/src/request.rs
UTF-8
1,386
2.734375
3
[ "Apache-2.0" ]
permissive
//! A middleware that boxes HTTP request bodies. use crate::Payload; use futures::Poll; #[derive(Debug)] pub struct Layer<B>(std::marker::PhantomData<fn(B)>); #[derive(Debug)] pub struct BoxRequest<S, B>(S, std::marker::PhantomData<fn(B)>); impl<B> Layer<B> where B: hyper::body::Payload + 'static, { pub fn new() -> Self { Layer(std::marker::PhantomData) } } impl<B> Clone for Layer<B> { fn clone(&self) -> Self { Layer(self.0) } } impl<S, B> tower::layer::Layer<S> for Layer<B> where B: hyper::body::Payload + 'static, S: tower::Service<http::Request<Payload>>, BoxRequest<S, B>: tower::Service<http::Request<B>>, { type Service = BoxRequest<S, B>; fn layer(&self, inner: S) -> Self::Service { BoxRequest(inner, self.0) } } impl<S: Clone, B> Clone for BoxRequest<S, B> { fn clone(&self) -> Self { BoxRequest(self.0.clone(), self.1) } } impl<S, B> tower::Service<http::Request<B>> for BoxRequest<S, B> where B: hyper::body::Payload + 'static, S: tower::Service<http::Request<Payload>>, { type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.0.poll_ready() } fn call(&mut self, req: http::Request<B>) -> Self::Future { self.0.call(req.map(Payload::new)) } }
true
40e33bfb6686dc9cad01ab8f29151d00697819d7
Rust
forkkit/kas
/crates/kas-widgets/src/frame.rs
UTF-8
2,151
2.578125
3
[ "Apache-2.0" ]
permissive
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! A simple frame use kas::{event, prelude::*}; /// A frame around content /// /// This widget provides a simple abstraction: drawing a frame around its /// contents. #[derive(Clone, Debug, Default, Widget)] #[handler(msg = <W as Handler>::Msg)] #[widget_derive(class_traits, Deref, DerefMut)] pub struct Frame<W: Widget> { #[widget_core] core: CoreData, #[widget_derive] #[widget] pub inner: W, offset: Offset, size: Size, } impl<W: Widget> Frame<W> { /// Construct a frame #[inline] pub fn new(inner: W) -> Self { Frame { core: Default::default(), inner, offset: Offset::ZERO, size: Size::ZERO, } } } impl<W: Widget> Layout for Frame<W> { fn size_rules(&mut self, size_handle: &mut dyn SizeHandle, axis: AxisInfo) -> SizeRules { let frame_rules = size_handle.frame(axis.is_vertical()); let child_rules = self.inner.size_rules(size_handle, axis); let (rules, offset, size) = frame_rules.surround_as_margin(child_rules); self.offset.set_component(axis, offset); self.size.set_component(axis, size); rules } fn set_rect(&mut self, mgr: &mut Manager, mut rect: Rect, align: AlignHints) { self.core.rect = rect; rect.pos += self.offset; rect.size -= self.size; self.inner.set_rect(mgr, rect, align); } #[inline] fn find_id(&self, coord: Coord) -> Option<WidgetId> { if !self.rect().contains(coord) { return None; } self.inner.find_id(coord).or(Some(self.id())) } fn draw(&self, draw_handle: &mut dyn DrawHandle, mgr: &event::ManagerState, disabled: bool) { draw_handle.outer_frame(self.core_data().rect); let disabled = disabled || self.is_disabled(); self.inner.draw(draw_handle, mgr, disabled); } }
true
a8a17378491d44611f5971ba2251bae6377cae5c
Rust
accounts-inheritance-finders-of-america/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
/e.rs
UTF-8
349
2.84375
3
[]
no_license
#![feature(main)] #[cfg(feature = "functional")] #[main] fn e() { std::iter::repeat('e').for_each(|e| print!("{}", e)); } #[cfg(not(feature = "functional"))] #[main] fn e() -> ! { loop { print!("e"); } } #[cfg(test)] mod tests { use super::*; #[test] fn teeeeest() { e(); unreachable!("eeeeeeeeee?????"); } }
true
1d72a47daf7338d3c9781479d4158b44bbd5cbe7
Rust
MichaelAquilina/adventofcode2018
/day11/src/main.rs
UTF-8
388
2.546875
3
[]
no_license
// https://adventofcode.com/2018/day/11 mod grid; use grid::Grid; fn main() { let serial_number = 7857; let grid = Grid::generate(300, 300, serial_number); let (point, power) = grid.find_max_power_point(); println!("{:?} (power: {})", point, power); let (point, power) = grid.find_max_power_point_adjustable(); println!("{:?} (power: {})", point, power); }
true
2b74a11bec6f2a23a1cd9fd887266fa1ece839fe
Rust
nowei/learning-rust
/generics/src/main.rs
UTF-8
1,693
3.59375
4
[]
no_license
mod lib; use lib::Tweet; use lib::Summary; fn largest<T: PartialOrd>(list: &[T]) -> &T { let mut largest = &list[0]; for item in list.iter() { if item > largest { largest = &item; } } return largest; } fn largest_alt<T>(list: &[T]) -> T where T: PartialOrd + Copy { let mut largest = list[0]; for &item in list.iter() { if item > largest { largest = item; } } return largest; } use std::fmt::Display; #[derive(Debug)] struct Point<T> { x: T, y: T } impl<T> Point<T> { fn x(&self) -> &T { &self.x } fn new(x: T, y: T) -> Self { Self { x, y, } } } impl<T: Display + PartialOrd> Pair<T> { fn cmp_display(&self) { if self.x >= self.y { println!("{:?}", self.x); } else { println!("{:?}", self.y); } } } fn main() { let number_list = vec![34, 50, 25, 100, 65]; println!("{:?}", largest(&number_list)); println!("{:?}", &number_list); let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; println!("{:?}", largest(&number_list)); let char_list = vec!['y', 'm', 'a', 'q']; println!("{:?}", largest(&char_list)); let integer = Point {x : 5, y : 10}; let float = Point {x : 1.0, y : 4.0}; println!("{:?}, {:?}", integer, float); println!("{:?}", integer.x); let tweet = Tweet { username: String::from("horse_ebooks"), content: String::from("of course, as you probably already know, people"), reply: false, retweet: false }; println!("1 new tweet: {:?}", tweet.summarize()); }
true
8f5dbdc04afe94c260b32cbe7b235a1aed3720bb
Rust
kitchenSpoon/solana
/src/accountant_stub.rs
UTF-8
7,320
2.96875
3
[ "Apache-2.0" ]
permissive
//! The `accountant_stub` module is a client-side object that interfaces with a server-side Accountant //! object via the network interface exposed by AccountantSkel. Client code should use //! this object instead of writing messages to the network directly. The binary //! encoding of its messages are unstable and may change in future releases. use accountant_skel::{Request, Response, Subscription}; use bincode::{deserialize, serialize}; use futures::future::{ok, FutureResult}; use hash::Hash; use signature::{KeyPair, PublicKey, Signature}; use std::collections::HashMap; use std::io; use std::net::UdpSocket; use transaction::Transaction; pub struct AccountantStub { pub addr: String, pub socket: UdpSocket, last_id: Option<Hash>, num_events: u64, balances: HashMap<PublicKey, Option<i64>>, } impl AccountantStub { /// Create a new AccountantStub that will interface with AccountantSkel /// over `socket`. To receive responses, the caller must bind `socket` /// to a public address before invoking AccountantStub methods. pub fn new(addr: &str, socket: UdpSocket) -> Self { let stub = AccountantStub { addr: addr.to_string(), socket, last_id: None, num_events: 0, balances: HashMap::new(), }; stub.init(); stub } pub fn init(&self) { let subscriptions = vec![Subscription::EntryInfo]; let req = Request::Subscribe { subscriptions }; let data = serialize(&req).expect("serialize Subscribe"); let _res = self.socket.send_to(&data, &self.addr); } pub fn recv_response(&self) -> io::Result<Response> { let mut buf = vec![0u8; 1024]; self.socket.recv_from(&mut buf)?; let resp = deserialize(&buf).expect("deserialize balance"); Ok(resp) } pub fn process_response(&mut self, resp: Response) { match resp { Response::Balance { key, val } => { self.balances.insert(key, val); } Response::LastId { id } => { self.last_id = Some(id); } Response::EntryInfo(entry_info) => { self.last_id = Some(entry_info.id); self.num_events += entry_info.num_events; } } } /// Send a signed Transaction to the server for processing. This method /// does not wait for a response. pub fn transfer_signed(&self, tr: Transaction) -> io::Result<usize> { let req = Request::Transaction(tr); let data = serialize(&req).unwrap(); self.socket.send_to(&data, &self.addr) } /// Creates, signs, and processes a Transaction. Useful for writing unit-tests. pub fn transfer( &self, n: i64, keypair: &KeyPair, to: PublicKey, last_id: &Hash, ) -> io::Result<Signature> { let tr = Transaction::new(keypair, to, n, *last_id); let sig = tr.sig; self.transfer_signed(tr).map(|_| sig) } /// Request the balance of the user holding `pubkey`. This method blocks /// until the server sends a response. If the response packet is dropped /// by the network, this method will hang indefinitely. pub fn get_balance(&mut self, pubkey: &PublicKey) -> FutureResult<i64, i64> { let req = Request::GetBalance { key: *pubkey }; let data = serialize(&req).expect("serialize GetBalance"); self.socket .send_to(&data, &self.addr) .expect("buffer error"); let mut done = false; while !done { let resp = self.recv_response().expect("recv response"); if let &Response::Balance { ref key, .. } = &resp { done = key == pubkey; } self.process_response(resp); } ok(self.balances[pubkey].unwrap()) } /// Request the last Entry ID from the server. This method blocks /// until the server sends a response. At the time of this writing, /// it also has the side-effect of causing the server to log any /// entries that have been published by the Historian. pub fn get_last_id(&mut self) -> FutureResult<Hash, ()> { let req = Request::GetLastId; let data = serialize(&req).expect("serialize GetId"); self.socket .send_to(&data, &self.addr) .expect("buffer error"); let mut done = false; while !done { let resp = self.recv_response().expect("recv response"); if let &Response::LastId { .. } = &resp { done = true; } self.process_response(resp); } ok(self.last_id.unwrap_or(Hash::default())) } /// Return the number of transactions the server processed since creating /// this stub instance. pub fn transaction_count(&mut self) -> u64 { // Wait for at least one EntryInfo. let mut done = false; while !done { let resp = self.recv_response().expect("recv response"); if let &Response::EntryInfo(_) = &resp { done = true; } self.process_response(resp); } // Then take the rest. self.socket.set_nonblocking(true).expect("set nonblocking"); loop { match self.recv_response() { Err(_) => break, Ok(resp) => self.process_response(resp), } } self.socket.set_nonblocking(false).expect("set blocking"); self.num_events } } #[cfg(test)] mod tests { use super::*; use accountant::Accountant; use accountant_skel::AccountantSkel; use futures::Future; use historian::Historian; use mint::Mint; use signature::{KeyPair, KeyPairUtil}; use std::io::sink; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::sync_channel; use std::sync::{Arc, Mutex}; use std::thread::sleep; use std::time::Duration; // TODO: Figure out why this test sometimes hangs on TravisCI. #[test] fn test_accountant_stub() { let addr = "127.0.0.1:9000"; let send_addr = "127.0.0.1:9001"; let alice = Mint::new(10_000); let acc = Accountant::new(&alice); let bob_pubkey = KeyPair::new().pubkey(); let exit = Arc::new(AtomicBool::new(false)); let (input, event_receiver) = sync_channel(10); let historian = Historian::new(event_receiver, &alice.last_id(), Some(30)); let acc = Arc::new(Mutex::new(AccountantSkel::new( acc, alice.last_id(), sink(), input, historian, ))); let _threads = AccountantSkel::serve(&acc, addr, exit.clone()).unwrap(); sleep(Duration::from_millis(300)); let socket = UdpSocket::bind(send_addr).unwrap(); socket.set_read_timeout(Some(Duration::new(5, 0))).unwrap(); let mut acc = AccountantStub::new(addr, socket); let last_id = acc.get_last_id().wait().unwrap(); let _sig = acc.transfer(500, &alice.keypair(), bob_pubkey, &last_id) .unwrap(); assert_eq!(acc.get_balance(&bob_pubkey).wait().unwrap(), 500); exit.store(true, Ordering::Relaxed); } }
true
0bdfea5d9744ac989abf10b66eb5355448b83c96
Rust
pimeys/napi-rs
/napi/src/win_delay_load_hook.rs
UTF-8
2,614
2.640625
3
[ "MIT" ]
permissive
//! The following directly was copied from [neon][]. //! //! Rust port of [win_delay_load_hook.cc][]. //! //! When the addon tries to load the "node.exe" DLL module, this module gives it the pointer to the //! .exe we are running in instead. Typically, that will be the same value. But if the node executable //! was renamed, you would not otherwise get the correct DLL. //! //! [neon]: https://github.com/neon-bindings/neon/blob/5ffa2d282177b63094c46e92b20b8e850d122e65/src/win_delay_load_hook.rs //! [win_delay_load_hook.cc]: https://github.com/nodejs/node-gyp/blob/e18a61afc1669d4897e6c5c8a6694f4995a0f4d6/src/win_delay_load_hook.cc use std::ffi::CStr; use std::ptr::null_mut; use winapi::shared::minwindef::{BOOL, DWORD, FARPROC, HMODULE, LPVOID}; use winapi::shared::ntdef::LPCSTR; use winapi::um::libloaderapi::GetModuleHandleA; // Structures hand-copied from // https://docs.microsoft.com/en-us/cpp/build/reference/structure-and-constant-definitions #[repr(C)] #[allow(non_snake_case)] struct DelayLoadProc { fImportByName: BOOL, // Technically this is `union{LPCSTR; DWORD;}` but we don't access it anyways. szProcName: LPCSTR, } #[repr(C)] #[allow(non_snake_case)] struct DelayLoadInfo { /// size of structure cb: DWORD, /// raw form of data (everything is there) /// Officially a pointer to ImgDelayDescr but we don't access it. pidd: LPVOID, /// points to address of function to load ppfn: *mut FARPROC, /// name of dll szDll: LPCSTR, /// name or ordinal of procedure dlp: DelayLoadProc, /// the hInstance of the library we have loaded hmodCur: HMODULE, /// the actual function that will be called pfnCur: FARPROC, /// error received (if an error notification) dwLastError: DWORD, } #[allow(non_snake_case)] type PfnDliHook = unsafe extern "C" fn(dliNotify: usize, pdli: *const DelayLoadInfo) -> FARPROC; const HOST_BINARIES: &[&[u8]] = &[b"node.exe", b"electron.exe"]; unsafe extern "C" fn load_exe_hook(event: usize, info: *const DelayLoadInfo) -> FARPROC { if event != 0x01 /* dliNotePreLoadLibrary */ { return null_mut(); } let dll_name = CStr::from_ptr((*info).szDll); if !HOST_BINARIES .iter() .any(|&host_name| host_name == dll_name.to_bytes()) { return null_mut(); } let exe_handle = GetModuleHandleA(null_mut()); // PfnDliHook sometimes has to return a FARPROC, sometimes an HMODULE, but only one // of them could be specified in the header, so we have to cast our HMODULE to that. exe_handle as FARPROC } #[no_mangle] static mut __pfnDliNotifyHook2: *mut PfnDliHook = load_exe_hook as *mut PfnDliHook;
true
78c0079234e14187086d68ceaa08b363750cdbd9
Rust
jng985/terra_rps
/src/contract.rs
UTF-8
1,980
2.703125
3
[ "Apache-2.0" ]
permissive
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult}; use cosmwasm_std::Addr; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; use crate::state::{State, STATE}; #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, info: MessageInfo, msg: InstantiateMsg, ) -> Result<Response, ContractError> { let state = State { host: info.sender.clone(), }; STATE.save(deps.storage, &state)?; Ok(Response::new() .add_attribute("method", "instantiate") .add_attribute("host", info.sender) ) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, _env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::StartGame { opponent } => try_start_game(deps, opponent), } } pub fn try_start_game(deps: DepsMut, opponent: Addr) -> Result<Response, ContractError> { let rcpt_addr = deps.api.addr_validate(&opponent.to_string())?; Ok(Response::new().add_attribute("method", "try_start_game")) } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{coins, from_binary}; #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InstantiateMsg { }; let info = mock_info("creator", &coins(1000, "earth")); // we can just call .unwrap() to assert this was a success let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); } #[test] fn start_game() { let info = mock_info("anyone", &coins(2, "token")); let msg = ExecuteMsg::StartGame { opponent: info.sender}; } }
true
04f8320b4e7589ee0d5d0c84dd0cd2b56eafd3ad
Rust
irraco/yew
/examples/mount_point/src/main.rs
UTF-8
1,579
2.796875
3
[ "Apache-2.0", "MIT" ]
permissive
#[macro_use] extern crate yew; #[macro_use] extern crate stdweb; use yew::html::{App, Html, InputData}; use stdweb::web::{IElement, document, INode}; struct Context {} struct Model { name: String, } enum Msg { UpdateName(String), } fn update(_: &mut Context, model: &mut Model, msg: Msg) { match msg { Msg::UpdateName(new_name) => { model.name = new_name; } } } fn view(model: &Model) -> Html<Msg> { html! { <div> <input value=&model.name, oninput=|e: InputData| Msg::UpdateName(e.value), /> <p>{ model.name.chars().rev().collect::<String>() }</p> </div> } } fn main() { yew::initialize(); let body = document().query_selector("body").unwrap(); // This canvas won't be overwritten by yew! let canvas = document().create_element("canvas"); body.append_child(&canvas); js! { const canvas = document.querySelector("canvas"); canvas.width = 100; canvas.height = 100; const ctx = canvas.getContext("2d"); ctx.fillStyle = "green"; ctx.fillRect(10, 10, 50, 50); }; let mount_class = "mount-point"; let mount_point = document().create_element("div"); mount_point.class_list().add(mount_class); body.append_child(&mount_point); let mut app = App::new(); let context = Context {}; let model = Model { name: "Reversed".to_owned(), }; let mount_point = format!(".{}", mount_class); app.mount_to(&mount_point, context, model, update, view); yew::run_loop(); }
true
0393ea8f888b1ae8c2291ee5415dc88092fbf8f1
Rust
cundd/rcoin
/src/rate_provider/cryptonator/mod.rs
UTF-8
2,075
2.828125
3
[]
no_license
// https://api.cryptonator.com/api/ticker/ltc-usd //{ // "ticker": { // "base": "LTC", // "target": "USD", // "price": "248.16084013", // "volume": "286939.69094764", // "change": "-0.67224984" // }, // "timestamp": 1515878702, // "success": true, // "error": "" //} mod intermediate_rate; use serde_json; use rate; use super::ProviderError; use super::RateProvider; use super::Currency; use self::intermediate_rate::*; pub struct Cryptonator {} impl Cryptonator { fn convert_to_internal_rate(response: &str) -> Result<IntermediateRate, ProviderError> { let deserialized_result: serde_json::Result<IntermediateRate> = serde_json::from_str(&response); match deserialized_result { Ok(deserialized) => Ok(deserialized), Err(e) => Err(ProviderError::new(e.to_string())), } } fn download_pair(crypto_currency: &Currency, fiat_currency: &str) -> Result<String, ProviderError> { Self::download(&format!( "https://api.cryptonator.com/api/ticker/{}-{}", crypto_currency.symbol(), fiat_currency.to_lowercase() )) } fn get_pair_in_internal_rate(crypto_currency: &Currency, fiat_currency: &str) -> Result<IntermediateRate, ProviderError> { Self::convert_to_internal_rate(&Self::download_pair(crypto_currency, fiat_currency)?) } } impl RateProvider for Cryptonator { fn get_name() -> &'static str { "Cryptonator" } fn get(currency: Currency) -> Result<rate::Rate, ProviderError> { let usd_rate:IntermediateRate = Self::get_pair_in_internal_rate(&currency, "usd")?; let eur_rate:IntermediateRate = Self::get_pair_in_internal_rate(&currency, "eur")?; Ok(rate::Rate::new(currency, usd_rate.price(), eur_rate.price())) } } #[cfg(test)] mod tests { use super::*; #[test] fn get_test() { let result: Result<rate::Rate, ProviderError> = <Cryptonator as RateProvider>::get(Currency::Bitcoin); assert!(result.is_ok()) } }
true
aa10ddec486aa9e82d082b3a9f14df931bead4e5
Rust
wangjia184/rholang-rust
/model/src/rho_types/SourcePosition.rs
UTF-8
419
2.703125
3
[]
no_license
// Extends generated SourcePosition structure impl SourcePosition { pub fn new (row : i32, col : i32, len : usize) -> SourcePosition { SourcePosition { row : row, col : col, len : len as i32, } } } impl fmt::Display for SourcePosition { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}:{}", self.row, self.col) } }
true
f7c568d1172417ce997f57ec4da556fca0205639
Rust
knokko/wasmuri-container
/src/layer/simple/keylistening.rs
UTF-8
4,557
2.640625
3
[ "MIT" ]
permissive
use crate::*; use std::cell::RefCell; use std::rc::Weak; use wasmuri_core::*; pub struct KeyListenManager { hover_down_listeners: WeakMetaVec<dyn ComponentBehavior, Region>, hover_up_listeners: WeakMetaVec<dyn ComponentBehavior, Region>, full_down_listeners: WeakMetaVec<dyn ComponentBehavior, i8>, full_up_listeners: WeakMetaVec<dyn ComponentBehavior, i8> } impl KeyListenManager { pub fn new() -> KeyListenManager { KeyListenManager { hover_down_listeners: WeakMetaVec::new(), hover_up_listeners: WeakMetaVec::new(), full_down_listeners: WeakMetaVec::new(), full_up_listeners: WeakMetaVec::new() } } pub fn can_claim_down(&self, region: Region) -> bool { for handle in &self.hover_down_listeners.vec { if handle.metadata.intersects_with(region) { return false; } } true } pub fn can_claim_up(&self, region: Region) -> bool { for handle in &self.hover_up_listeners.vec { if handle.metadata.intersects_with(region) { return false; } } true } /// Should only be used after can_claim_down confirmed that the given region is available pub fn add_region_key_down_listener(&mut self, behavior: Weak<RefCell<dyn ComponentBehavior>>, region: Region){ self.hover_down_listeners.push(behavior, region); } /// Should only be used after can_claim_up confirmed that the given region is available pub fn add_region_key_up_listener(&mut self, behavior: Weak<RefCell<dyn ComponentBehavior>>, region: Region){ self.hover_up_listeners.push(behavior, region); } pub fn add_global_key_down_listener(&mut self, behavior: Weak<RefCell<dyn ComponentBehavior>>, priority: i8){ Self::add_global_key_listener(&mut self.full_down_listeners, behavior, priority); } pub fn add_global_key_up_listener(&mut self, behavior: Weak<RefCell<dyn ComponentBehavior>>, priority: i8){ Self::add_global_key_listener(&mut self.full_up_listeners, behavior, priority); } fn add_global_key_listener(list: &mut WeakMetaVec<dyn ComponentBehavior, i8>, behavior: Weak<RefCell<dyn ComponentBehavior>>, priority: i8){ let maybe_index = list.vec.binary_search_by(|existing| { // Intentionally INVERT the order so that the higher priorities come first priority.cmp(&existing.metadata) }); let index; match maybe_index { Ok(the_index) => index = the_index, Err(the_index) => index = the_index }; list.vec.insert(index, WeakMetaHandle { weak_cell: behavior, metadata: priority }); } pub fn fire_key_down(&mut self, keys: &KeyInfo, manager: &ContainerManager, mouse_pos: Option<(f32, f32)>) -> bool { KeyListenManager::fire(&mut self.hover_down_listeners, &mut self.full_down_listeners, |behavior, manager| { behavior.key_down(&mut KeyDownParams::new(keys, manager)) }, manager, mouse_pos) } pub fn fire_key_up(&mut self, keys: &KeyInfo, manager: &ContainerManager, mouse_pos: Option<(f32, f32)>) -> bool { KeyListenManager::fire(&mut self.hover_up_listeners, &mut self.full_up_listeners, |behavior, manager| { behavior.key_up(&mut KeyUpParams::new(keys, manager)) }, manager, mouse_pos) } fn fire<F: FnMut(&mut dyn ComponentBehavior, &ContainerManager) -> bool>( hover_listeners: &mut WeakMetaVec<dyn ComponentBehavior, Region>, full_listeners: &mut WeakMetaVec<dyn ComponentBehavior, i8>, mut processor: F, manager: &ContainerManager, mouse_pos: Option<(f32, f32)>) -> bool { // The key listeners with a location have priority over those without bound location let mut consumed = false; if mouse_pos.is_some() { hover_listeners.for_each_mut(|behavior, region| { if !consumed && region.is_float_inside(mouse_pos.unwrap()) { consumed = processor(behavior, manager); } }); } // If none of the bound key listeners consumed the event, it will be passed to the full key listeners if !consumed { full_listeners.for_each_mut(|behavior, _priority| { if !consumed { consumed = processor(behavior, manager); } }); } consumed } }
true
2a4ccb181085f1db5be21cff609f50d3516f6d1d
Rust
Misterio77/ncspot
/src/theme.rs
UTF-8
2,151
2.671875
3
[ "BSD-2-Clause" ]
permissive
use cursive::theme::BaseColor::*; use cursive::theme::Color::*; use cursive::theme::PaletteColor::*; use cursive::theme::*; use crate::config::Config; macro_rules! load_color { ( $cfg: expr, $member: ident, $default: expr ) => { $cfg.theme .as_ref() .and_then(|t| t.$member.clone()) .map(|c| Color::parse(c.as_ref()).expect(&format!("Failed to parse color \"{}\"", c))) .unwrap_or($default) }; } pub fn load(cfg: &Config) -> Theme { let mut palette = Palette::default(); let borders = BorderStyle::Simple; palette[Background] = load_color!(cfg, background, TerminalDefault); palette[View] = load_color!(cfg, background, TerminalDefault); palette[Primary] = load_color!(cfg, primary, TerminalDefault); palette[Secondary] = load_color!(cfg, secondary, Dark(Blue)); palette[TitlePrimary] = load_color!(cfg, title, Dark(Red)); palette[Tertiary] = load_color!(cfg, highlight, TerminalDefault); palette[Highlight] = load_color!(cfg, highlight_bg, Dark(Red)); palette.set_color("playing", load_color!(cfg, playing, Dark(Blue))); palette.set_color( "playing_selected", load_color!(cfg, playing_selected, Light(Blue)), ); palette.set_color("playing_bg", load_color!(cfg, playing_bg, TerminalDefault)); palette.set_color("error", load_color!(cfg, error, TerminalDefault)); palette.set_color("error_bg", load_color!(cfg, error_bg, Dark(Red))); palette.set_color( "statusbar_progress", load_color!(cfg, statusbar_progress, Dark(Blue)), ); palette.set_color( "statusbar_progress_bg", load_color!(cfg, statusbar_progress_bg, Light(Black)), ); palette.set_color("statusbar", load_color!(cfg, statusbar, Dark(Yellow))); palette.set_color( "statusbar_bg", load_color!(cfg, statusbar_bg, TerminalDefault), ); palette.set_color("cmdline", load_color!(cfg, cmdline, TerminalDefault)); palette.set_color("cmdline_bg", load_color!(cfg, cmdline_bg, TerminalDefault)); Theme { shadow: false, palette, borders, } }
true
5b48c225b7bcc6a9fc64702b1f481250555d16d3
Rust
CodeSandwich/Mocktopus
/src/mock_store.rs
UTF-8
4,041
2.859375
3
[ "MIT" ]
permissive
use crate::mocking::MockResult; use std::{any::TypeId, marker::Tuple}; use std::cell::RefCell; use std::collections::HashMap; use std::mem::transmute; use std::rc::Rc; pub struct MockStore { layers: RefCell<Vec<MockLayer>>, } impl MockStore { pub fn clear(&self) { for layer in self.layers.borrow_mut().iter_mut() { layer.clear() } } pub fn clear_id(&self, id: TypeId) { for layer in self.layers.borrow_mut().iter_mut() { layer.clear_id(id) } } /// Layer will be in use as long as MockLayerGuard is alive /// MockLayerGuards must always be dropped and always in reverse order of their creation pub unsafe fn add_layer(&self, layer: MockLayer) { self.layers.borrow_mut().push(layer) } pub unsafe fn remove_layer(&self) { self.layers.borrow_mut().pop(); } pub unsafe fn add_to_thread_layer<I: Tuple, O>( &self, id: TypeId, mock: Box<dyn FnMut<I, Output = MockResult<I, O>> + 'static>, ) { self.layers .borrow_mut() .first_mut() .expect("Thread mock level missing") .add(id, mock); } pub unsafe fn call<I: Tuple, O>(&self, id: TypeId, mut input: I) -> MockResult<I, O> { // Do not hold RefCell borrow while calling mock, it can try to modify mocks let layer_count = self.layers.borrow().len(); for layer_idx in (0..layer_count).rev() { let mock_opt = self .layers .borrow() .get(layer_idx) .expect("Mock layer removed while iterating") .get(id); if let Some(mock) = mock_opt { match mock.call(input) { MockLayerResult::Handled(result) => return result, MockLayerResult::Unhandled(new_input) => input = new_input, } } } MockResult::Continue(input) } } //TODO tests // clear // clear id // add and remove layer // inside mock closure impl Default for MockStore { fn default() -> Self { MockStore { layers: RefCell::new(vec![MockLayer::default()]), } } } #[derive(Default)] pub struct MockLayer { mocks: HashMap<TypeId, ErasedStoredMock>, } impl MockLayer { fn clear(&mut self) { self.mocks.clear() } fn clear_id(&mut self, id: TypeId) { self.mocks.remove(&id); } pub unsafe fn add<I: Tuple, O>( &mut self, id: TypeId, mock: Box<dyn FnMut<I, Output = MockResult<I, O>> + 'static>, ) { let stored = StoredMock::new(mock).erase(); self.mocks.insert(id, stored); } unsafe fn get(&self, id: TypeId) -> Option<ErasedStoredMock> { self.mocks.get(&id).cloned() } } pub enum MockLayerResult<I, O> { Handled(MockResult<I, O>), Unhandled(I), } #[derive(Clone)] struct ErasedStoredMock { mock: StoredMock<(), ()>, } impl ErasedStoredMock { unsafe fn call<I: Tuple, O>(self, input: I) -> MockLayerResult<I, O> { let unerased: StoredMock<I, O> = transmute(self.mock); unerased.call(input) } } /// Guarantees that while mock is running it's not overwritten, destroyed, or called again #[derive(Clone)] struct StoredMock<I: Tuple, O> { mock: Rc<RefCell<Box<dyn FnMut<I, Output = MockResult<I, O>>>>>, } impl<I: Tuple, O> StoredMock<I, O> { fn new(mock: Box<dyn FnMut<I, Output = MockResult<I, O>> + 'static>) -> Self { StoredMock { mock: Rc::new(RefCell::new(mock)), } } fn call(&self, input: I) -> MockLayerResult<I, O> { match self.mock.try_borrow_mut() { Ok(mut mock) => MockLayerResult::Handled(mock.call_mut(input)), Err(_) => MockLayerResult::Unhandled(input), } } fn erase(self) -> ErasedStoredMock { unsafe { ErasedStoredMock { mock: transmute(self), } } } }
true
84666255aab4d6e6ffea12795613dfed450f83c1
Rust
ItsHoff/Rusty
/src/statistics.rs
UTF-8
4,034
2.9375
3
[ "MIT" ]
permissive
mod accumulator; use std::collections::HashMap; use std::fmt::Write; use std::sync::Mutex; use std::time::{Duration, Instant}; use prettytable::{cell, ptable, row, table}; use self::accumulator::SumAccumulator; lazy_static::lazy_static! { static ref STATS: Mutex<Vec<Statistics>> = Mutex::new(Vec::new()); } macro_rules! get_stats_vec { () => { STATS.lock().unwrap() }; } macro_rules! get_current { () => { get_stats_vec!().last_mut().unwrap() }; } pub fn new_scene(name: &str) { let mut vec = get_stats_vec!(); vec.push(Statistics::new(name)); } pub fn print() { let vec = get_stats_vec!(); for stats in &*vec { let (labels, durations) = stats.stopwatch_string(); ptable!([labels, durations]); } } fn report_stopwatch(watch: &Stopwatch) { get_current!().read_stopwatch(watch); } struct Statistics { name: String, nodes: Vec<StopwatchNode>, node_map: HashMap<String, usize>, } impl Statistics { fn new(name: &str) -> Self { let mut stats = Self::empty(name); let total = stats.add_stopwatch("Total", None); let load = stats.add_stopwatch("Load", Some(total)); stats.add_stopwatch("Loab obj", Some(load)); stats.add_stopwatch("Bvh", Some(load)); stats.add_stopwatch("Render", Some(total)); stats } fn empty(name: &str) -> Self { Statistics { name: name.to_string(), nodes: Vec::new(), node_map: HashMap::new(), } } fn add_stopwatch(&mut self, name: &str, parent: Option<usize>) -> usize { let new_i = self.nodes.len(); self.nodes.push(StopwatchNode::new(name)); self.node_map.insert(name.to_string(), new_i); if let Some(parent_i) = parent { let parent = &mut self.nodes[parent_i]; parent.children.push(new_i); } new_i } fn read_stopwatch(&mut self, watch: &Stopwatch) { if let Some(&i) = self.node_map.get(&watch.name) { let node = &mut self.nodes[i]; node.duration.add_self(watch.duration); } else { panic!("Stopwatch {} did not have a matching node!", watch.name); } } fn stopwatch_string(&self) -> (String, String) { let mut labels = String::new(); let mut durations = String::new(); self.add_node_to_string(0, 0, &mut labels, &mut durations); (labels, durations) } fn add_node_to_string(&self, node_i: usize, level: usize, labels: &mut String, durations: &mut String) { let node = &self.nodes[node_i]; writeln!(labels, "{}{}", "| ".repeat(level), node.name); writeln!(durations, "{}{:#.2?}", "| ".repeat(level), node.duration.val); for &child_i in &node.children { self.add_node_to_string(child_i, level + 1, labels, durations); } } } #[derive(Debug)] struct StopwatchNode { name: String, duration: SumAccumulator<Duration>, children: Vec<usize>, } impl StopwatchNode { fn new(name: &str) -> Self { Self { name: name.to_string(), duration: SumAccumulator::new(), children: Vec::new(), } } } pub struct Stopwatch { name: String, start: Option<Instant>, duration: SumAccumulator<Duration>, } impl Stopwatch { pub fn new(name: &str) -> Self { Self { name: name.to_string(), start: None, duration: SumAccumulator::new() } } pub fn start(&mut self) { assert!( self.start.is_none(), "Tried to start already running stopwatch {}!", self.name ); self.start = Some(Instant::now()); } pub fn stop(&mut self) { if let Some(start) = self.start.take() { self.duration.add_val(start.elapsed()); } } } impl Drop for Stopwatch { fn drop(&mut self) { self.stop(); report_stopwatch(self); } }
true
833704443753dea3634e8e3a13ab1b3052e7f4fc
Rust
richwandell/rustjs
/src/ast_interpreter/interpreter.rs
UTF-8
22,312
2.53125
3
[]
no_license
use crate::parser::symbols::{JSItem, Operator, Statement, StdFun, AssignOp}; use crate::parser::symbols::Expression; use crate::ast_interpreter::bin_op::{bin_add, bin_mul, bin_sub, bin_div, bin_less}; use std::collections::HashMap; use crate::lexer::js_token::Tok; use crate::ast_interpreter::std::{create_std_objects}; use crate::ast_interpreter::std::console::std_log; use crate::ast_interpreter::std::function::std_fun_apply; use crate::ast_interpreter::helpers::{o_to_v, find_object_from_reference, find_reference_from_member_expression}; use crate::ast_interpreter::scope::insert::{set_object}; use crate::ast_interpreter::std::array::std_array_push; use crate::ast_interpreter::std::inherit::inherit; pub(crate) struct Interpreter { pub(crate) scopes: Vec<HashMap<String, JSItem>>, pub(crate) scope: usize, pub(crate) function_scope: Vec<usize>, #[cfg(test)] pub(crate) captured_output: Vec<Vec<JSItem>> } impl Interpreter { pub(crate) fn new() -> Interpreter { let mut int = Interpreter { scopes: vec![HashMap::new()], scope: 0, function_scope: vec![], #[cfg(test)] captured_output: vec![] }; create_std_objects(int) } fn get_object(&mut self, name: &String) -> Result<(JSItem, usize), ()> { for i in (0..=self.scope).rev() { let objects = self.scopes.get_mut(i).unwrap(); let object = objects.remove(name); if let Some(object) = object { return Ok((object, i)); } } Err(()) } fn replace_object(&mut self, scope: usize, object: JSItem, name: String) { self.scopes.get_mut(scope) .unwrap() .insert(name, object); } fn add_params_to_scope(&mut self, mut names: Vec<Tok>, mut items: Vec<JSItem>) { while !items.is_empty() { let item = items.pop().unwrap(); if let Tok::Name {name} = names.pop().unwrap() { self.scopes.get_mut(self.scope) .unwrap() .insert(name, item); } } } fn call_identifier(&mut self, name: String, arguments: Vec<JSItem>) -> Result<JSItem, ()>{ let func = self.get_object(&name); match func { Ok(f) => { match f.0 { JSItem::Function { mutable, params, properties, body } => { let body_clone = body.clone(); let params_clone = params.clone(); //first add the function back where it belongs in the call stack self.scopes.get_mut(f.1) .unwrap() .insert(name, JSItem::Function { mutable, params, properties, body }); //create a new scope self.create_new_scope(); let args = self.make_params(params_clone, arguments); self.add_params_to_scope(args.0, args.1); let mut out = JSItem::Undefined; for item in body_clone { out = self.interpret(item); } return Ok(out); } _ => { Err(()) } } } Err(_) => Err(()) } } fn make_params(&mut self, mut params: Vec<Tok>, mut arguments: Vec<JSItem>) -> (Vec<Tok>, Vec<JSItem>) { arguments.reverse(); let mut new_params = vec![]; while !params.is_empty() { let tok = params.pop().unwrap(); match tok { Tok::Comma => {}, _ => { new_params.push(tok); } } } let mut names = vec![]; let mut items = vec![]; while !arguments.is_empty() { if let Some(arg) = arguments.pop() { let out = self.visit(arg); names.push(new_params.pop().unwrap_or(Tok::Name {name: "extra".to_string()})); items.push(out); } } return (names, items); } fn call_function(&mut self, params: Vec<Tok>, arguments: Vec<JSItem>, body: Vec<JSItem>) -> Result<JSItem, ()> { //create a new scope self.create_new_scope(); self.function_scope.push(self.scope.clone()); let args = self.make_params(params, arguments); self.add_params_to_scope(args.0, args.1); let mut out = JSItem::Undefined; for item in body { out = self.interpret(item); } self.function_scope.pop(); self.remove_current_scope(); return Ok(out); } fn call_std(&mut self, this_path: Vec<String>, func: StdFun, params: Vec<Tok>, arguments: Vec<JSItem>) -> Result<JSItem, ()> { //create a new scope self.create_new_scope(); self.function_scope.push(self.scope.clone()); match func { #[allow(unreachable_code)] StdFun::ConsoleLog => { let args = self.make_params(params, arguments); #[cfg(test)]{ self.captured_output.push(args.1 ); self.function_scope.pop(); self.remove_current_scope(); return Ok(JSItem::Undefined) } std_log(args.1); self.function_scope.pop(); self.remove_current_scope(); return Ok(JSItem::Undefined) } StdFun::ObjectKeys => { self.function_scope.pop(); self.remove_current_scope(); return Err(()); } StdFun::FunctionApply => { let args = self.make_params(params, arguments); let out = std_fun_apply(self, this_path, args); self.function_scope.pop(); self.remove_current_scope(); return out; } StdFun::ArrayMap => { self.function_scope.pop(); self.remove_current_scope(); return Err(()); } StdFun::ArrayConstructor => { self.function_scope.pop(); self.remove_current_scope(); return Err(()); } StdFun::ArrayPush => { let mut args = self.make_params(params, arguments); if let Ok(()) = std_array_push(self, this_path, args) { return Ok(JSItem::Undefined); } return Err(()) } } } fn call_func_ex(&mut self, ex: Expression, _this_path: Vec<String>, arguments: Vec<JSItem>) -> Result<JSItem, ()> { match ex { Expression::FuncEx { params, body } => { return self.call_function(params.clone(), arguments, body.clone()); } _ => { return Err(()) } } } fn call_object_reference(&mut self, this_path: Vec<String>, reference: Vec<String>, arguments: Vec<JSItem>) -> Result<JSItem, ()> { let mut path = reference.clone(); let function = find_object_from_reference(self, path.clone()); match function { Ok(function) => { match function { JSItem::Ex {expression} => { return self.call_func_ex(*expression, this_path, arguments); } JSItem::ObjectReference { path } => { return self.call_object_reference( this_path, path.clone(), arguments); } JSItem::Function { mutable: _, params, properties: _, body } => { #[allow(mutable_borrow_reservation_conflict)] return self.call_function(params.clone(), arguments, body.clone()); } JSItem::Std { params, func } => { #[allow(mutable_borrow_reservation_conflict)] return self.call_std(this_path, func.clone(), params.clone(), arguments); } _ => { return Err(()) } } } Err(e) => return Err(e) } } fn call_member_ex(&mut self, object: Box<Expression>, property: Box<Expression>, arguments: Vec<JSItem>) -> Result<JSItem, ()>{ let mut path = find_reference_from_member_expression(Expression::MemberExpression {object, property}); let mut this_path = path.clone(); this_path.pop(); self.call_object_reference(this_path, path, arguments) } fn visit_binop(&mut self, a: Box<Expression>, op: Operator, b: Box<Expression>) -> JSItem { match op { Operator::Add => { bin_add(self.visit_ex(a), self.visit_ex(b)).unwrap() } Operator::Sub => { bin_sub(self.visit_ex(a), self.visit_ex(b)).unwrap() } Operator::Mult => { bin_mul(self.visit_ex(a), self.visit_ex(b)).unwrap() } Operator::Div => { bin_div(self.visit_ex(a), self.visit_ex(b)).unwrap() } Operator::Less => { bin_less(self.visit_ex(a), self.visit_ex(b)).unwrap() } _ => { JSItem::Undefined } } } fn visit_call_ex(&mut self, callee: Box<Expression>, arguments: Vec<JSItem>) -> JSItem { match *callee { Expression::MemberExpression { object, property } => { self.call_member_ex(object, property, arguments).unwrap() } Expression::Identifier { name } => { self.call_identifier(name, arguments).unwrap() } _ => { JSItem::Undefined } } } fn visit_ident(&mut self, name: String) -> JSItem { let object = self.get_object(&name); match object { Ok(obj) => { match obj.0 { JSItem::Variable { mutable, value } => { match value { Expression::ArrayExpression { items, properties } => { let out = JSItem::Array { items: items.clone(), properties: properties.clone() }; self.replace_object(obj.1, JSItem::Variable { mutable, value: Expression::ArrayExpression {items, properties} }, name); return out; } Expression::Object { mutable: om, properties } => { let out = JSItem::Object {mutable: om, properties: properties.clone()}; self.replace_object(obj.1, JSItem::Variable { mutable, value: Expression::Object {mutable: om, properties} }, name); return out; } Expression::String {value} => { let out = JSItem::String {value: value.clone()}; self.replace_object(obj.1, JSItem::Variable { mutable, value: Expression::String {value} }, name); return out; } Expression::Number {value} => { self.replace_object(obj.1, JSItem::Variable { mutable, value: Expression::Number {value} }, name); return JSItem::Number {value: value.clone()}; } _ => {} } } JSItem::Number {value} => { self.replace_object(obj.1, JSItem::Number {value}, name); return JSItem::Number {value: value.clone()}; } JSItem::String {value} => { let out = JSItem::String {value: value.clone()}; self.replace_object(obj.1, JSItem::String {value}, name); return out; } _ => {} } }, Err(_) => {} } JSItem::Undefined } fn visit_ex_up(&mut self, ex: Box<Expression>) -> JSItem { if let Expression::Identifier {name} = *ex { if let Ok(obj) = self.get_object(&name) { if let JSItem::Variable {mutable, value} = obj.0 { match value { Expression::String {value:_} => { self.replace_object(obj.1, JSItem::NaN, name); } Expression::Number {value} => { self.replace_object(obj.1, JSItem::Variable { mutable, value: Expression::Number {value: value + 1.} }, name); } _ => {} } } } } JSItem::Undefined } fn visit_member_expression(&mut self, object: Box<Expression>, property: Box<Expression>) -> JSItem { let object_out = self.visit_ex(object); match object_out { JSItem::Object { mutable:_, properties } => { if let Expression::Identifier {name} = *property { if let Some(item) = properties.get(&name) { return self.visit(item.clone()); } } } _ => { return JSItem::Undefined; } } JSItem::Undefined } fn visit_array_expression(&mut self, items: Vec<JSItem>, _properties: HashMap<String, JSItem>) -> JSItem { let mut new_items = vec![]; for mut item in items { new_items.push(self.visit(item)); } let array = inherit(&self, JSItem::ObjectReference { path: vec!["Array".to_string()] }, JSItem::ObjectReference { path: vec!["Array".to_string()] }); JSItem::Array {items: new_items, properties: match array { JSItem::Object { mutable:_, properties } => { properties } _ => HashMap::new() }} } fn visit_ex(&mut self, ex: Box<Expression>) -> JSItem { match *ex { Expression::ArrayExpression { items, properties } => { self.visit_array_expression(items, properties) } Expression::MemberExpression { object, property } => { self.visit_member_expression(object, property) } Expression::UpdateExpression {expression} => { self.visit_ex_up(expression) } Expression::Identifier {name} => { self.visit_ident(name) } Expression::Literal { value } => { JSItem::String { value } } Expression::Number { value } => { JSItem::Number { value } } Expression::Binop { a, op, b } => { self.visit_binop(a, op, b) } Expression::SubExpression { expression } => { self.visit_ex(expression) } Expression::CallExpression { callee, arguments } => { self.visit_call_ex(callee, arguments) } Expression::String {value} => { JSItem::String {value} } _ => { JSItem::Undefined } } } fn create_new_scope(&mut self) { let scope = HashMap::new(); self.scopes.push(scope); self.scope += 1; } #[allow(dead_code)] fn remove_current_scope(&mut self) { self.scopes.pop(); self.scope -= 1; } fn visit_for_statement(&mut self, init: JSItem, test: JSItem, update: JSItem, body: Vec<JSItem>) -> JSItem { self.create_new_scope(); self.visit(init); loop { let cloned_test = test.clone(); let test_out = self.visit(cloned_test); if let JSItem::Bool {value} = test_out { if !value { break; } } for item in body.clone() { self.interpret(item); } self.visit(update.clone()); } self.remove_current_scope(); JSItem::Undefined } fn declare_function_in_scope(&mut self, mutable: bool, name: String, params: Vec<Tok>, body: Vec<JSItem>) { let mut properties = HashMap::new(); properties.insert("prototype".to_string(), JSItem::Ex { expression: Box::new(Expression::String { value: name.clone() }) }); properties.insert("name".to_string(), JSItem::Ex { expression: Box::new(Expression::Literal { value: name.clone() }) }); self.scopes.get_mut(self.scope) .unwrap() .insert(name.clone(), JSItem::Function { mutable, properties, params, body, }); } fn assign_variable(&mut self, operator: AssignOp, left: JSItem, right: JSItem) -> Result<(), ()> { let mut path = vec![]; if let JSItem::Ex {expression} = left { if let Expression::MemberExpression { object, property } = *expression { path = find_reference_from_member_expression(Expression::MemberExpression {object, property}) } else if let Expression::String {value} = *expression { path = vec![value]; } else if let Expression::Literal {value} = *expression { path = vec![value]; } } let right_out = self.visit(right); let exp = o_to_v(right_out, operator.clone()); match operator { AssignOp::Var => { let mut scope = 0; //if we are in a function, var assignments are declared at function scope if !self.function_scope.is_empty() { scope = self.function_scope.get(self.function_scope.len() - 1).unwrap().clone(); } self.scopes.get_mut(scope) .unwrap() .insert(path.get(0).unwrap().to_string(), exp.clone()); return Ok(()); } AssignOp::Let | AssignOp::Const => { if path.len() > 1 { return Err(()) } let scope = self.scope; let var_name = path.get(0).unwrap().to_string(); //const|let cannot re declare in same scope if self.scopes.get(scope).unwrap().contains_key(&var_name) { return Err(()); } self.scopes.get_mut(scope) .unwrap() .insert(var_name, exp.clone()); return Ok(()); } AssignOp::None => { if let Ok(_result) = set_object(self, path, exp) { return Ok(()); } else { return Err(()); } } } } fn visit_st(&mut self, st: Box<Statement>) -> JSItem { match *st { Statement::Return { value } => { return self.visit(*value); } Statement::AssignObject { .. } => { JSItem::Undefined } Statement::ForStatement { init, test, update, body } => { return self.visit_for_statement(init, test, update, body); } Statement::AssignArrowFunction { mutable, function } => { match *function { Statement::FunctionDef { name, params, body } => { self.declare_function_in_scope(mutable, name, params, body); JSItem::Undefined } _ => { JSItem::Undefined } } } #[allow(unused_must_use)] Statement::AssignmentExpression { operator, left, right } => { self.assign_variable(operator, left, right); JSItem::Undefined } Statement::FunctionDef { name, params, body } => { self.declare_function_in_scope(true, name, params, body); JSItem::Undefined } _ => { JSItem::Undefined } } } fn visit(&mut self, tree: JSItem) -> JSItem { match tree { JSItem::Variable { mutable:_, value } => { self.visit_ex(Box::from(value)) } JSItem::Ex { expression } => { self.visit_ex(expression) } JSItem::St { statement } => { self.visit_st(statement) } JSItem::Object { mutable, properties } => { JSItem::Object {mutable, properties} } _ => { JSItem::Undefined } } } pub(crate) fn interpret(&mut self, js_item: JSItem) -> JSItem { self.visit(js_item) } }
true
731d9ae92f3bb8c48f0757781ba305b3698bb320
Rust
prabhugopal/Sprocket
/lib/mem_utils/src/lib.rs
UTF-8
3,474
2.84375
3
[ "MIT" ]
permissive
#![no_std] use core::ops::Sub; // Memory layout pub const KERNBASE: VirtAddr = VirtAddr(0x80000000); pub const KERNLINK: VirtAddr = VirtAddr(KERNBASE.0 + EXTMEM.0); // Address where kernel is linked pub const EXTMEM: PhysAddr = PhysAddr(0x100000); // Start of extended memory pub const PHYSTOP: PhysAddr = PhysAddr(0xE000000); // Top physical memory pub const DEVSPACE: VirtAddr = VirtAddr(0xFE000000); // Other devices are at high addresses pub const PGSIZE: usize = 4096; pub const PDXSHIFT: usize = 22; pub const PTXSHIFT: usize = 12; extern "C" { pub static end: u8; } /// A utility trait that implements common methods for `PhysAddr` and `VirtAddr` pub trait Address { fn new(usize) -> Self where Self: core::marker::Sized; fn addr(&self) -> usize; fn is_page_aligned(&self) -> bool { self.addr() % PGSIZE == 0 } fn page_roundup(&self) -> Self where Self: core::marker::Sized { let addr = (self.addr() + PGSIZE - 1) & !(PGSIZE - 1); Self::new(addr) } fn page_rounddown(&self) -> Self where Self: core::marker::Sized { let addr = self.addr() & !(PGSIZE - 1); Self::new(addr) } // Simulate pointer arithmetic of adding/subtracting 4-byte int to address fn offset<T>(&self, off: isize) -> Self where Self: core::marker::Sized { let size = core::mem::size_of::<T>(); if off > 0 { Self::new(self.addr() + (size * off as usize)) } else { Self::new(self.addr().wrapping_add(size * off as usize)) } } } /// A convenience class to safely work with and manipulate physical addresses #[derive(PartialOrd, Ord, PartialEq, Eq, Copy, Clone, Default, Debug)] pub struct PhysAddr(pub usize); /// A convenience class to safely work with and manipulate virtual (paged) addresses #[derive(PartialOrd, Ord, PartialEq, Eq, Copy, Clone, Default, Debug)] pub struct VirtAddr(pub usize); impl Address for VirtAddr { fn new(addr: usize) -> VirtAddr { VirtAddr(addr) } fn addr(&self) -> usize { self.0 } } impl Address for PhysAddr { fn new(addr: usize) -> PhysAddr { PhysAddr(addr) } fn addr(&self) -> usize { self.0 } } impl PhysAddr { pub fn new(addr: usize) -> PhysAddr { PhysAddr(addr) } pub fn to_virt(&self) -> VirtAddr { VirtAddr::new(self.0 + KERNBASE.addr()) } } impl Sub for PhysAddr { type Output = usize; fn sub(self, other: PhysAddr) -> usize { self.0.wrapping_sub(other.0) } } impl Sub for VirtAddr { type Output = usize; fn sub(self, other: VirtAddr) -> usize { self.0.wrapping_sub(other.0) } } impl VirtAddr { pub fn new(addr: usize) -> VirtAddr { VirtAddr(addr) } pub fn from_pageno(pageno: usize) -> VirtAddr { let base = VirtAddr::new(unsafe { &end as *const _ as usize }).page_roundup(); VirtAddr::new(PGSIZE * pageno + base.addr()) } pub fn to_phys(&self) -> PhysAddr { PhysAddr::new(self.0 - KERNBASE.addr()) } pub fn page_dir_index(&self) -> usize { (self.addr() >> PDXSHIFT) & 0x3FF } pub fn page_table_index(&self) -> usize { (self.addr() >> PTXSHIFT) & 0x3FF } pub fn pageno(&self) -> usize { let new = self.page_roundup(); (new - VirtAddr::new(unsafe { &end as *const _ as usize }).page_roundup()) / PGSIZE } }
true