lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
boa/src/builtins/math/mod.rs
coolreader18/boa
7dd32a68594585950be3eaa62e480b8fec5ba45a
use crate::{ builtins::{ function::NativeFunctionData, value::{from_value, to_value, ResultValue, Value, ValueData}, }, exec::Interpreter, }; use rand::random; use std::f64; #[cfg(test)] mod tests; pub fn abs(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .abs() })) } pub fn acos(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .acos() })) } pub fn acosh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .acosh() })) } pub fn asin(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .asin() })) } pub fn asinh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .asinh() })) } pub fn atan(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .atan() })) } pub fn atanh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .atanh() })) } pub fn atan2(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .atan2(args.get(1).expect("Could not get argument").to_num()) })) } pub fn cbrt(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .cbrt() })) } pub fn ceil(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .ceil() })) } pub fn cos(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .cos() })) } pub fn cosh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .cosh() })) } pub fn exp(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .exp() })) } pub fn floor(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .floor() })) } pub fn log(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { let value = from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); if value <= 0.0 { f64::NAN } else { value.log(f64::consts::E) } })) } pub fn log10(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { let value = from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); if value <= 0.0 { f64::NAN } else { value.log10() } })) } pub fn log2(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { let value = from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); if value <= 0.0 { f64::NAN } else { value.log2() } })) } pub fn max(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { let mut max = f64::NEG_INFINITY; for arg in args { let num = arg.to_num(); max = max.max(num); } Ok(to_value(max)) } pub fn min(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { let mut max = f64::INFINITY; for arg in args { let num = arg.to_num(); max = max.min(num); } Ok(to_value(max)) } pub fn pow(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.len() >= 2 { let num: f64 = from_value(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); let power: f64 = from_value(args.get(1).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); num.powf(power) } else { f64::NAN })) } pub fn _random(_: &Value, _: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(random::<f64>())) } pub fn round(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .round() })) } pub fn sign(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { let value = from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); if value == 0.0 || value == -0.0 { value } else { value.signum() } })) } pub fn sin(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .sin() })) } pub fn sinh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .sinh() })) } pub fn sqrt(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .sqrt() })) } pub fn tan(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .tan() })) } pub fn tanh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .tanh() })) } pub fn trunc(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .trunc() })) } pub fn create_constructor(global: &Value) -> Value { let math = ValueData::new_obj(Some(global)); math.set_field_slice("E", to_value(f64::consts::E)); math.set_field_slice("LN2", to_value(f64::consts::LN_2)); math.set_field_slice("LN10", to_value(f64::consts::LN_10)); math.set_field_slice("LOG2E", to_value(f64::consts::LOG2_E)); math.set_field_slice("LOG10E", to_value(f64::consts::LOG10_E)); math.set_field_slice("SQRT1_2", to_value(0.5_f64.sqrt())); math.set_field_slice("SQRT2", to_value(f64::consts::SQRT_2)); math.set_field_slice("PI", to_value(f64::consts::PI)); make_builtin_fn!(abs, named "abs", with length 1, of math); make_builtin_fn!(acos, named "acos", with length 1, of math); make_builtin_fn!(acosh, named "acosh", with length 1, of math); make_builtin_fn!(asin, named "asin", with length 1, of math); make_builtin_fn!(asinh, named "asinh", with length 1, of math); make_builtin_fn!(atan, named "atan", with length 1, of math); make_builtin_fn!(atanh, named "atanh", with length 1, of math); make_builtin_fn!(atan2, named "atan2", with length 2, of math); make_builtin_fn!(cbrt, named "cbrt", with length 1, of math); make_builtin_fn!(ceil, named "ceil", with length 1, of math); make_builtin_fn!(cos, named "cos", with length 1, of math); make_builtin_fn!(cosh, named "cosh", with length 1, of math); make_builtin_fn!(exp, named "exp", with length 1, of math); make_builtin_fn!(floor, named "floor", with length 1, of math); make_builtin_fn!(log, named "log", with length 1, of math); make_builtin_fn!(log10, named "log10", with length 1, of math); make_builtin_fn!(log2, named "log2", with length 1, of math); make_builtin_fn!(max, named "max", with length 2, of math); make_builtin_fn!(min, named "min", with length 2, of math); make_builtin_fn!(pow, named "pow", with length 2, of math); make_builtin_fn!(_random, named "random", of math); make_builtin_fn!(round, named "round", with length 1, of math); make_builtin_fn!(sign, named "sign", with length 1, of math); make_builtin_fn!(sin, named "sin", with length 1, of math); make_builtin_fn!(sinh, named "sinh", with length 1, of math); make_builtin_fn!(sqrt, named "sqrt", with length 1, of math); make_builtin_fn!(tan, named "tan", with length 1, of math); make_builtin_fn!(tanh, named "tanh", with length 1, of math); make_builtin_fn!(trunc, named "trunc", with length 1, of math); math }
use crate::{ builtins::{ function::NativeFunctionData, value::{from_value, to_value, ResultValue, Value, ValueData}, }, exec::Interpreter, }; use rand::random; use std::f64; #[cfg(test)] mod tests; pub fn abs(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .abs() })) } pub fn acos(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .acos() })) } pub fn acosh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .acosh() })) } pub fn asin(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .asin() })) } pub fn asinh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .asinh() })) } pub fn atan(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .atan() })) } pub fn atanh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .atanh() })) } pub fn atan2(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .atan2(args.get(1).expect("Could not get argument").to_num()) })) } pub fn cbrt(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .cbrt() })) } pub fn ceil(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .ceil() })) } pub fn cos(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .cos() })) } pub fn cosh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .cosh() })) } pub fn exp(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .exp() })) } pub fn floor(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .floor() })) } pub fn log(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { let value = from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); if value <= 0.0 { f64::NAN } else { value.log(f64::consts::E) } })) } pub fn log10(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { let value = from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); if value <= 0.0 { f64::NAN } else { value.log10() } })) } pub fn log2(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { let value = from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); if value <= 0.0 { f64::NAN } else { value.log2() } })) } pub fn max(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { let mut max = f64::NEG_INFINITY; for arg in args { let num = arg.to_num(); max = max.max(num); } Ok(to_value(max)) } pub fn min(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { let mut max = f64::INFINITY; for arg in args { let num = arg.to_num(); max = max.min(num); } Ok(to_value(max)) } pub fn pow(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.len() >= 2 { let num: f64 = from_value(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); let power: f64 = from_value(args.get(1).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); num.powf(power) } else { f64::NAN })) } pub fn _random(_: &Value, _: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(random::<f64>())) } pub fn round(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .round() })) } pub fn sign(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { let value = from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64"); if value == 0.0 || value == -0.0 { value } else { value.signum() } })) } pub fn sin(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .sin() })) } pub fn sinh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .sinh() })) } pub fn sqrt(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
} pub fn tan(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .tan() })) } pub fn tanh(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .tanh() })) } pub fn trunc(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .trunc() })) } pub fn create_constructor(global: &Value) -> Value { let math = ValueData::new_obj(Some(global)); math.set_field_slice("E", to_value(f64::consts::E)); math.set_field_slice("LN2", to_value(f64::consts::LN_2)); math.set_field_slice("LN10", to_value(f64::consts::LN_10)); math.set_field_slice("LOG2E", to_value(f64::consts::LOG2_E)); math.set_field_slice("LOG10E", to_value(f64::consts::LOG10_E)); math.set_field_slice("SQRT1_2", to_value(0.5_f64.sqrt())); math.set_field_slice("SQRT2", to_value(f64::consts::SQRT_2)); math.set_field_slice("PI", to_value(f64::consts::PI)); make_builtin_fn!(abs, named "abs", with length 1, of math); make_builtin_fn!(acos, named "acos", with length 1, of math); make_builtin_fn!(acosh, named "acosh", with length 1, of math); make_builtin_fn!(asin, named "asin", with length 1, of math); make_builtin_fn!(asinh, named "asinh", with length 1, of math); make_builtin_fn!(atan, named "atan", with length 1, of math); make_builtin_fn!(atanh, named "atanh", with length 1, of math); make_builtin_fn!(atan2, named "atan2", with length 2, of math); make_builtin_fn!(cbrt, named "cbrt", with length 1, of math); make_builtin_fn!(ceil, named "ceil", with length 1, of math); make_builtin_fn!(cos, named "cos", with length 1, of math); make_builtin_fn!(cosh, named "cosh", with length 1, of math); make_builtin_fn!(exp, named "exp", with length 1, of math); make_builtin_fn!(floor, named "floor", with length 1, of math); make_builtin_fn!(log, named "log", with length 1, of math); make_builtin_fn!(log10, named "log10", with length 1, of math); make_builtin_fn!(log2, named "log2", with length 1, of math); make_builtin_fn!(max, named "max", with length 2, of math); make_builtin_fn!(min, named "min", with length 2, of math); make_builtin_fn!(pow, named "pow", with length 2, of math); make_builtin_fn!(_random, named "random", of math); make_builtin_fn!(round, named "round", with length 1, of math); make_builtin_fn!(sign, named "sign", with length 1, of math); make_builtin_fn!(sin, named "sin", with length 1, of math); make_builtin_fn!(sinh, named "sinh", with length 1, of math); make_builtin_fn!(sqrt, named "sqrt", with length 1, of math); make_builtin_fn!(tan, named "tan", with length 1, of math); make_builtin_fn!(tanh, named "tanh", with length 1, of math); make_builtin_fn!(trunc, named "trunc", with length 1, of math); math }
Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .sqrt() }))
call_expression
[ { "content": "/// Search for a match between this regex and a specified string\n\npub fn test(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {\n\n let arg_str = get_argument::<String>(args, 0)?;\n\n let mut last_index =\n\n from_value::<usize>(this.get_field_slice(\"lastIndex\"))...
Rust
src/game.rs
ttempleton/rust-battleship
48d45f8c5d8c73ec399e1b6781418cdb5774fdc0
use crate::direction::Direction; use crate::player::Player; use crate::settings::GameSettings; use rand::{seq::SliceRandom, thread_rng, Rng}; pub struct Game { settings: GameSettings, players: [Player; 2], state: GameState, turn: u8, } impl Game { pub fn new(settings: GameSettings) -> Result<Game, &'static str> { let grid_size = [settings.spaces[0], settings.spaces[1]]; let mut players = [ Player::new(grid_size, settings.ships.len(), false), Player::new(grid_size, settings.ships.len(), true), ]; for player in &mut players { if !player.is_cpu() { player.add_ship([0, 0], Direction::West, settings.ships[0], true)?; } else { let mut rng = thread_rng(); let mut i = 0; while i < settings.ships.len() { let pos = [ rng.gen_range(0, grid_size[0]), rng.gen_range(0, grid_size[1]), ]; if player .add_ship(pos, Direction::random(), settings.ships[i], false) .is_ok() { i += 1; } } } } Ok(Game { settings: settings, players: players, state: GameState::Placement, turn: 0, }) } pub fn settings(&self) -> &GameSettings { &self.settings } pub fn active_player(&self) -> &Player { &self.players[self.turn as usize] } pub fn inactive_player(&self) -> &Player { &self.players[self.not_turn()] } pub fn is_state_placement(&self) -> bool { self.state == GameState::Placement } pub fn is_state_active(&self) -> bool { self.state == GameState::Active } pub fn set_state_active(&mut self) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to set game as active from a state other than placement") } else { self.state = GameState::Active; self.turn = 0; Ok(()) } } pub fn is_state_complete(&self) -> bool { self.state == GameState::Complete } pub fn turn(&self) -> usize { self.turn as usize } pub fn not_turn(&self) -> usize { (self.turn + 1) as usize % 2 } pub fn switch_active_player(&mut self) { self.turn = self.not_turn() as u8; } pub fn active_player_placed_all_ships(&self) -> bool { let ships = self.active_player().ships(); ships.len() == self.settings.ships.len() && !ships[ships.len() - 1].is_placement() } pub fn is_player_placing_ship(&self) -> bool { self.state == GameState::Placement && !self.active_player().is_cpu() } pub fn is_player_selecting_space(&self) -> bool { self.state == GameState::Active && !self.active_player().is_cpu() } pub fn get_winner(&self) -> Option<usize> { match self.state { GameState::Complete => Some(self.turn as usize), _ => None, } } pub fn place_ship(&mut self) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to place ship outside of placement game state") } else { let ref mut player = self.players[self.turn as usize]; let ship_count = player.ships().len(); player.place_placement_ship()?; if ship_count < self.settings.ships.len() { player.add_ship( [0, 0], Direction::West, self.settings.ships[ship_count], true, )?; } Ok(()) } } pub fn move_ship(&mut self, direction: Direction) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to move ship outside of placement game state") } else { self.players[self.turn as usize].move_placement_ship(direction)?; Ok(()) } } pub fn rotate_ship(&mut self) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to rotate ship outside of placement game state") } else { self.players[self.turn as usize].rotate_placement_ship()?; Ok(()) } } pub fn set_placement_ship(&mut self, pos: Vec<[u8; 2]>) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to set position of ship outside of placement game state") } else { let ship = self.players[self.turn as usize].placement_ship_mut()?; ship.set_pos(pos)?; Ok(()) } } pub fn select_space(&mut self, pos: &[u8; 2]) -> Result<(), &'static str> { let ref mut opponent = self.players[self.not_turn()]; opponent.select_space(pos)?; if opponent.sink_ship_if_all_hit(pos) == Ok(true) { self.state = match opponent.all_ships_sunk() { true => GameState::Complete, false => GameState::Active, }; } Ok(()) } pub fn suggested_check(&self) -> [u8; 2] { let mut rng = thread_rng(); let mut positions = self.inactive_player().suggested_checks(); positions.shuffle(&mut rng); positions[0] } pub fn move_grid_cursor(&mut self, direction: Direction) -> Result<(), &'static str> { self.players[self.turn as usize].move_grid_cursor(direction) } pub fn set_grid_cursor(&mut self, pos: &[u8; 2]) -> Result<(), &'static str> { self.players[self.turn as usize].set_grid_cursor(pos) } } #[derive(Clone, Copy, PartialEq)] pub enum GameState { Placement, Active, Complete, }
use crate::direction::Direction; use crate::player::Player; use crate::settings::GameSettings; use rand::{seq::SliceRandom, thread_rng, Rng}; pub struct Game { settings: GameSettings, players: [Player; 2], state: GameState, turn: u8, } impl Game { pub fn new(settings: GameSettings) -> Result<Game, &'static str> { let grid_size = [settings.spaces[0], settings.spaces[1]]; let mut players = [ Player::new(grid_size, settings.ships.len(), false), Player::new(grid_size, settings.ships.len(), true), ]; for player in &mut players { if !player.is_cpu() { player.add_ship([0, 0], Direction::West, settings.ships[0], true)?; } else { let mut rng = thread_rng(); let mut i = 0; while i < settings.ships.len() { let pos = [ rng.gen_range(0, grid_size[0]), rng.gen_range(0, grid_size[1]), ]; if player .add_ship(pos, Direction::random(), settings.ships[i], false) .is_ok() { i += 1; } } } } Ok(Game {
pub fn settings(&self) -> &GameSettings { &self.settings } pub fn active_player(&self) -> &Player { &self.players[self.turn as usize] } pub fn inactive_player(&self) -> &Player { &self.players[self.not_turn()] } pub fn is_state_placement(&self) -> bool { self.state == GameState::Placement } pub fn is_state_active(&self) -> bool { self.state == GameState::Active } pub fn set_state_active(&mut self) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to set game as active from a state other than placement") } else { self.state = GameState::Active; self.turn = 0; Ok(()) } } pub fn is_state_complete(&self) -> bool { self.state == GameState::Complete } pub fn turn(&self) -> usize { self.turn as usize } pub fn not_turn(&self) -> usize { (self.turn + 1) as usize % 2 } pub fn switch_active_player(&mut self) { self.turn = self.not_turn() as u8; } pub fn active_player_placed_all_ships(&self) -> bool { let ships = self.active_player().ships(); ships.len() == self.settings.ships.len() && !ships[ships.len() - 1].is_placement() } pub fn is_player_placing_ship(&self) -> bool { self.state == GameState::Placement && !self.active_player().is_cpu() } pub fn is_player_selecting_space(&self) -> bool { self.state == GameState::Active && !self.active_player().is_cpu() } pub fn get_winner(&self) -> Option<usize> { match self.state { GameState::Complete => Some(self.turn as usize), _ => None, } } pub fn place_ship(&mut self) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to place ship outside of placement game state") } else { let ref mut player = self.players[self.turn as usize]; let ship_count = player.ships().len(); player.place_placement_ship()?; if ship_count < self.settings.ships.len() { player.add_ship( [0, 0], Direction::West, self.settings.ships[ship_count], true, )?; } Ok(()) } } pub fn move_ship(&mut self, direction: Direction) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to move ship outside of placement game state") } else { self.players[self.turn as usize].move_placement_ship(direction)?; Ok(()) } } pub fn rotate_ship(&mut self) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to rotate ship outside of placement game state") } else { self.players[self.turn as usize].rotate_placement_ship()?; Ok(()) } } pub fn set_placement_ship(&mut self, pos: Vec<[u8; 2]>) -> Result<(), &'static str> { if self.state != GameState::Placement { Err("tried to set position of ship outside of placement game state") } else { let ship = self.players[self.turn as usize].placement_ship_mut()?; ship.set_pos(pos)?; Ok(()) } } pub fn select_space(&mut self, pos: &[u8; 2]) -> Result<(), &'static str> { let ref mut opponent = self.players[self.not_turn()]; opponent.select_space(pos)?; if opponent.sink_ship_if_all_hit(pos) == Ok(true) { self.state = match opponent.all_ships_sunk() { true => GameState::Complete, false => GameState::Active, }; } Ok(()) } pub fn suggested_check(&self) -> [u8; 2] { let mut rng = thread_rng(); let mut positions = self.inactive_player().suggested_checks(); positions.shuffle(&mut rng); positions[0] } pub fn move_grid_cursor(&mut self, direction: Direction) -> Result<(), &'static str> { self.players[self.turn as usize].move_grid_cursor(direction) } pub fn set_grid_cursor(&mut self, pos: &[u8; 2]) -> Result<(), &'static str> { self.players[self.turn as usize].set_grid_cursor(pos) } } #[derive(Clone, Copy, PartialEq)] pub enum GameState { Placement, Active, Complete, }
settings: settings, players: players, state: GameState::Placement, turn: 0, }) }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let settings = settings::AppSettings { space_size: 20 };\n\n let mut app = app::App::new(&settings);\n\n\n\n app.init();\n\n}\n", "file_path": "src/main.rs", "rank": 0, "score": 28101.960460366587 }, { "content": "pub struct AppSettings {\n\n pub spa...
Rust
src/kmain.rs
hobo0xcc/citron
46fb564f0f7e360fa4e210f5963b121eb8f98594
use crate::arch::riscv64::virtio::gpu_device; use crate::arch::riscv64::virtio::keyboard_device; use crate::arch::riscv64::virtio::mouse_device; use crate::arch::target::interrupt; use crate::arch::target::virtio::virtio_input::*; use crate::graphics::layer_manager; use crate::graphics::*; use crate::process::*; use crate::*; pub unsafe extern "C" fn kproc() { let pm = process_manager(); let mouse = mouse_device(); let keyboard = keyboard_device(); let gpu = gpu_device(); mouse.lock().init_input_event(); keyboard.lock().init_input_event(); gpu.lock().init_display(); graphics::init(); let lm = layer_manager(); loop { let queue = &mut mouse.lock().event_queue; if queue.is_empty() { pm.event_wait(pm.running, ProcessEvent::MouseEvent) .expect("process"); continue; } let mut event = queue.pop_front(); while let Some(ev) = event { match EventType::from(ev.type_) { EventType::EV_REL => { if ev.code == EV_REL::REL_X as u16 { lm.move_rel(MOUSE_LAYER_ID, ev.value as i32, 0); } else if ev.code == EV_REL::REL_Y as u16 { lm.move_rel(MOUSE_LAYER_ID, 0, ev.value as i32); } } EventType::EV_KEY => { if ev.code == EV_KEY::BTN_LEFT as u16 && ev.value == 1 { let x = lm.get_layer_x(MOUSE_LAYER_ID); let y = lm.get_layer_y(MOUSE_LAYER_ID); lm.on_event(ObjectEvent::MouseLeftPress(x, y), MOUSE_LAYER_ID); } else if ev.code == EV_KEY::BTN_LEFT as u16 && ev.value == 0 { let x = lm.get_layer_x(MOUSE_LAYER_ID); let y = lm.get_layer_y(MOUSE_LAYER_ID); lm.on_event(ObjectEvent::MouseLeftRelease(x, y), MOUSE_LAYER_ID); } } EventType::EV_SYN => { lm.update(MOUSE_LAYER_ID); } _ => {} } event = queue.pop_front(); } } } pub unsafe extern "C" fn fs_proc() { fs::fat::init(); fs::init(); let pm = process_manager(); let pid = pm.create_process("user", 1, true).expect("process"); pm.load_program(pid, "/bin/main").expect("process"); pm.ready(pid).expect("process"); let running = pm.running; get_process_mut!(pm.ptable_lock_mut(), running) .expect("process") .state = State::Free; pm.schedule().expect("process"); loop { pm.schedule().expect("process"); } } #[no_mangle] pub extern "C" fn kmain() { let mut hart_id: usize; unsafe { asm!("mv {}, tp", out(reg)hart_id); } if hart_id != 0 { loop {} } unsafe { init::init_all(); } println!("Initialization done"); println!("Hello, citron!"); let pm = unsafe { process::process_manager() }; interrupt::timer_interrupt_off(); interrupt::interrupt_on(); pm.defer_schedule(DeferCommand::Start).expect("process"); let pid = pm .create_kernel_process("fs", 1, fs_proc as usize) .expect("process"); pm.ready(pid).expect("process"); let pid = pm .create_kernel_process("kproc", 2, kproc as usize) .expect("process"); pm.ready(pid).expect("process"); pm.defer_schedule(DeferCommand::Stop).expect("process"); interrupt::timer_interrupt_on(); loop { pm.schedule().expect("process"); } }
use crate::arch::riscv64::virtio::gpu_device; use crate::arch::riscv64::virtio::keyboard_device; use crate::arch::riscv64::virtio::mouse_device; use crate::arch::target::interrupt; use crate::arch::target::virtio::virtio_input::*; use crate::graphics::layer_manager; use crate::graphics::*; use crate::process::*; use crate::*; pub unsafe extern "C" fn kproc() { let pm = process_manager(); let mouse = mouse_device(); let keyboard = keyboard_device(); let gpu = gpu_device(); mouse.lock().init_input_event(); keyboard.lock().init_input_event(); gpu.lock().init_display(); graphics::init(); let lm = layer_manager(); loop { let queue = &mut mouse.lock().event_queue; if queue.is_empty() { pm.event_wait(pm.running, ProcessEvent::MouseEvent) .expect("process"); continue; } let mut event = queue.pop_front(); while let Some(ev) = event { match EventType::from(ev.type_) { EventType::EV_REL => { if ev.code == EV_REL::REL_X as u16 { lm.move_rel(MOUSE_LAYER_ID, ev.value as i32, 0); } else if ev.code == EV_REL::REL_Y as u16 { lm.move_rel(MOUSE_LAYER_ID, 0, ev.value as i32); } } EventType::EV_KEY => {
} EventType::EV_SYN => { lm.update(MOUSE_LAYER_ID); } _ => {} } event = queue.pop_front(); } } } pub unsafe extern "C" fn fs_proc() { fs::fat::init(); fs::init(); let pm = process_manager(); let pid = pm.create_process("user", 1, true).expect("process"); pm.load_program(pid, "/bin/main").expect("process"); pm.ready(pid).expect("process"); let running = pm.running; get_process_mut!(pm.ptable_lock_mut(), running) .expect("process") .state = State::Free; pm.schedule().expect("process"); loop { pm.schedule().expect("process"); } } #[no_mangle] pub extern "C" fn kmain() { let mut hart_id: usize; unsafe { asm!("mv {}, tp", out(reg)hart_id); } if hart_id != 0 { loop {} } unsafe { init::init_all(); } println!("Initialization done"); println!("Hello, citron!"); let pm = unsafe { process::process_manager() }; interrupt::timer_interrupt_off(); interrupt::interrupt_on(); pm.defer_schedule(DeferCommand::Start).expect("process"); let pid = pm .create_kernel_process("fs", 1, fs_proc as usize) .expect("process"); pm.ready(pid).expect("process"); let pid = pm .create_kernel_process("kproc", 2, kproc as usize) .expect("process"); pm.ready(pid).expect("process"); pm.defer_schedule(DeferCommand::Stop).expect("process"); interrupt::timer_interrupt_on(); loop { pm.schedule().expect("process"); } }
if ev.code == EV_KEY::BTN_LEFT as u16 && ev.value == 1 { let x = lm.get_layer_x(MOUSE_LAYER_ID); let y = lm.get_layer_y(MOUSE_LAYER_ID); lm.on_event(ObjectEvent::MouseLeftPress(x, y), MOUSE_LAYER_ID); } else if ev.code == EV_KEY::BTN_LEFT as u16 && ev.value == 0 { let x = lm.get_layer_x(MOUSE_LAYER_ID); let y = lm.get_layer_y(MOUSE_LAYER_ID); lm.on_event(ObjectEvent::MouseLeftRelease(x, y), MOUSE_LAYER_ID); }
if_condition
[ { "content": "pub fn unmap(root: &mut Table) {\n\n let page_layout = Layout::from_size_align(0x1000, 0x1000).unwrap();\n\n #[cfg(target_pointer_width = \"32\")]\n\n for lv2 in 0..Table::len() {\n\n let ref entry_lv2 = root.entries[lv2];\n\n if entry_lv2.is_valid() && entry_lv2.is_branch()...
Rust
src/main.rs
Shirataki2/atcoder-discord-bot
236023c7d2a29d09c62785249230eddea92ceeae
#![warn(clippy::all)] mod commands; mod tasks; mod models; mod database; mod utils; mod data; mod event_handler; mod error; mod http; #[macro_use] extern crate log; #[macro_use] extern crate sqlx; use crate::{ utils::send_error, data::{DatabasePool, ShardManagerContainer, SubmissionQueue}, event_handler::Handler, models::{account::Account as DiscordAccount, submission::Submission} }; use commands::{ help::*, general::{invite::*, source::*}, account::{register::*, unregister::*, subscribe::*, unsubscribe::*}, settings::{start::*, stop::*}, stat::{streak::*, problem_count::*, point_sum::*}, }; use std::{collections::*, env, sync::Arc}; use serenity::{ prelude::*, http::Http, framework::{ StandardFramework, standard::{ macros::{group, hook}, DispatchError, CommandResult } }, model::{ channel::Message, }, }; use dotenv::dotenv; #[hook] async fn before(_: &Context, msg: &Message, command_name: &str) -> bool { info!("Get command `{}` by user {}({})", command_name, msg.author.name, msg.author.id); true } #[hook] async fn after(ctx: &Context, msg: &Message, command_name: &str, error: CommandResult) { if let Err(why) = &error { error!("Error while running command {}", &command_name); error!("{:?}", &error); if send_error(ctx, msg, "Error!", format!("{}", why).as_str()).await.is_err() { error!( "Unable to send messages on channel id {}", &msg.channel_id.0 ); }; } } #[hook] #[allow(clippy::useless_format)] async fn on_dispatch_error(ctx: &Context, msg: &Message, error: DispatchError) { match error { DispatchError::NotEnoughArguments { min, given } => { let description = match (min, given) { (1, 0) => format!("This command requires one argument"), (m, 0) => format!("This command requires at least {} arguments to run", m), (m, g) => format!("This command requires at least {} arguments, but you give {} arguments", m, g), }; let _ = send_error(ctx, msg, "Not Enough Arguments!", &description).await; } DispatchError::OnlyForGuilds => { let description = format!("This command does not work on DM."); let _ = send_error(ctx, msg, "Only For Guilds!", &description).await; } DispatchError::Ratelimited(dur) => { let description = format!("You cannot run this command for {} seconds.", dur.as_secs()); let _ = send_error(ctx, msg, "Rate Limited!", &description).await; } DispatchError::LackingPermissions(perms) => { let description = format!("This command requires `{}` permission(s).", perms); let _ = send_error(ctx, msg, "Permission Error!", &description).await; } _ => { error!("Unhandled dispatch error: {:?}", error); } } } #[group] #[commands(invite, source)] struct General; #[group] #[commands(register, unregister, subscribe, unsubscribe)] struct Account; #[group] #[commands(start, stop)] struct Settings; #[group] #[commands(streak, problem, point)] struct Ranking; #[tokio::main(flavor = "multi_thread", worker_threads = 8)] async fn main() { if let Err(e) = dotenv() { warn!("Failed to load .env: {:?}", e); } env_logger::init(); let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment (DISCORD_TOKEN)"); let http = Http::new_with_token(&token); let owners = http.get_current_application_info() .await .map(|info| { let mut map = HashSet::new(); map.insert(info.owner.id); map }) .unwrap(); let framework = StandardFramework::new() .configure(|c| c.owners(owners).prefix("^")) .bucket("basic", |b| b.delay(1).time_span(5).limit(5)).await .bucket("account", |b| b.delay(3).time_span(10).limit(2)).await .before(before) .after(after) .on_dispatch_error(on_dispatch_error) .help(&MY_HELP) .group(&GENERAL_GROUP) .group(&SETTINGS_GROUP) .group(&ACCOUNT_GROUP) .group(&RANKING_GROUP); let mut client = Client::builder(&token) .framework(framework) .event_handler(Handler::new()) .await .expect("Failed to create client."); { let mut data = client.data.write().await; data.insert::<ShardManagerContainer>(client.shard_manager.clone()); let pg_pool = database::create_pgpool().await.expect("Failed to connect database"); data.insert::<DatabasePool>(pg_pool); let map = Arc::new(Mutex::new(HashMap::<i64, VecDeque<(DiscordAccount, Submission)>>::new())); data.insert::<SubmissionQueue>(map); } let shard_manager = client.shard_manager.clone(); tokio::spawn(async move { tokio::signal::ctrl_c().await.expect("Failed to register SIGINT handler"); shard_manager.lock().await.shutdown_all().await; }); if let Err(why) = client.start().await { error!("Client error: {:?}", why); } }
#![warn(clippy::all)] mod commands; mod tasks; mod models; mod database; mod utils; mod data; mod event_handler; mod error; mod http; #[macro_use] extern crate log; #[macro_use] extern crate sqlx; use crate::{ utils::send_error, data::{DatabasePool, ShardManagerContainer, SubmissionQueue}, event_handler::Handler, models::{account::Account as DiscordAccount, submission::Submission} }; use commands::{ help::*, general::{invite::*, source::*}, account::{register::*, unregister::*, subscribe::*, unsubscribe::*}, settings::{start::*, stop::*}, stat::{streak::*, problem_count::*, point_sum::*}, }; use std::{collections::*, env, sync::Arc}; use serenity::{ prelude::*, http::Http, framework::{ StandardFramework, standard::{ macros::{group, hook}, DispatchError, CommandResult } }, model::{ channel::Message, }, }; use dotenv::dotenv; #[hook] async fn before(_: &Context, msg: &Message, command_name: &str) -> bool { info!("Get command `{}` by user {}({})", command_name, msg.author.name, msg.author.id); true } #[hook] async fn after(ctx: &Context, msg: &Message, command_name: &str, error: CommandResult) { if let Err(why) = &error { error!("Error while running command {}", &command_name); error!("{:?}", &error); if send_error(ctx, msg, "Error!", format!("{}", why).as_str()).await.is_err() { error!( "Unable to send messages on channel id {}", &msg.channel_id.0 ); }; } } #[hook] #[allow(clippy::useless_format)] async fn on_dispatch_error(ctx: &Context, msg: &Message, error: DispatchError) { match error { DispatchError::NotEnoughArguments { min, given } => { let description = match (min, given) { (1, 0) => format!("This command requires one argument"), (
#[group] #[commands(invite, source)] struct General; #[group] #[commands(register, unregister, subscribe, unsubscribe)] struct Account; #[group] #[commands(start, stop)] struct Settings; #[group] #[commands(streak, problem, point)] struct Ranking; #[tokio::main(flavor = "multi_thread", worker_threads = 8)] async fn main() { if let Err(e) = dotenv() { warn!("Failed to load .env: {:?}", e); } env_logger::init(); let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment (DISCORD_TOKEN)"); let http = Http::new_with_token(&token); let owners = http.get_current_application_info() .await .map(|info| { let mut map = HashSet::new(); map.insert(info.owner.id); map }) .unwrap(); let framework = StandardFramework::new() .configure(|c| c.owners(owners).prefix("^")) .bucket("basic", |b| b.delay(1).time_span(5).limit(5)).await .bucket("account", |b| b.delay(3).time_span(10).limit(2)).await .before(before) .after(after) .on_dispatch_error(on_dispatch_error) .help(&MY_HELP) .group(&GENERAL_GROUP) .group(&SETTINGS_GROUP) .group(&ACCOUNT_GROUP) .group(&RANKING_GROUP); let mut client = Client::builder(&token) .framework(framework) .event_handler(Handler::new()) .await .expect("Failed to create client."); { let mut data = client.data.write().await; data.insert::<ShardManagerContainer>(client.shard_manager.clone()); let pg_pool = database::create_pgpool().await.expect("Failed to connect database"); data.insert::<DatabasePool>(pg_pool); let map = Arc::new(Mutex::new(HashMap::<i64, VecDeque<(DiscordAccount, Submission)>>::new())); data.insert::<SubmissionQueue>(map); } let shard_manager = client.shard_manager.clone(); tokio::spawn(async move { tokio::signal::ctrl_c().await.expect("Failed to register SIGINT handler"); shard_manager.lock().await.shutdown_all().await; }); if let Err(why) = client.start().await { error!("Client error: {:?}", why); } }
m, 0) => format!("This command requires at least {} arguments to run", m), (m, g) => format!("This command requires at least {} arguments, but you give {} arguments", m, g), }; let _ = send_error(ctx, msg, "Not Enough Arguments!", &description).await; } DispatchError::OnlyForGuilds => { let description = format!("This command does not work on DM."); let _ = send_error(ctx, msg, "Only For Guilds!", &description).await; } DispatchError::Ratelimited(dur) => { let description = format!("You cannot run this command for {} seconds.", dur.as_secs()); let _ = send_error(ctx, msg, "Rate Limited!", &description).await; } DispatchError::LackingPermissions(perms) => { let description = format!("This command requires `{}` permission(s).", perms); let _ = send_error(ctx, msg, "Permission Error!", &description).await; } _ => { error!("Unhandled dispatch error: {:?}", error); } } }
function_block-function_prefix_line
[ { "content": "pub fn unknown_error() -> CommandError {\n\n CommandError::from(\"Unknown error has occurred.\\n\\\n\n If you get this error repeatedly, please contact `admin@sample.com`.\")\n\n}\n", "file_path": "src/utils.rs", "rank": 0, "score": 111059.39148688925 }, { "content": ...
Rust
src/zcm.rs
Gregory-Meyer/zcm-rs
6e9e6e9be1f4324260c239e7054ee0313056be3c
extern crate std; use super::*; pub struct Zcm { zcm: ffi::zcm_t, } impl Zcm { pub fn new(url: &str) -> Result<Zcm, NewError> { let url_owned = match std::ffi::CString::new(url) { Ok(u) => u, Err(e) => return Err(NewError::Nul(e)), }; let mut zcm = Zcm { zcm: unsafe { std::mem::uninitialized() }, }; if unsafe { ffi::zcm_init(zcm.as_mut_ptr(), url_owned.as_ptr()) } != 0 { return Err(NewError::Error(zcm.errno().unwrap())); } Ok(zcm) } pub fn errno(&self) -> Option<Error> { let err = unsafe { ffi::zcm_errno(self.as_ptr()) }; Error::from_raw(err) } pub fn strerror(&self) -> std::borrow::Cow<str> { let err = unsafe { ffi::zcm_strerror(self.as_ptr()) }; unsafe { std::ffi::CStr::from_ptr(err) }.to_string_lossy() } pub fn flush(&mut self) { unsafe { ffi::zcm_flush(self.as_mut_ptr()) }; } pub fn try_flush(&mut self) -> Result<(), Error> { let result = unsafe { ffi::zcm_try_flush(self.as_mut_ptr()) }; match Error::from_raw(result) { None => Ok(()), Some(e) => Err(e), } } pub fn as_ptr(&self) -> *const ffi::zcm_t { &self.zcm as *const ffi::zcm_t } pub fn as_mut_ptr(&mut self) -> *mut ffi::zcm_t { &mut self.zcm as *mut ffi::zcm_t } } impl Drop for Zcm { fn drop(&mut self) { unsafe { ffi::zcm_cleanup(&mut self.zcm as *mut ffi::zcm_t) } } } #[derive(Clone, Copy, Debug)] pub enum Error { Invalid, Again, Connect, Interrupted, Unknown, NumReturnCodes, } impl Error { pub fn from_raw(err: libc::c_int) -> Option<Error> { use ffi::zcm_return_codes::*; if err < 0 || err >= unsafe { std::mem::transmute(ZCM_NUM_RETURN_CODES) } { return Some(Error::NumReturnCodes); } match unsafe { std::mem::transmute(err) } { ZCM_EOK => None, ZCM_EINVALID => Some(Error::Invalid), ZCM_EAGAIN => Some(Error::Again), ZCM_ECONNECT => Some(Error::Connect), ZCM_EINTR => Some(Error::Interrupted), ZCM_EUNKNOWN => Some(Error::Unknown), _ => Some(Error::NumReturnCodes), } } pub fn as_int(&self) -> libc::c_int { use ffi::zcm_return_codes::*; let underlying = match self { Error::Invalid => ZCM_EINVALID, Error::Again => ZCM_EAGAIN, Error::Connect => ZCM_ECONNECT, Error::Interrupted => ZCM_EINTR, Error::Unknown => ZCM_EUNKNOWN, Error::NumReturnCodes => ZCM_NUM_RETURN_CODES, }; unsafe { std::mem::transmute(underlying) } } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let as_str = unsafe { std::ffi::CStr::from_ptr(ffi::zcm_strerrno(self.as_int())) }; write!(f, "{}", as_str.to_string_lossy()) } } impl std::error::Error for Error {} #[derive(Clone, Debug)] pub enum NewError { Nul(std::ffi::NulError), Error(Error), } impl std::fmt::Display for NewError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { NewError::Nul(e) => write!(f, "{}", e), NewError::Error(e) => write!(f, "{}", e), } } } impl std::error::Error for NewError {}
extern crate std; use super::*; pub struct Zcm { zcm: ffi::zcm_t, } impl Zcm { pub fn new(url: &str) -> Result<Zcm, NewError> { let url_owned = match std::ffi::CString::new(url) { Ok(u) => u, Err(e) => return Err(NewError::Nul(e)), }; let mut zcm = Zcm { zcm: unsafe { std::mem::uninitialized() }, }; if unsafe { ffi::zcm_init(zcm.as_mut_ptr(), url_owned.as_ptr()) } != 0 { return Err(NewError::Error(zcm.errno().unwrap())); } Ok(zcm) } pub fn errno(&self) -> Option<Error> { let err = unsafe { ffi::zcm_errno(self.as_ptr()) }; Error::from_raw(err) } pub fn strerror(&self) -> std::borrow::Cow<str> {
} } pub fn as_ptr(&self) -> *const ffi::zcm_t { &self.zcm as *const ffi::zcm_t } pub fn as_mut_ptr(&mut self) -> *mut ffi::zcm_t { &mut self.zcm as *mut ffi::zcm_t } } impl Drop for Zcm { fn drop(&mut self) { unsafe { ffi::zcm_cleanup(&mut self.zcm as *mut ffi::zcm_t) } } } #[derive(Clone, Copy, Debug)] pub enum Error { Invalid, Again, Connect, Interrupted, Unknown, NumReturnCodes, } impl Error { pub fn from_raw(err: libc::c_int) -> Option<Error> { use ffi::zcm_return_codes::*; if err < 0 || err >= unsafe { std::mem::transmute(ZCM_NUM_RETURN_CODES) } { return Some(Error::NumReturnCodes); } match unsafe { std::mem::transmute(err) } { ZCM_EOK => None, ZCM_EINVALID => Some(Error::Invalid), ZCM_EAGAIN => Some(Error::Again), ZCM_ECONNECT => Some(Error::Connect), ZCM_EINTR => Some(Error::Interrupted), ZCM_EUNKNOWN => Some(Error::Unknown), _ => Some(Error::NumReturnCodes), } } pub fn as_int(&self) -> libc::c_int { use ffi::zcm_return_codes::*; let underlying = match self { Error::Invalid => ZCM_EINVALID, Error::Again => ZCM_EAGAIN, Error::Connect => ZCM_ECONNECT, Error::Interrupted => ZCM_EINTR, Error::Unknown => ZCM_EUNKNOWN, Error::NumReturnCodes => ZCM_NUM_RETURN_CODES, }; unsafe { std::mem::transmute(underlying) } } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let as_str = unsafe { std::ffi::CStr::from_ptr(ffi::zcm_strerrno(self.as_int())) }; write!(f, "{}", as_str.to_string_lossy()) } } impl std::error::Error for Error {} #[derive(Clone, Debug)] pub enum NewError { Nul(std::ffi::NulError), Error(Error), } impl std::fmt::Display for NewError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { NewError::Nul(e) => write!(f, "{}", e), NewError::Error(e) => write!(f, "{}", e), } } } impl std::error::Error for NewError {}
let err = unsafe { ffi::zcm_strerror(self.as_ptr()) }; unsafe { std::ffi::CStr::from_ptr(err) }.to_string_lossy() } pub fn flush(&mut self) { unsafe { ffi::zcm_flush(self.as_mut_ptr()) }; } pub fn try_flush(&mut self) -> Result<(), Error> { let result = unsafe { ffi::zcm_try_flush(self.as_mut_ptr()) }; match Error::from_raw(result) { None => Ok(()), Some(e) => Err(e),
random
[ { "content": "#[test]\n\nfn foo() {\n\n let mut zcm = Zcm::new(\"ipc\").unwrap();\n\n let channel = std::ffi::CString::new(\"foo\").unwrap();\n\n\n\n let mut received = false;\n\n\n\n let sub = unsafe {\n\n ffi::zcm_subscribe(\n\n zcm.as_mut_ptr(),\n\n channel.as_ptr(),\...
Rust
crates/graphics/src/api/vulkan/texture.rs
gents83/NRG
62743a54ac873a8dea359f3816e24c189a323ebb
use super::{ copy_buffer_to_image, copy_from_buffer, copy_image_to_buffer, copy_to_buffer, create_buffer, create_image, create_image_view, destroy_buffer, }; use super::{device::BackendDevice, find_depth_format}; use crate::api::backend::physical_device::BackendPhysicalDevice; use crate::{Area, TEXTURE_CHANNEL_COUNT}; use vulkan_bindings::*; pub struct BackendTexture { width: u32, height: u32, layers_count: u32, texture_image: VkImage, texture_image_memory: VkDeviceMemory, texture_image_view: VkImageView, texture_sampler: VkSampler, } unsafe impl Send for BackendTexture {} unsafe impl Sync for BackendTexture {} impl BackendTexture { pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } pub fn layers_count(&self) -> u32 { self.layers_count } pub fn create( device: &BackendDevice, physical_device: &BackendPhysicalDevice, width: u32, height: u32, layers_count: u32, ) -> Self { let mut texture = Self { width, height, layers_count, texture_image: ::std::ptr::null_mut(), texture_image_memory: ::std::ptr::null_mut(), texture_image_view: ::std::ptr::null_mut(), texture_sampler: ::std::ptr::null_mut(), }; texture.create_texture_image( device, physical_device, VkFormat_VK_FORMAT_R8G8B8A8_UNORM, layers_count, 0, VkImageAspectFlagBits_VK_IMAGE_ASPECT_COLOR_BIT, ); texture.create_texture_sampler(device, physical_device); texture } pub fn create_as_render_target( device: &BackendDevice, physical_device: &BackendPhysicalDevice, width: u32, height: u32, layers_count: u32, is_depth: bool, ) -> Self { let mut texture = Self { width, height, layers_count, texture_image: ::std::ptr::null_mut(), texture_image_memory: ::std::ptr::null_mut(), texture_image_view: ::std::ptr::null_mut(), texture_sampler: ::std::ptr::null_mut(), }; let format = if is_depth { find_depth_format(**physical_device) } else { VkFormat_VK_FORMAT_R8G8B8A8_UNORM }; let specific_flags = if is_depth { VkImageUsageFlagBits_VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT as _ } else { VkImageUsageFlagBits_VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT as _ }; let aspect_flags = if is_depth { (VkImageAspectFlagBits_VK_IMAGE_ASPECT_DEPTH_BIT | VkImageAspectFlagBits_VK_IMAGE_ASPECT_STENCIL_BIT) as _ } else { VkImageAspectFlagBits_VK_IMAGE_ASPECT_COLOR_BIT as _ }; texture.create_texture_image( device, physical_device, format, layers_count, specific_flags, aspect_flags, ); texture.create_texture_sampler(device, physical_device); texture } pub fn destroy(&self, device: &BackendDevice) { unsafe { vkDestroySampler.unwrap()(**device, self.texture_sampler, ::std::ptr::null_mut()); vkDestroyImageView.unwrap()(**device, self.texture_image_view, ::std::ptr::null_mut()); vkDestroyImage.unwrap()(**device, self.texture_image, ::std::ptr::null_mut()); vkFreeMemory.unwrap()(**device, self.texture_image_memory, ::std::ptr::null_mut()); } } pub fn get_descriptor(&self) -> VkDescriptorImageInfo { VkDescriptorImageInfo { imageLayout: VkImageLayout_VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, imageView: self.texture_image_view, sampler: self.texture_sampler, } } pub fn get_image(&self) -> VkImage { self.texture_image } pub fn get_image_view(&self) -> VkImageView { self.texture_image_view } pub fn add_in_layer( &mut self, device: &BackendDevice, physical_device: &BackendPhysicalDevice, index: u32, area: &Area, image_data: &[u8], ) { sabi_profiler::scoped_profile!("texture::add_in_layer"); if self.width < area.width || self.height < area.height { panic!("Image resolution is different from texture one"); } let image_size: VkDeviceSize = (area.width * area.height * TEXTURE_CHANNEL_COUNT) as _; let flags = VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; let mut staging_buffer: VkBuffer = ::std::ptr::null_mut(); let mut staging_buffer_memory: VkDeviceMemory = ::std::ptr::null_mut(); create_buffer( device, physical_device, image_size as _, VkBufferUsageFlagBits_VK_BUFFER_USAGE_TRANSFER_SRC_BIT as _, flags as _, &mut staging_buffer, &mut staging_buffer_memory, ); copy_from_buffer(device, &mut staging_buffer_memory, 0, image_data); copy_buffer_to_image( device, staging_buffer, self.texture_image, index, self.layers_count, area, ); destroy_buffer(device, &staging_buffer, &staging_buffer_memory); } pub fn get_from_layer( &self, device: &BackendDevice, physical_device: &BackendPhysicalDevice, index: u32, area: &Area, image_data: &mut [u8], ) { sabi_profiler::scoped_profile!("texture::get_from_layer"); if self.width < area.width || self.height < area.height { panic!("Image resolution is different from texture one"); } let image_size: VkDeviceSize = (area.width * area.height * TEXTURE_CHANNEL_COUNT) as _; let flags = VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_HOST_CACHED_BIT; let mut staging_buffer: VkBuffer = ::std::ptr::null_mut(); let mut staging_buffer_memory: VkDeviceMemory = ::std::ptr::null_mut(); create_buffer( device, physical_device, image_size as _, VkBufferUsageFlagBits_VK_BUFFER_USAGE_TRANSFER_DST_BIT as _, flags as _, &mut staging_buffer, &mut staging_buffer_memory, ); copy_image_to_buffer( device, self.texture_image, staging_buffer, index, self.layers_count, area, ); copy_to_buffer(device, &mut staging_buffer_memory, 0, image_data); destroy_buffer(device, &staging_buffer, &staging_buffer_memory); } fn create_texture_image( &mut self, device: &BackendDevice, physical_device: &BackendPhysicalDevice, format: VkFormat, layers_count: u32, specific_flags: i32, aspect_flags: i32, ) { let flags = specific_flags | VkImageUsageFlagBits_VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VkImageUsageFlagBits_VK_IMAGE_USAGE_TRANSFER_DST_BIT | VkImageUsageFlagBits_VK_IMAGE_USAGE_SAMPLED_BIT; let (device_image, device_image_memory) = create_image( device, physical_device, (self.width, self.height, format), VkImageTiling_VK_IMAGE_TILING_OPTIMAL, flags as _, VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT as _, layers_count, ); self.texture_image = device_image; self.texture_image_memory = device_image_memory; self.texture_image_view = create_image_view( **device, self.texture_image, format, aspect_flags as _, layers_count, ); } fn create_texture_sampler( &mut self, device: &BackendDevice, physical_device: &BackendPhysicalDevice, ) { let properties = physical_device.get_properties(); let sampler_info = VkSamplerCreateInfo { sType: VkStructureType_VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, pNext: ::std::ptr::null_mut(), flags: 0, magFilter: VkFilter_VK_FILTER_LINEAR, minFilter: VkFilter_VK_FILTER_LINEAR, mipmapMode: VkSamplerMipmapMode_VK_SAMPLER_MIPMAP_MODE_LINEAR, addressModeU: VkSamplerAddressMode_VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, addressModeV: VkSamplerAddressMode_VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, addressModeW: VkSamplerAddressMode_VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, mipLodBias: 0.0, anisotropyEnable: VK_TRUE, maxAnisotropy: properties.limits.maxSamplerAnisotropy, compareEnable: VK_FALSE, compareOp: VkCompareOp_VK_COMPARE_OP_NEVER, minLod: 0.0, maxLod: 1.0, borderColor: VkBorderColor_VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, unnormalizedCoordinates: VK_FALSE, }; self.texture_sampler = unsafe { let mut option = ::std::mem::MaybeUninit::uninit(); assert_eq!( VkResult_VK_SUCCESS, vkCreateSampler.unwrap()( **device, &sampler_info, ::std::ptr::null_mut(), option.as_mut_ptr() ) ); option.assume_init() }; } }
use super::{ copy_buffer_to_image, copy_from_buffer, copy_image_to_buffer, copy_to_buffer, create_buffer, create_image, create_image_view, destroy_buffer, }; use super::{device::BackendDevice, find_depth_format}; use crate::api::backend::physical_device::BackendPhysicalDevice; use crate::{Area, TEXTURE_CHANNEL_COUNT}; use vulkan_bindings::*; pub struct BackendTexture { width: u32, height: u32, layers_count: u32, texture_image: VkImage, texture_image_memory: VkDeviceMemory, texture_image_view: VkImageView, texture_sampler: VkSampler, } unsafe impl Send for BackendTexture {} unsafe impl Sync for BackendTexture {} impl BackendTexture { pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } pub fn layers_count(&self) -> u32 { self.layers_count } pub fn create( device: &BackendDevice, physical_device: &BackendPhysicalDevice, width: u32, height: u32, layers_count: u32, ) -> Self { let mut texture = Self { width, height, layers_count, texture_image: ::std::ptr::null_mut(), texture_image_memory: ::std::ptr::null_mut(), texture_image_view: ::std::ptr::null_mut(), texture_sampler: ::std::ptr::null_mut(), }; texture.create_texture_image( device, physical_device, VkFormat_VK_FORMAT_R8G8B8A8_UNORM, layers_count, 0, VkImageAspectFlagBits_VK_IMAGE_ASPECT_COLOR_BIT, ); texture.create_texture_sampler(device, physical_device); texture } pub fn create_as_render_target( device: &BackendDevice, physical_device: &BackendPhysicalDevice, width: u32, height: u32, layers_count: u32, is_depth: bool, ) -> Self { let mut texture = Self { width, height, layers_count, texture_image: ::std::ptr::null_mut(), texture_image_memory: ::std::ptr::null_mut(), texture_image_view: ::std::ptr::null_mut(), texture_sampler: ::std::ptr::null_mut(), }; let format = if is_depth { find_depth_format(**physical_device) } else { VkFormat_VK_FORMAT_R8G8B8A8_UNORM }; let specific_flags = if is_depth { VkImageUsageFlagBits_VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT as _ } else { VkImageUsageFlagBits_VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT as _ }; let aspect_flags = if is_depth { (VkImageAspectFlagBits_VK_IMAGE_ASPECT_DEPTH_BIT | VkImageAspectFlagBits_VK_IMAGE_ASPECT_STENCIL_BIT) as _ } else { VkImageAspectFlagBits_VK_IMAGE_ASPECT_COLOR_BIT as _ }; texture.create_texture_imag
pub fn destroy(&self, device: &BackendDevice) { unsafe { vkDestroySampler.unwrap()(**device, self.texture_sampler, ::std::ptr::null_mut()); vkDestroyImageView.unwrap()(**device, self.texture_image_view, ::std::ptr::null_mut()); vkDestroyImage.unwrap()(**device, self.texture_image, ::std::ptr::null_mut()); vkFreeMemory.unwrap()(**device, self.texture_image_memory, ::std::ptr::null_mut()); } } pub fn get_descriptor(&self) -> VkDescriptorImageInfo { VkDescriptorImageInfo { imageLayout: VkImageLayout_VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, imageView: self.texture_image_view, sampler: self.texture_sampler, } } pub fn get_image(&self) -> VkImage { self.texture_image } pub fn get_image_view(&self) -> VkImageView { self.texture_image_view } pub fn add_in_layer( &mut self, device: &BackendDevice, physical_device: &BackendPhysicalDevice, index: u32, area: &Area, image_data: &[u8], ) { sabi_profiler::scoped_profile!("texture::add_in_layer"); if self.width < area.width || self.height < area.height { panic!("Image resolution is different from texture one"); } let image_size: VkDeviceSize = (area.width * area.height * TEXTURE_CHANNEL_COUNT) as _; let flags = VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; let mut staging_buffer: VkBuffer = ::std::ptr::null_mut(); let mut staging_buffer_memory: VkDeviceMemory = ::std::ptr::null_mut(); create_buffer( device, physical_device, image_size as _, VkBufferUsageFlagBits_VK_BUFFER_USAGE_TRANSFER_SRC_BIT as _, flags as _, &mut staging_buffer, &mut staging_buffer_memory, ); copy_from_buffer(device, &mut staging_buffer_memory, 0, image_data); copy_buffer_to_image( device, staging_buffer, self.texture_image, index, self.layers_count, area, ); destroy_buffer(device, &staging_buffer, &staging_buffer_memory); } pub fn get_from_layer( &self, device: &BackendDevice, physical_device: &BackendPhysicalDevice, index: u32, area: &Area, image_data: &mut [u8], ) { sabi_profiler::scoped_profile!("texture::get_from_layer"); if self.width < area.width || self.height < area.height { panic!("Image resolution is different from texture one"); } let image_size: VkDeviceSize = (area.width * area.height * TEXTURE_CHANNEL_COUNT) as _; let flags = VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_HOST_CACHED_BIT; let mut staging_buffer: VkBuffer = ::std::ptr::null_mut(); let mut staging_buffer_memory: VkDeviceMemory = ::std::ptr::null_mut(); create_buffer( device, physical_device, image_size as _, VkBufferUsageFlagBits_VK_BUFFER_USAGE_TRANSFER_DST_BIT as _, flags as _, &mut staging_buffer, &mut staging_buffer_memory, ); copy_image_to_buffer( device, self.texture_image, staging_buffer, index, self.layers_count, area, ); copy_to_buffer(device, &mut staging_buffer_memory, 0, image_data); destroy_buffer(device, &staging_buffer, &staging_buffer_memory); } fn create_texture_image( &mut self, device: &BackendDevice, physical_device: &BackendPhysicalDevice, format: VkFormat, layers_count: u32, specific_flags: i32, aspect_flags: i32, ) { let flags = specific_flags | VkImageUsageFlagBits_VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VkImageUsageFlagBits_VK_IMAGE_USAGE_TRANSFER_DST_BIT | VkImageUsageFlagBits_VK_IMAGE_USAGE_SAMPLED_BIT; let (device_image, device_image_memory) = create_image( device, physical_device, (self.width, self.height, format), VkImageTiling_VK_IMAGE_TILING_OPTIMAL, flags as _, VkMemoryPropertyFlagBits_VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT as _, layers_count, ); self.texture_image = device_image; self.texture_image_memory = device_image_memory; self.texture_image_view = create_image_view( **device, self.texture_image, format, aspect_flags as _, layers_count, ); } fn create_texture_sampler( &mut self, device: &BackendDevice, physical_device: &BackendPhysicalDevice, ) { let properties = physical_device.get_properties(); let sampler_info = VkSamplerCreateInfo { sType: VkStructureType_VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, pNext: ::std::ptr::null_mut(), flags: 0, magFilter: VkFilter_VK_FILTER_LINEAR, minFilter: VkFilter_VK_FILTER_LINEAR, mipmapMode: VkSamplerMipmapMode_VK_SAMPLER_MIPMAP_MODE_LINEAR, addressModeU: VkSamplerAddressMode_VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, addressModeV: VkSamplerAddressMode_VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, addressModeW: VkSamplerAddressMode_VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, mipLodBias: 0.0, anisotropyEnable: VK_TRUE, maxAnisotropy: properties.limits.maxSamplerAnisotropy, compareEnable: VK_FALSE, compareOp: VkCompareOp_VK_COMPARE_OP_NEVER, minLod: 0.0, maxLod: 1.0, borderColor: VkBorderColor_VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, unnormalizedCoordinates: VK_FALSE, }; self.texture_sampler = unsafe { let mut option = ::std::mem::MaybeUninit::uninit(); assert_eq!( VkResult_VK_SUCCESS, vkCreateSampler.unwrap()( **device, &sampler_info, ::std::ptr::null_mut(), option.as_mut_ptr() ) ); option.assume_init() }; } }
e( device, physical_device, format, layers_count, specific_flags, aspect_flags, ); texture.create_texture_sampler(device, physical_device); texture }
function_block-function_prefixed
[]
Rust
src/main.rs
KisaragiEffective/webhook-handler
d31f1df94e5f0c8e445ef6bdcbb8c63b0b7283d8
#![warn(clippy::pedantic, clippy::nursery)] #![deny(type_alias_bounds, legacy_derive_helpers, late_bound_lifetime_arguments)] mod payload; mod call; mod config; mod serde_integration; mod generic_format_io; use std::any::Any; use std::borrow::Borrow; use std::fs::File; use std::io::BufReader; use std::marker::PhantomData; use once_cell::sync::OnceCell; use std::sync::Arc; use actix_web::{App, guard, HttpResponse, HttpServer, Responder, web}; use actix_web::web::JsonConfig; use anyhow::Context; use log::{info, trace}; use serde::{Deserialize, Deserializer, Serialize}; use rustls::{Certificate, PrivateKey, ServerConfig}; use rustls_pemfile::{certs, pkcs8_private_keys}; use generic_format_io::handler; use generic_format_io::handler::JsonHandler; use crate::generic_format_io::outgoing::GenericOutgoingSerializer; use crate::payload::todoist::{TodoistEvent, TodoistPayload}; use crate::payload::discord::{DiscordWebhookPayload, Embed, EmbedCollection, EmbedField, EmbedFields}; use crate::call::api_key::ApiKey; use crate::config::config::Config; type PhantomLifetime<'a> = PhantomData<&'a ()>; fn setup_logger() -> Result<(), fern::InitError> { use fern::colors::*; let mut colors = ColoredLevelConfig::new(); fern::Dispatch::new() .format(move |out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), colors.color(record.level()), message )) }) .level(log::LevelFilter::Trace) .chain(std::io::stdout()) .chain(fern::log_file("output.log")?) .apply()?; Ok(()) } fn todoist_to_webhook(incoming_data: TodoistPayload) -> DiscordWebhookPayload { let username = Some("Todoist".to_string()); let avatar_url = Some("https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/Cib-todoist_%28CoreUI_Icons_v1.0.0%29.svg/240px-Cib-todoist_%28CoreUI_Icons_v1.0.0%29.svg.png".to_string()); let content = "abx".to_string(); let tts = false; match incoming_data.event { TodoistEvent::NoteAdded(note) => { DiscordWebhookPayload { content, username, avatar_url, tts, embeds: EmbedCollection(vec![ Embed { title: Some("Note added".to_string()), description: None, url: Some("test".to_string()), color: Some(0xFF34eb5e), footer: None, image: None, thumbnail: None, video: None, provider: None, author: None, fields: (EmbedFields(vec![EmbedField { name: "description".to_string(), value: note.content }])) } ]), components: Default::default() } } _ => unreachable!("oops") } } static RUNNING_CONFIG: OnceCell<Config> = OnceCell::new(); #[actix_web::main] async fn main() -> std::io::Result<()> { println!("starting"); match setup_logger().context("failed to setup logger") { Ok(_) => {} Err(err) => { eprintln!("failed to initialize logger: {:?}", err); } } let mut config = { trace!("loading cert.pem"); let cert_file = &mut BufReader::new(File::open("cert.pem").unwrap()); let cert_chain = certs(cert_file).unwrap().iter().map(|a| Certificate(a.clone())).collect(); trace!("loading key.pem"); let key_file = &mut BufReader::new(File::open("key.pem").unwrap()); let mut keys = pkcs8_private_keys(key_file).unwrap().iter().map(|x| PrivateKey(x.clone())).collect::<Vec<_>>(); if keys.is_empty() { eprintln!("Could not locate PKCS 8 private keys."); std::process::exit(1); } ServerConfig::builder() .with_safe_defaults() .with_no_client_auth() .with_single_cert(cert_chain, keys.remove(0)).unwrap() }; trace!("Reading config..."); let running_config = File::open("data/config.json").unwrap(); RUNNING_CONFIG.set(serde_json::from_reader(BufReader::new(running_config)).unwrap()); trace!("building HttpServer"); let mut http_server = HttpServer::new(|| { App::new() .wrap(actix_web::middleware::Logger::default()) .app_data( JsonConfig::default().error_handler(handler::json_error_handler) ) .service( web::resource("/api/from/todoist/to/discord") .route( web::post() .guard(guard::Header("content-type", "application/json")) .to(|a, b| handler::handle(Arc::new(JsonHandler::new( RUNNING_CONFIG.get().unwrap().discord_webhook.clone().unwrap(), todoist_to_webhook )), a, b)) ) .route( web::post() .to(|| { HttpResponse::BadRequest().body("Content-Type header must be included") }) ) ) }); trace!("binding ports"); http_server .bind_rustls(format!("127.0.0.1:{}", RUNNING_CONFIG.get().unwrap().https_port), config)? .bind(format!("127.0.0.1:{}", RUNNING_CONFIG.get().unwrap().http_port))? .run() .await?; info!("stopped"); Ok(()) }
#![warn(clippy::pedantic, clippy::nursery)] #![deny(type_alias_bounds, legacy_derive_helpers, late_bound_lifetime_arguments)] mod payload; mod call; mod config; mod serde_integration; mod generic_format_io; use std::any::Any; use std::borrow::Borrow; use std::fs::File; use std::io::BufReader; use std::marker::PhantomData; use once_cell::sync::OnceCell; use std::sync::Arc; use actix_web::{App, guard, HttpResponse, HttpServer, Responder, web}; use actix_web::web::JsonConfig; use anyhow::Context; use log::{info, trace}; use serde::{Deserialize, Deserializer, Serialize}; use rustls::{Certificate, PrivateKey, ServerConfig}; use rustls_pemfile::{certs, pkcs8_private_keys}; use generic_format_io::handler; use generic_format_io::handler::JsonHandler; use crate::generic_format_io::outgoing::GenericOutgoingSerializer; use crate::payload::todoist::{TodoistEvent, TodoistPayload}; use crate::payload::discord::{DiscordWebhookPayload, Embed, EmbedCollection, EmbedField, EmbedFields}; use crate::call::api_key::ApiKey; use crate::config::config::Config; type PhantomLifetime<'a> = PhantomData<&'a ()>; fn setup_logger() -> Result<(), fern::InitError> { use fern::colors::*; let mut colors = ColoredLevelConfig::new(); fern::Dispatch::new() .format(move |out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), colors.color(record.level()), message )) }) .level(log::LevelFilter::Trace) .chain(std::io::stdout()) .chain(fern::log_file("output.log")?) .apply()?; Ok(()) } fn todoist_to_webhook(incoming_data: TodoistPayload) -> DiscordWebhookPayload { let username = Some("Todoist".to_string()); let avatar_url = Some("https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/Cib-todoist_%28CoreUI_Icons_v1.0.0%29.svg/240px-Cib-todoist_%28CoreUI_Icons_v1.0.0%29.svg.png".to_string()); let content = "abx".to_string(); let tts = false; match incoming_data.event { TodoistEvent::NoteAdded(note) => { DiscordWebhookPayload { content, username, avatar_url, tts, embeds: EmbedCollection(vec![ Embed { title: Some("Note added".to_string()), description: None, url: Some("test".to_string()), color: Some(0xFF34eb5e), footer: None, image: None, thumbnail: None, video: None, provider: None, author: None, fields: (EmbedFields(vec![EmbedField { name: "description".to_string(), value: note.content }])) } ]), components: Default::default() } } _ => unreachable!("oops") } } static RUNNING_CONFIG: OnceCell<Config> = OnceCell::new(); #[actix_web::main] async fn main() -> std::io::Result<()> { println!("starting"); match setup_logger().context("failed to setup logger") { Ok(_) => {} Err(err) => { eprintln!("failed to initialize logger: {:?}", err); } } let mut config = { trace!("loading cert.pem"); let cert_file = &mut BufReader::new(File::open("cert.pem").unwrap()); let cert_chain = certs(cert_file).unwrap().iter().map(|a| Certificate(a.clone())).collect(); trace!("loading key.pem"); let key_file = &mut BufReader::new(File::open("key.pem").unwrap()); let mut keys = pkcs8_private_keys(key_file).unwrap().iter().map(|x| PrivateKey(x.clone())).collect::<Vec<_>>(); if keys.is_empty() { eprintln!("Could not locate PKCS 8 private keys."); std::process::exit(1
web::post() .to(|| { HttpResponse::BadRequest().body("Content-Type header must be included") }) ) ) }); trace!("binding ports"); http_server .bind_rustls(format!("127.0.0.1:{}", RUNNING_CONFIG.get().unwrap().https_port), config)? .bind(format!("127.0.0.1:{}", RUNNING_CONFIG.get().unwrap().http_port))? .run() .await?; info!("stopped"); Ok(()) }
); } ServerConfig::builder() .with_safe_defaults() .with_no_client_auth() .with_single_cert(cert_chain, keys.remove(0)).unwrap() }; trace!("Reading config..."); let running_config = File::open("data/config.json").unwrap(); RUNNING_CONFIG.set(serde_json::from_reader(BufReader::new(running_config)).unwrap()); trace!("building HttpServer"); let mut http_server = HttpServer::new(|| { App::new() .wrap(actix_web::middleware::Logger::default()) .app_data( JsonConfig::default().error_handler(handler::json_error_handler) ) .service( web::resource("/api/from/todoist/to/discord") .route( web::post() .guard(guard::Header("content-type", "application/json")) .to(|a, b| handler::handle(Arc::new(JsonHandler::new( RUNNING_CONFIG.get().unwrap().discord_webhook.clone().unwrap(), todoist_to_webhook )), a, b)) ) .route(
function_block-random_span
[ { "content": "pub fn deserialize_iso8601<'de, D: Deserializer<'de>>(deserializer: D) -> Result<DateTime, D::Error> {\n\n use std::str::FromStr;\n\n match String::deserialize(deserializer) {\n\n Ok(a) => {\n\n match DateTime::from_str(a.as_str()) {\n\n Ok(a) => { Ok(a) }\n\...
Rust
src/mix/sender.rs
hydra-acn/hydra
b5cb31310d1be95202f65ea732574e84555c3365
use futures_util::stream; use log::*; use rand::seq::SliceRandom; use std::collections::HashMap; use std::io::Write; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use tokio::task; use crate::crypto::cprng::thread_cprng; use crate::epoch::current_time; use crate::error::Error; use crate::net::cell::Cell; use crate::net::channel_pool::{MixChannel, RendezvousChannel, TcpChannel}; use crate::net::PacketWithNextHop; use crate::tonic_mix::{SetupPacket, Subscription}; use super::cell_processor::cell_rss_t; use super::directory_client; use super::setup_processor::setup_t; pub type Batch<T> = (Vec<Vec<PacketWithNextHop<T>>>, Option<Duration>); pub type SetupBatch = Batch<SetupPacket>; pub type SubscribeBatch = Batch<Subscription>; pub type CellBatch = Batch<Cell>; macro_rules! send_next_batch { ($state:expr, $queue:ident, $batch_type:ident, $channel_getter:ident, $send_fun:ident) => { let queue = $state.$queue.clone(); let maybe_batch = task::spawn_blocking(move || queue.recv()) .await .expect("Spawn failed"); let batch: $batch_type = match maybe_batch { Ok(b) => b, Err(e) => { error!("Seems like the worker thread is gone: {}", e); break; } }; let deadline = batch.1; let (batch_map, destinations) = sort_by_destination(batch); let channel_map = $state.dir_client.$channel_getter(&destinations).await; for (dst, pkts) in batch_map.into_iter() { match channel_map.get(&dst) { Some(c) => { tokio::spawn($send_fun( $state.dir_client.clone(), c.clone(), pkts, deadline, )); } None => { warn!( "Expected to have a connection by now, dropping packets destined to {}", dst ); () } } } }; } macro_rules! define_send_task { ($name:ident, $queue:ident, $batch_type:ident, $channel_getter:ident, $send_fun:ident) => { pub async fn $name(state: Arc<State>) -> Result<(), Error> { loop { send_next_batch!(state, $queue, $batch_type, $channel_getter, $send_fun); } Ok(()) } }; } pub struct State { dir_client: Arc<directory_client::Client>, setup_tx_queue: setup_t::TxQueue, subscribe_tx_queue: setup_t::AltTxQueue, relay_tx_queue: cell_rss_t::TxQueue, } impl State { pub fn new( dir_client: Arc<directory_client::Client>, setup_tx_queue: setup_t::TxQueue, subscribe_tx_queue: setup_t::AltTxQueue, relay_tx_queue: cell_rss_t::TxQueue, ) -> Self { State { dir_client, setup_tx_queue, subscribe_tx_queue, relay_tx_queue, } } } fn sort_by_destination<T>(batch: Batch<T>) -> (HashMap<SocketAddr, Vec<T>>, Vec<SocketAddr>) { let mut batch_map: HashMap<SocketAddr, Vec<T>> = HashMap::new(); for vec in batch.0.into_iter() { for pkt in vec.into_iter() { match batch_map.get_mut(pkt.next_hop()) { Some(vec) => vec.push(pkt.into_inner()), None => { batch_map.insert(*pkt.next_hop(), vec![pkt.into_inner()]); } } } } let destinations: Vec<SocketAddr> = batch_map.keys().cloned().collect(); (batch_map, destinations) } async fn send_setup_packets( dir_client: Arc<directory_client::Client>, mut c: MixChannel, pkts: Vec<SetupPacket>, deadline: Option<Duration>, ) { let shuffle_it = ShuffleIterator::new(pkts, deadline); let mut req = tonic::Request::new(stream::iter(shuffle_it)); req.metadata_mut().insert( "reply-to", dir_client .config() .setup_reply_to() .parse() .expect("Why should this fail?"), ); c.stream_setup_circuit(req) .await .map(|_| ()) .unwrap_or_else(|e| warn!("Creating circuits failed: {}", e)); } async fn send_subscriptions( _dir_client: Arc<directory_client::Client>, mut c: RendezvousChannel, pkts: Vec<Subscription>, _deadline: Option<Duration>, ) { if pkts.len() > 1 { warn!("Expected one subscription to each rendezvous node only"); } for sub in pkts.into_iter() { info!("Sending subscriptions for {} circuits", sub.circuits.len()); let req = tonic::Request::new(sub); c.subscribe(req) .await .map(|_| ()) .unwrap_or_else(|e| warn!("Subscription failed: {}", e)); } } async fn relay_cells( _dir_client: Arc<directory_client::Client>, c: TcpChannel, cells: Vec<Cell>, deadline: Option<Duration>, ) { tokio::task::spawn_blocking(move || { let shuffle_it = ShuffleIterator::new(cells, deadline); let mut stream = c.write().expect("Lock poisoned"); for cell in shuffle_it { stream.write_all(cell.buf()).unwrap_or_else(|e| { warn!("Writing to TCP stream failed: {}", e); }); } }) .await .expect("Spawn failed"); } define_send_task!( setup_task, setup_tx_queue, SetupBatch, get_mix_channels, send_setup_packets ); define_send_task!( subscribe_task, subscribe_tx_queue, SubscribeBatch, get_rendezvous_channels, send_subscriptions ); define_send_task!( relay_task, relay_tx_queue, CellBatch, get_relay_channels, relay_cells ); pub async fn run(state: Arc<State>) { let setup_handle = tokio::spawn(setup_task(state.clone())); let subscribe_handle = tokio::spawn(subscribe_task(state.clone())); let relay_handle = tokio::spawn(relay_task(state.clone())); match tokio::try_join!(setup_handle, subscribe_handle, relay_handle,) { Ok(_) => (), Err(e) => error!("Something panicked: {}", e), } } pub struct ShuffleIterator<T> { idx_vec: Vec<usize>, pkt_vec: Vec<T>, pos: usize, deadline: Option<Duration>, } impl<T> ShuffleIterator<T> { pub fn new(pkt_vec: Vec<T>, deadline: Option<Duration>) -> Self { let mut idx_vec: Vec<usize> = (0..pkt_vec.len()).collect(); idx_vec.shuffle(&mut thread_cprng()); ShuffleIterator { idx_vec, pkt_vec, pos: 0, deadline, } } } impl<T: Default> Iterator for ShuffleIterator<T> { type Item = T; fn next(&mut self) -> Option<T> { if let Some(deadline) = self.deadline { if deadline.checked_sub(current_time()).is_none() { warn!("Sending did not finish in time"); return None; } } if self.pos < self.idx_vec.len() { let pkt = std::mem::take(&mut self.pkt_vec[self.idx_vec[self.pos]]); self.pos += 1; Some(pkt) } else { None } } }
use futures_util::stream; use log::*; use rand::seq::SliceRandom; use std::collections::HashMap; use std::io::Write; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use tokio::task; use crate::crypto::cprng::thread_cprng; use crate::epoch::current_time; use crate::error::Error; use crate::net::cell::Cell; use crate::net::channel_pool::{MixChannel, RendezvousChannel, TcpChannel}; use crate::net::PacketWithNextHop; use crate::tonic_mix::{SetupPacket, Subscription}; use super::cell_processor::cell_rss_t; use super::directory_client; use super::setup_processor::setup_t; pub type Batch<T> = (Vec<Vec<PacketWithNextHop<T>>>, Option<Duration>); pub type SetupBatch = Batch<SetupPacket>; pub type SubscribeBatch = Batch<Subscription>; pub type CellBatch = Batch<Cell>; macro_rules! send_next_batch { ($state:expr, $queue:ident, $batch_type:ident, $channel_getter:ident, $send_fun:ident) => { let queue = $state.$queue.clone(); let maybe_batch = task::spawn_blocking(move || queue.recv()) .await .expect("Spawn failed"); let batch: $batch_type = match maybe_batch { Ok(b) => b, Err(e) => { error!("Seems like the worker thread is gone: {}", e); break; } }; let deadline = batch.1; let (batch_map, destinations) = sort_by_destination(batch); let channel_map = $state.dir_client.$channel_getter(&destinations).await; for (dst, pkts) in batch_map.into_iter() { match channel_map.get(&dst) { Some(c) => { tokio::spawn($send_fun( $state.dir_client.clone(), c.clone(), pkts, deadline, )); } None => { warn!( "Expected to have a connection by now, dropping packets destined to {}", dst ); () } } } }; } macro_rules! define_send_task { ($name:ident, $queue:ident, $batch_type:ident, $channel_getter:ident, $send_fun:ident) => { pub async fn $name(state: Arc<State>) -> Result<(), Error> { loop { send_next_batch!(state, $queue, $batch_type, $channel_getter, $send_fun); } Ok(()) } }; } pub struct State { dir_client: Arc<directory_client::Client>, setup_tx_queue: setup_t::TxQueue, subscribe_tx_queue: setup_t::AltTxQueue, relay_tx_queue: cell_rss_t::TxQueue, } impl State { pub fn new( dir_client: Arc<directory_client::Client>, setup_tx_queue: setup_t::TxQueue, subscribe_tx_queue: setup_t::AltTxQueue, relay_tx_queue: cell_rss_t::TxQueue, ) -> Self { State { dir_client, setup_tx_queue, subscribe_tx_queue, relay_tx_queue, } } } fn sort_by_destination<T>(batch: Batch<T>) -> (HashMap<SocketAddr, Vec<T>>, Vec<SocketAddr>) { let mut batch_map: HashMap<SocketAddr, Vec<T>> = HashMap::new(); for vec in batch.0.into_iter() { for pkt in vec.into_iter() { match batch_map.get_mut(pkt.next_hop()) { Some(vec) => vec.push(pkt.into_inner()), None => { batch_map.insert(*pkt.next_hop(), vec![pkt.into_inner()]); } } } } let destinations: Vec<SocketAddr> = batch_map.keys().cloned().collect(); (batch_map, destinations) } async fn send_setup_packets( dir_client: Arc<directory_client::Client>, mut c: MixChannel, pkts: Vec<SetupPacket>, deadline: Option<Duration>, ) { let shuffle_it = ShuffleIterator::new(pkts, deadline); let mut req = tonic::Request::new(stream::iter(shuffle_it)); req.metadata_mut().insert( "reply-to", dir_client .config() .setup_reply_to() .parse() .expect("Why should this fail?"), ); c.stream_setup_circuit(req) .await .map(|_| ()) .unwrap_or_else(|e| warn!("Creating circuits failed: {}", e)); } async fn send_subscriptions( _dir_client: Arc<directory_client::Client>, mut c: RendezvousChannel, pkts: Vec<Subscription>, _deadline: Option<Duration>, ) { if pkts.len() > 1 { warn!("Expected one
async fn relay_cells( _dir_client: Arc<directory_client::Client>, c: TcpChannel, cells: Vec<Cell>, deadline: Option<Duration>, ) { tokio::task::spawn_blocking(move || { let shuffle_it = ShuffleIterator::new(cells, deadline); let mut stream = c.write().expect("Lock poisoned"); for cell in shuffle_it { stream.write_all(cell.buf()).unwrap_or_else(|e| { warn!("Writing to TCP stream failed: {}", e); }); } }) .await .expect("Spawn failed"); } define_send_task!( setup_task, setup_tx_queue, SetupBatch, get_mix_channels, send_setup_packets ); define_send_task!( subscribe_task, subscribe_tx_queue, SubscribeBatch, get_rendezvous_channels, send_subscriptions ); define_send_task!( relay_task, relay_tx_queue, CellBatch, get_relay_channels, relay_cells ); pub async fn run(state: Arc<State>) { let setup_handle = tokio::spawn(setup_task(state.clone())); let subscribe_handle = tokio::spawn(subscribe_task(state.clone())); let relay_handle = tokio::spawn(relay_task(state.clone())); match tokio::try_join!(setup_handle, subscribe_handle, relay_handle,) { Ok(_) => (), Err(e) => error!("Something panicked: {}", e), } } pub struct ShuffleIterator<T> { idx_vec: Vec<usize>, pkt_vec: Vec<T>, pos: usize, deadline: Option<Duration>, } impl<T> ShuffleIterator<T> { pub fn new(pkt_vec: Vec<T>, deadline: Option<Duration>) -> Self { let mut idx_vec: Vec<usize> = (0..pkt_vec.len()).collect(); idx_vec.shuffle(&mut thread_cprng()); ShuffleIterator { idx_vec, pkt_vec, pos: 0, deadline, } } } impl<T: Default> Iterator for ShuffleIterator<T> { type Item = T; fn next(&mut self) -> Option<T> { if let Some(deadline) = self.deadline { if deadline.checked_sub(current_time()).is_none() { warn!("Sending did not finish in time"); return None; } } if self.pos < self.idx_vec.len() { let pkt = std::mem::take(&mut self.pkt_vec[self.idx_vec[self.pos]]); self.pos += 1; Some(pkt) } else { None } } }
subscription to each rendezvous node only"); } for sub in pkts.into_iter() { info!("Sending subscriptions for {} circuits", sub.circuits.len()); let req = tonic::Request::new(sub); c.subscribe(req) .await .map(|_| ()) .unwrap_or_else(|e| warn!("Subscription failed: {}", e)); } }
function_block-function_prefixed
[ { "content": "pub fn key_exchange(pk_mix: &Key) -> Result<(Key, Key), Error> {\n\n let (pk, sk) = x448::generate_keypair();\n\n let s = x448::generate_shared_secret(&pk_mix, &sk)?;\n\n Ok((pk, s))\n\n}\n\n\n\npub async fn update_loop(state: Arc<State>) {\n\n loop {\n\n // wait till next updat...
Rust
Project/src/main.rs
qarmin/gtk-rs-fuzzer
def0baaabe356998cef130f3a3aec6654bd5b78d
#![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_must_use)] mod create_objects; mod enum_things; mod helpers; mod implementations; mod ziemniak; use crate::create_objects::*; use crate::ziemniak::{run_tests, SettingsTaker}; use gtk4::prelude::*; use gtk4::*; use std::fs; use std::fs::File; fn main() { let application = gtk4::Application::builder().build(); application.connect_activate(move |application| { let window = gtk4::ApplicationWindow::new(application); window.set_title(Some("Fuzzer gtk-rs")); window.show(); let sf = read_from_file(); if TEST == 0 { crashes(); } else { run_tests(sf); } }); application.run(); } const TEST: u64 = 1; fn crashes() { println!("TESTSTTSTSTSTSTSTST"); } fn read_from_file() -> SettingsTaker { let string: String = match fs::read_to_string("settings.txt") { Ok(t) => t, Err(_) => { println!("Missing settings.txt file"); return SettingsTaker { ignored_functions: vec![], allowed_functions: vec![], ignored_classes: vec![], allowed_classes: vec![], repeating_number: 3, all_repeating_number: 1, number_of_max_executed_function: -1, }; } }; let mut st: SettingsTaker = SettingsTaker { ignored_functions: vec![], allowed_functions: vec![], ignored_classes: vec![], allowed_classes: vec![], repeating_number: 3, all_repeating_number: 1, number_of_max_executed_function: -1, }; enum MODES { None, IgnoredFunctions, AllowedFunctions, IgnoredClasses, AllowedClasses, Repeating, AllRepeating, MaxExecutedFunction, } let mut current_mode: MODES = MODES::None; for line in string.split('\n').map(|e| e.to_string()).collect::<Vec<String>>() { let new_line = line.trim().to_string(); if new_line.starts_with("//") { continue; } if new_line == "ignored_functions:" { current_mode = MODES::IgnoredFunctions; } else if new_line == "allowed_functions:" { current_mode = MODES::AllowedFunctions; } else if new_line == "ignored_classes:" { current_mode = MODES::IgnoredClasses; } else if new_line == "allowed_classes:" { current_mode = MODES::AllowedClasses; } else if new_line == "repeating_number:" { current_mode = MODES::Repeating; } else if new_line == "all_repeating_number:" { current_mode = MODES::AllRepeating; } else if new_line == "number_of_max_executed_function:" { current_mode = MODES::MaxExecutedFunction; } else { if !new_line.is_empty() { match current_mode { MODES::IgnoredFunctions => st.ignored_functions.push(new_line), MODES::AllowedFunctions => st.allowed_functions.push(new_line), MODES::IgnoredClasses => st.ignored_classes.push(new_line), MODES::AllowedClasses => st.allowed_classes.push(new_line), MODES::Repeating => { if let Ok(number) = new_line.parse() { st.repeating_number = number; } } MODES::AllRepeating => { if let Ok(number) = new_line.parse() { st.all_repeating_number = number; } } MODES::MaxExecutedFunction => { if let Ok(number) = new_line.parse() { st.number_of_max_executed_function = number; } } MODES::None => println!("SETTING: Missing mode for {}", new_line), } } } } { println!("Start settings loading"); if !st.ignored_classes.is_empty() { println!("Ignored classes:"); for i in &st.ignored_classes { println!("{}", i); } } if !st.allowed_classes.is_empty() { println!("Allowed classes:"); for i in &st.allowed_classes { println!("{}", i); } } if !st.allowed_functions.is_empty() { println!("Allowed functions:"); for i in &st.allowed_functions { println!("{}", i); } } if !st.ignored_functions.is_empty() { println!("Ignored functions:"); for i in &st.ignored_functions { println!("{}", i); } } println!("Repeating - {}", st.repeating_number); println!("All Repeating - {}", st.all_repeating_number); println!("Max Executed Functions - {}", st.number_of_max_executed_function); println!("End settings loading"); } st }
#![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_must_use)] mod create_objects; mod enum_things; mod helpers; mod implementations; mod ziemniak; use crate::create_objects::*; use crate::ziemniak::{run_tests, SettingsTaker}; use gtk4::prelude::*; use gtk4::*; use std::fs; use std::fs::File; fn main() { let application = gtk4::Application::builder().build(); application.connect_activate(move |application| { let window = gtk4::ApplicationWindow::new(application); window.set_title(Some("Fuzzer gtk-rs")); window.show(); let sf = read_from_file(); if TEST == 0 { crashes(); } else { run_tests(sf); } }); application.run(); } const TEST: u64 = 1; fn crashes() { println!("TESTSTTSTSTSTSTSTST"); } fn read_from_file() -> SettingsTaker { let string: String = match fs::read_to_string("settings.txt") { Ok(t) => t, Err(_) => { println!("Missing settings.txt file"); return SettingsTaker { ignored_functions: vec![], allowed_functions: vec![], ignored_classes: vec![], allowed_classes: vec![], repeating_number: 3, all_repeating_number: 1, number_of_max_executed_function: -1, }; } }; let mut st: SettingsTaker = SettingsTaker { ignored_functions: vec![], allowed_functions: vec![], ignored_classes: vec![], allowed_classes: vec![], repeating_number: 3, all_repeating_number: 1, number_of_max_executed_function: -1, }; enum MODES { None, IgnoredFunctions, AllowedFunctions, IgnoredClasses, AllowedClasses, Repeating, AllRepeating, MaxExecutedFunction, } let mut current_mode: MODES = MODES::None; for line in string.split('\n').map(|e| e.to_string()).collect::<Vec<String>>() { let new_line = line.trim().to_string(); if new_line.starts_with("//") { continue; } if new_line == "ignored_functions:" { current_mode = MODES::IgnoredFunctions; } else if new_line == "allowed_functions:" { current_mode = MODES::AllowedFunctions; } else if new_line == "ignored_classes:" { current_mode = MODES::IgnoredClasses; } else if new_line == "allowed_classes:" { current_mode = MODES::AllowedClasses; } else if new_line == "repeating_number:" { current_mode = MODES::Repeating; } else if new_line == "all_repeating_number:" { current_mode = MODES::AllRepeating; } else if new_line == "number_of_max_executed_function:" { current_mode = MODES::MaxExecutedFunction; } else { if !new_line.is_empty() { match current_mode { MODES::IgnoredFunctions => st.ignored_functions.push(new_line), MODES::AllowedFunctions => st.allowed_functions.push(new_line), MODES::IgnoredClasses => st.ignored_classes.push(new_line), MODES::AllowedClasses => st.allowed_classes.push(new_line), MODES::Repeating => { if let Ok(number) = new_line.parse() { st.repeating_number = number; } } MODES::AllRepeating => { if let Ok(number) = new_line.parse() { st.all_repeating_number = number; } } MODES::MaxExecutedFunction => { if let Ok(number) = new_line.parse() { st.number_of_max_executed_function = number; } } MODES::None => println!("SETTING: Missing mode for {}", new_line), } } } } { println!("Start settings loading"); if !st.ignored_classes.is_empty() { println!("Ignored classes:"); for i in &st.ignored_classes { println!("{}", i); } }
if !st.allowed_functions.is_empty() { println!("Allowed functions:"); for i in &st.allowed_functions { println!("{}", i); } } if !st.ignored_functions.is_empty() { println!("Ignored functions:"); for i in &st.ignored_functions { println!("{}", i); } } println!("Repeating - {}", st.repeating_number); println!("All Repeating - {}", st.all_repeating_number); println!("Max Executed Functions - {}", st.number_of_max_executed_function); println!("End settings loading"); } st }
if !st.allowed_classes.is_empty() { println!("Allowed classes:"); for i in &st.allowed_classes { println!("{}", i); } }
if_condition
[ { "content": "pub fn take_vec_string() -> Vec<String> {\n\n let mut to_return = Vec::new();\n\n\n\n for _i in 0..thread_rng().gen_range(0..10) {\n\n to_return.push(take_string());\n\n }\n\n\n\n debug_printing_vec(&to_return);\n\n to_return\n\n}\n\n\n", "file_path": "Project/src/helpers...
Rust
src/gl33/buffer.rs
phaazon/luminance-gl-rs
73e156ce276b3882335201bde5ca31bc6afa4ba5
use gl; use gl::types::*; use gl33::token::GL33; use luminance::buffer; use std::cmp::Ordering::*; use std::mem; use std::os::raw::c_void; use std::ptr; use std::slice; pub type Buffer<T> = buffer::Buffer<GL33, T>; pub type BufferSlice<'a, T> = buffer::BufferSlice<'a, GL33, T>; pub type BufferSliceMut<'a, T> = buffer::BufferSliceMut<'a, GL33, T>; #[derive(Debug, Clone, Eq, PartialEq)] pub struct GLBuffer { pub handle: GLuint, pub bytes: usize } unsafe impl buffer::HasBuffer for GL33 { type ABuffer = GLBuffer; fn new(size: usize) -> Self::ABuffer { let mut buffer: GLuint = 0; unsafe { gl::GenBuffers(1, &mut buffer); gl::BindBuffer(gl::ARRAY_BUFFER, buffer); gl::BufferData(gl::ARRAY_BUFFER, size as isize, ptr::null(), gl::STREAM_DRAW); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } GLBuffer { handle: buffer, bytes: size } } fn free(buffer: &mut Self::ABuffer) { unsafe { gl::DeleteBuffers(1, &buffer.handle) } } fn write_whole<T>(buffer: &Self::ABuffer, values: &[T]) -> Result<(), buffer::BufferError> { let bytes = values.len() * mem::size_of::<T>(); let (warning, bytes) = match bytes.cmp(&buffer.bytes) { Less => (Some(buffer::BufferError::TooFewValues), bytes), Greater => (Some(buffer::BufferError::TooManyValues), buffer.bytes), _ => (None, bytes) }; unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::WRITE_ONLY); ptr::copy_nonoverlapping(values.as_ptr() as *const c_void, ptr, bytes); let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } match warning { Some(w) => Err(w), None => Ok(()) } } fn write<T>(buffer: &Self::ABuffer, off: usize, x: T) -> Result<(), buffer::BufferError> where T: Copy { if off >= buffer.bytes { return Err(buffer::BufferError::Overflow); } unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::WRITE_ONLY); *(ptr.offset(off as isize) as *mut T) = x; let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } Ok(()) } fn read_whole<T>(buffer: &Self::ABuffer, nb: usize) -> Vec<T> where T: Copy { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_ONLY) as *const T; let values = Vec::from(slice::from_raw_parts(ptr, nb)); let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER, 0); values } } fn read<T>(buffer: &Self::ABuffer, off: usize) -> Option<T> where T: Copy { if off >= buffer.bytes { return None; } unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_ONLY); let x = *(ptr.offset(off as isize) as *const T); let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER, 0); Some(x) } } fn map<T>(buffer: &mut Self::ABuffer) -> *const T { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_ONLY) as *const T } } fn map_mut<T>(buffer: &mut Self::ABuffer) -> *mut T { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_WRITE) as *mut T } } fn unmap(buffer: &mut Self::ABuffer) { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); gl::UnmapBuffer(gl::ARRAY_BUFFER); } } }
use gl; use gl::types::*; use gl33::token::GL33; use luminance::buffer; use std::cmp::Ordering::*; use std::mem; use std::os::raw::c_void; use std::ptr; use std::slice; pub type Buffer<T> = buffer::Buffer<GL33, T>; pub type BufferSlice<'a, T> = buffer::BufferSlice<'a, GL33, T>; pub type BufferSliceMut<'a, T> = buffer::BufferSliceMut<'a, GL33, T>; #[derive(Debug, Clone, Eq, PartialEq)] pub struct GLBuffer { pub handle: GLuint, pub bytes: usize } unsafe impl buffer::HasBuffer for GL33 { type ABuffer = GLBuffer; fn new(size: usize) -> Self::ABuffer { let mut buffer: GLuint = 0; unsafe { gl::GenBuffers(1, &mut buffer); gl::BindBuffer(gl::ARRAY_BUFFER, buffer); gl::BufferData(gl::ARRAY_BUFFER, size as isize, ptr::null(), gl::STREAM_DRAW); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } GLBuffer { handle: buffer, bytes: size } } fn free(buffer: &mut Self::ABuffer) { unsafe { gl::DeleteBuffers(1, &buffer.handle) } } fn write_whole<T>(buffer: &Self::ABuffer, values: &[T]) -> Result<(), buffer::BufferError> { let bytes = values.len() * mem::size_of::<T>(); let (warning, bytes) = match bytes.cmp(&buffer.bytes) { Less => (Some(buffer::BufferError::TooFewValues), bytes), Greater => (Some(buffer::BufferError::TooManyValues), buffer.bytes), _ => (None, bytes) }; unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::WRITE_ONLY); ptr::copy_nonoverlapping(values.as_ptr() as *const c_void, ptr, bytes); let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } match warning { Some(w) => Err(w), None => Ok(()) } } fn write<T>(buffer: &Self::ABuffer, off: usize, x: T) -> Result<(), buffer::BufferError> where T: Copy { if off >= buffer.bytes {
fn read_whole<T>(buffer: &Self::ABuffer, nb: usize) -> Vec<T> where T: Copy { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_ONLY) as *const T; let values = Vec::from(slice::from_raw_parts(ptr, nb)); let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER, 0); values } } fn read<T>(buffer: &Self::ABuffer, off: usize) -> Option<T> where T: Copy { if off >= buffer.bytes { return None; } unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_ONLY); let x = *(ptr.offset(off as isize) as *const T); let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER, 0); Some(x) } } fn map<T>(buffer: &mut Self::ABuffer) -> *const T { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_ONLY) as *const T } } fn map_mut<T>(buffer: &mut Self::ABuffer) -> *mut T { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_WRITE) as *mut T } } fn unmap(buffer: &mut Self::ABuffer) { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); gl::UnmapBuffer(gl::ARRAY_BUFFER); } } }
return Err(buffer::BufferError::Overflow); } unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::WRITE_ONLY); *(ptr.offset(off as isize) as *mut T) = x; let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn create_texture<L, D>(target: GLenum, size: D::Size, mipmaps: usize, pf: PixelFormat, sampler: &Sampler) -> Result<()>\n\n where L: Layerable,\n\n D: Dimensionable,\n\n D::Size: Copy {\n\n set_texture_levels(target, mipmaps);\n\n\n\n apply_sampler_to_texture(target, sa...
Rust
src/test/instruction_tests/instr_vpsrldq.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpsrldq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(44)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 217, 115, 222, 44], OperandSize::Dword, ) } #[test] fn vpsrldq_2() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(62)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 209, 115, 217, 62], OperandSize::Qword, ) } #[test] fn vpsrldq_3() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM3)), operand3: Some(Literal8(60)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 229, 115, 219, 60], OperandSize::Dword, ) } #[test] fn vpsrldq_4() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM4)), operand2: Some(Direct(YMM7)), operand3: Some(Literal8(89)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 221, 115, 223, 89], OperandSize::Qword, ) } #[test] fn vpsrldq_5() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM2)), operand3: Some(Literal8(105)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 249, 115, 218, 105], OperandSize::Dword, ) } #[test] fn vpsrldq_6() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexedDisplaced( ESI, EDX, Two, 835075344, Some(OperandSize::Xmmword), None, )), operand3: Some(Literal8(110)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 69, 8, 115, 156, 86, 16, 61, 198, 49, 110], OperandSize::Dword, ) } #[test] fn vpsrldq_7() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM9)), operand2: Some(Direct(XMM17)), operand3: Some(Literal8(40)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 177, 53, 8, 115, 217, 40], OperandSize::Qword, ) } #[test] fn vpsrldq_8() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM16)), operand2: Some(IndirectScaledDisplaced( RDX, Four, 681780529, Some(OperandSize::Xmmword), None, )), operand3: Some(Literal8(26)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 125, 0, 115, 28, 149, 49, 37, 163, 40, 26], OperandSize::Qword, ) } #[test] fn vpsrldq_9() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM7)), operand3: Some(Literal8(53)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 229, 115, 223, 53], OperandSize::Dword, ) } #[test] fn vpsrldq_10() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM0)), operand2: Some(IndirectScaledIndexedDisplaced( EBX, ECX, Four, 1085957988, Some(OperandSize::Ymmword), None, )), operand3: Some(Literal8(100)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 125, 40, 115, 156, 139, 100, 103, 186, 64, 100], OperandSize::Dword, ) } #[test] fn vpsrldq_11() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM29)), operand2: Some(Direct(YMM18)), operand3: Some(Literal8(52)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 177, 21, 32, 115, 218, 52], OperandSize::Qword, ) } #[test] fn vpsrldq_12() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM26)), operand2: Some(Indirect(RSI, Some(OperandSize::Ymmword), None)), operand3: Some(Literal8(35)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 45, 32, 115, 30, 35], OperandSize::Qword, ) } #[test] fn vpsrldq_13() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(ZMM0)), operand2: Some(Direct(ZMM7)), operand3: Some(Literal8(123)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 125, 72, 115, 223, 123], OperandSize::Dword, ) } #[test] fn vpsrldq_14() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(ZMM1)), operand2: Some(IndirectScaledDisplaced( ECX, Four, 496895416, Some(OperandSize::Zmmword), None, )), operand3: Some(Literal8(116)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 117, 72, 115, 28, 141, 184, 5, 158, 29, 116], OperandSize::Dword, ) } #[test] fn vpsrldq_15() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(ZMM1)), operand2: Some(Direct(ZMM25)), operand3: Some(Literal8(44)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 145, 117, 72, 115, 217, 44], OperandSize::Qword, ) } #[test] fn vpsrldq_16() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(ZMM3)), operand2: Some(IndirectScaledDisplaced( RDI, Two, 260769911, Some(OperandSize::Zmmword), None, )), operand3: Some(Literal8(124)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 101, 72, 115, 28, 125, 119, 8, 139, 15, 124], OperandSize::Qword, ) }
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Re
erandSize::Xmmword), None, )), operand3: Some(Literal8(26)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 125, 0, 115, 28, 149, 49, 37, 163, 40, 26], OperandSize::Qword, ) } #[test] fn vpsrldq_9() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM7)), operand3: Some(Literal8(53)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 229, 115, 223, 53], OperandSize::Dword, ) } #[test] fn vpsrldq_10() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM0)), operand2: Some(IndirectScaledIndexedDisplaced( EBX, ECX, Four, 1085957988, Some(OperandSize::Ymmword), None, )), operand3: Some(Literal8(100)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 125, 40, 115, 156, 139, 100, 103, 186, 64, 100], OperandSize::Dword, ) } #[test] fn vpsrldq_11() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM29)), operand2: Some(Direct(YMM18)), operand3: Some(Literal8(52)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 177, 21, 32, 115, 218, 52], OperandSize::Qword, ) } #[test] fn vpsrldq_12() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM26)), operand2: Some(Indirect(RSI, Some(OperandSize::Ymmword), None)), operand3: Some(Literal8(35)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 45, 32, 115, 30, 35], OperandSize::Qword, ) } #[test] fn vpsrldq_13() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(ZMM0)), operand2: Some(Direct(ZMM7)), operand3: Some(Literal8(123)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 125, 72, 115, 223, 123], OperandSize::Dword, ) } #[test] fn vpsrldq_14() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(ZMM1)), operand2: Some(IndirectScaledDisplaced( ECX, Four, 496895416, Some(OperandSize::Zmmword), None, )), operand3: Some(Literal8(116)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 117, 72, 115, 28, 141, 184, 5, 158, 29, 116], OperandSize::Dword, ) } #[test] fn vpsrldq_15() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(ZMM1)), operand2: Some(Direct(ZMM25)), operand3: Some(Literal8(44)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 145, 117, 72, 115, 217, 44], OperandSize::Qword, ) } #[test] fn vpsrldq_16() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(ZMM3)), operand2: Some(IndirectScaledDisplaced( RDI, Two, 260769911, Some(OperandSize::Zmmword), None, )), operand3: Some(Literal8(124)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 101, 72, 115, 28, 125, 119, 8, 139, 15, 124], OperandSize::Qword, ) }
g, RoundingMode}; #[test] fn vpsrldq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(44)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 217, 115, 222, 44], OperandSize::Dword, ) } #[test] fn vpsrldq_2() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(62)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 209, 115, 217, 62], OperandSize::Qword, ) } #[test] fn vpsrldq_3() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM3)), operand3: Some(Literal8(60)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 229, 115, 219, 60], OperandSize::Dword, ) } #[test] fn vpsrldq_4() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(YMM4)), operand2: Some(Direct(YMM7)), operand3: Some(Literal8(89)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 221, 115, 223, 89], OperandSize::Qword, ) } #[test] fn vpsrldq_5() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM2)), operand3: Some(Literal8(105)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 249, 115, 218, 105], OperandSize::Dword, ) } #[test] fn vpsrldq_6() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexedDisplaced( ESI, EDX, Two, 835075344, Some(OperandSize::Xmmword), None, )), operand3: Some(Literal8(110)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 241, 69, 8, 115, 156, 86, 16, 61, 198, 49, 110], OperandSize::Dword, ) } #[test] fn vpsrldq_7() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM9)), operand2: Some(Direct(XMM17)), operand3: Some(Literal8(40)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 177, 53, 8, 115, 217, 40], OperandSize::Qword, ) } #[test] fn vpsrldq_8() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM16)), operand2: Some(IndirectScaledDisplaced( RDX, Four, 681780529, Some(Op
random
[ { "content": "fn encode64_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
cargo/vendor/memmap-0.6.1/src/windows.rs
mfarrugi/cargo-raze-example-stdx
e4283e299d298cea9a534d0623cb4f3b54ef36f5
extern crate kernel32; extern crate winapi; use std::{io, mem, ptr}; use std::fs::File; use std::os::raw::c_void; use std::os::windows::io::{AsRawHandle, RawHandle}; pub struct MmapInner { file: Option<File>, ptr: *mut c_void, len: usize, copy: bool, } impl MmapInner { pub fn new( file: &File, protect: winapi::DWORD, access: winapi::DWORD, offset: usize, len: usize, copy: bool, ) -> io::Result<MmapInner> { let alignment = offset % allocation_granularity(); let aligned_offset = offset - alignment; let aligned_len = len + alignment; unsafe { let handle = kernel32::CreateFileMappingW( file.as_raw_handle(), ptr::null_mut(), protect, 0, 0, ptr::null(), ); if handle == ptr::null_mut() { return Err(io::Error::last_os_error()); } let ptr = kernel32::MapViewOfFile( handle, access, (aligned_offset >> 16 >> 16) as winapi::DWORD, (aligned_offset & 0xffffffff) as winapi::DWORD, aligned_len as winapi::SIZE_T, ); kernel32::CloseHandle(handle); if ptr == ptr::null_mut() { Err(io::Error::last_os_error()) } else { Ok(MmapInner { file: Some(file.try_clone()?), ptr: ptr.offset(alignment as isize), len: len as usize, copy: copy, }) } } } pub fn map(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let write = protection_supported(file.as_raw_handle(), winapi::PAGE_READWRITE); let exec = protection_supported(file.as_raw_handle(), winapi::PAGE_EXECUTE_READ); let mut access = winapi::FILE_MAP_READ; let protection = match (write, exec) { (true, true) => { access |= winapi::FILE_MAP_WRITE | winapi::FILE_MAP_EXECUTE; winapi::PAGE_EXECUTE_READWRITE } (true, false) => { access |= winapi::FILE_MAP_WRITE; winapi::PAGE_READWRITE } (false, true) => { access |= winapi::FILE_MAP_EXECUTE; winapi::PAGE_EXECUTE_READ } (false, false) => winapi::PAGE_READONLY, }; let mut inner = MmapInner::new(file, protection, access, offset, len, false)?; if write || exec { inner.make_read_only()?; } Ok(inner) } pub fn map_exec(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let write = protection_supported(file.as_raw_handle(), winapi::PAGE_READWRITE); let mut access = winapi::FILE_MAP_READ | winapi::FILE_MAP_EXECUTE; let protection = if write { access |= winapi::FILE_MAP_WRITE; winapi::PAGE_EXECUTE_READWRITE } else { winapi::PAGE_EXECUTE_READ }; let mut inner = MmapInner::new(file, protection, access, offset, len, false)?; if write { inner.make_exec()?; } Ok(inner) } pub fn map_mut(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let exec = protection_supported(file.as_raw_handle(), winapi::PAGE_EXECUTE_READ); let mut access = winapi::FILE_MAP_READ | winapi::FILE_MAP_WRITE; let protection = if exec { access |= winapi::FILE_MAP_EXECUTE; winapi::PAGE_EXECUTE_READWRITE } else { winapi::PAGE_READWRITE }; let mut inner = MmapInner::new(file, protection, access, offset, len, false)?; if exec { inner.make_mut()?; } Ok(inner) } pub fn map_copy(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let exec = protection_supported(file.as_raw_handle(), winapi::PAGE_EXECUTE_READWRITE); let mut access = winapi::FILE_MAP_COPY; let protection = if exec { access |= winapi::FILE_MAP_EXECUTE; winapi::PAGE_EXECUTE_WRITECOPY } else { winapi::PAGE_WRITECOPY }; let mut inner = MmapInner::new(file, protection, access, offset, len, true)?; if exec { inner.make_mut()?; } Ok(inner) } pub fn map_anon(len: usize, _stack: bool) -> io::Result<MmapInner> { unsafe { let handle = kernel32::CreateFileMappingW( winapi::INVALID_HANDLE_VALUE, ptr::null_mut(), winapi::PAGE_EXECUTE_READWRITE, (len >> 16 >> 16) as winapi::DWORD, (len & 0xffffffff) as winapi::DWORD, ptr::null(), ); if handle == ptr::null_mut() { return Err(io::Error::last_os_error()); } let access = winapi::FILE_MAP_ALL_ACCESS | winapi::FILE_MAP_EXECUTE; let ptr = kernel32::MapViewOfFile(handle, access, 0, 0, len as winapi::SIZE_T); kernel32::CloseHandle(handle); if ptr == ptr::null_mut() { return Err(io::Error::last_os_error()); } let mut old = 0; let result = kernel32::VirtualProtect( ptr, len as winapi::SIZE_T, winapi::PAGE_READWRITE, &mut old, ); if result != 0 { Ok(MmapInner { file: None, ptr: ptr, len: len as usize, copy: false, }) } else { Err(io::Error::last_os_error()) } } } pub fn flush(&self, offset: usize, len: usize) -> io::Result<()> { self.flush_async(offset, len)?; if let Some(ref file) = self.file { file.sync_data()?; } Ok(()) } pub fn flush_async(&self, offset: usize, len: usize) -> io::Result<()> { let result = unsafe { kernel32::FlushViewOfFile(self.ptr.offset(offset as isize), len as winapi::SIZE_T) }; if result != 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } fn virtual_protect(&mut self, protect: winapi::DWORD) -> io::Result<()> { unsafe { let alignment = self.ptr as usize % allocation_granularity(); let ptr = self.ptr.offset(-(alignment as isize)); let aligned_len = self.len as winapi::SIZE_T + alignment as winapi::SIZE_T; let mut old = 0; let result = kernel32::VirtualProtect(ptr, aligned_len, protect, &mut old); if result != 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } } pub fn make_read_only(&mut self) -> io::Result<()> { self.virtual_protect(winapi::PAGE_READONLY) } pub fn make_exec(&mut self) -> io::Result<()> { if self.copy { self.virtual_protect(winapi::PAGE_EXECUTE_WRITECOPY) } else { self.virtual_protect(winapi::PAGE_EXECUTE_READ) } } pub fn make_mut(&mut self) -> io::Result<()> { if self.copy { self.virtual_protect(winapi::PAGE_WRITECOPY) } else { self.virtual_protect(winapi::PAGE_READWRITE) } } #[inline] pub fn ptr(&self) -> *const u8 { self.ptr as *const u8 } #[inline] pub fn mut_ptr(&mut self) -> *mut u8 { self.ptr as *mut u8 } #[inline] pub fn len(&self) -> usize { self.len } } impl Drop for MmapInner { fn drop(&mut self) { let alignment = self.ptr as usize % allocation_granularity(); unsafe { let ptr = self.ptr.offset(-(alignment as isize)); assert!( kernel32::UnmapViewOfFile(ptr) != 0, "unable to unmap mmap: {}", io::Error::last_os_error() ); } } } unsafe impl Sync for MmapInner {} unsafe impl Send for MmapInner {} fn protection_supported(handle: RawHandle, protection: winapi::DWORD) -> bool { unsafe { let handle = kernel32::CreateFileMappingW(handle, ptr::null_mut(), protection, 0, 0, ptr::null()); if handle == ptr::null_mut() { return false; } kernel32::CloseHandle(handle); true } } fn allocation_granularity() -> usize { unsafe { let mut info = mem::zeroed(); kernel32::GetSystemInfo(&mut info); return info.dwAllocationGranularity as usize; } }
extern crate kernel32; extern crate winapi; use std::{io, mem, ptr}; use std::fs::File; use std::os::raw::c_void; use std::os::windows::io::{AsRawHandle, RawHandle}; pub struct MmapInner { file: Option<File>, ptr: *mut c_void, len: usize, copy: bool, } impl MmapInner { pub fn new( file: &File, protect: winapi::DWORD, access: winapi::DWORD, offset: usize, len: usize, copy: bool, ) -> io::Result<MmapInner> { let alignment = offset % allocation_granularity(); let aligned_offset = offset - alignment; let aligned_len = len + alignment; unsafe { let handle = kernel32::CreateFileMappingW( file.as_raw_handle(), ptr::null_mut(), protect, 0, 0, ptr::null(), ); if handle == ptr::null_mut() { return Err(io::Error::last_os_error()); } let ptr = kernel32::MapViewOfFile( handle, access, (aligned_offset >> 16 >> 16) as winapi::DWORD, (aligned_offset & 0xffffffff) as winapi::DWORD, aligned_len as winapi::SIZE_T, ); kernel32::CloseHandle(handle); if ptr == ptr::null_mut() { Err(io::Error::last_os_error()) } else { Ok(MmapInner { file: Some(file.try_clone()?), ptr: ptr.offset(alignment as isize), len: len as usize, copy: copy, }) } } } pub fn map(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let write = protection_supported(file.as_raw_handle(), winapi::PAGE_READWRITE); let exec = protection_supported(file.as_raw_handle(), winapi::PAGE_EXECUTE_READ); let mut access = winapi::FILE_MAP_READ; let protection = match (write, exec) { (true, true) => { access |= winapi::FILE_MAP_WRITE | winapi::FILE_MAP_EXECUTE; winapi::PAGE_EXECUTE_READWRITE } (true, false) => { access |= winapi::FILE_MAP_WRITE; winapi::PAGE_READWRITE } (false, true) => { access |= winapi::FILE_MAP_EXECUTE; winapi::PAGE_EXECUTE_READ } (false, false) => winapi::PAGE_READONLY, }; let mut inner = MmapInner::new(file, protection, access, offset, len, false)?; if write || exec { inner.make_read_only()?; } Ok(inner) }
pub fn map_mut(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let exec = protection_supported(file.as_raw_handle(), winapi::PAGE_EXECUTE_READ); let mut access = winapi::FILE_MAP_READ | winapi::FILE_MAP_WRITE; let protection = if exec { access |= winapi::FILE_MAP_EXECUTE; winapi::PAGE_EXECUTE_READWRITE } else { winapi::PAGE_READWRITE }; let mut inner = MmapInner::new(file, protection, access, offset, len, false)?; if exec { inner.make_mut()?; } Ok(inner) } pub fn map_copy(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let exec = protection_supported(file.as_raw_handle(), winapi::PAGE_EXECUTE_READWRITE); let mut access = winapi::FILE_MAP_COPY; let protection = if exec { access |= winapi::FILE_MAP_EXECUTE; winapi::PAGE_EXECUTE_WRITECOPY } else { winapi::PAGE_WRITECOPY }; let mut inner = MmapInner::new(file, protection, access, offset, len, true)?; if exec { inner.make_mut()?; } Ok(inner) } pub fn map_anon(len: usize, _stack: bool) -> io::Result<MmapInner> { unsafe { let handle = kernel32::CreateFileMappingW( winapi::INVALID_HANDLE_VALUE, ptr::null_mut(), winapi::PAGE_EXECUTE_READWRITE, (len >> 16 >> 16) as winapi::DWORD, (len & 0xffffffff) as winapi::DWORD, ptr::null(), ); if handle == ptr::null_mut() { return Err(io::Error::last_os_error()); } let access = winapi::FILE_MAP_ALL_ACCESS | winapi::FILE_MAP_EXECUTE; let ptr = kernel32::MapViewOfFile(handle, access, 0, 0, len as winapi::SIZE_T); kernel32::CloseHandle(handle); if ptr == ptr::null_mut() { return Err(io::Error::last_os_error()); } let mut old = 0; let result = kernel32::VirtualProtect( ptr, len as winapi::SIZE_T, winapi::PAGE_READWRITE, &mut old, ); if result != 0 { Ok(MmapInner { file: None, ptr: ptr, len: len as usize, copy: false, }) } else { Err(io::Error::last_os_error()) } } } pub fn flush(&self, offset: usize, len: usize) -> io::Result<()> { self.flush_async(offset, len)?; if let Some(ref file) = self.file { file.sync_data()?; } Ok(()) } pub fn flush_async(&self, offset: usize, len: usize) -> io::Result<()> { let result = unsafe { kernel32::FlushViewOfFile(self.ptr.offset(offset as isize), len as winapi::SIZE_T) }; if result != 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } fn virtual_protect(&mut self, protect: winapi::DWORD) -> io::Result<()> { unsafe { let alignment = self.ptr as usize % allocation_granularity(); let ptr = self.ptr.offset(-(alignment as isize)); let aligned_len = self.len as winapi::SIZE_T + alignment as winapi::SIZE_T; let mut old = 0; let result = kernel32::VirtualProtect(ptr, aligned_len, protect, &mut old); if result != 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } } pub fn make_read_only(&mut self) -> io::Result<()> { self.virtual_protect(winapi::PAGE_READONLY) } pub fn make_exec(&mut self) -> io::Result<()> { if self.copy { self.virtual_protect(winapi::PAGE_EXECUTE_WRITECOPY) } else { self.virtual_protect(winapi::PAGE_EXECUTE_READ) } } pub fn make_mut(&mut self) -> io::Result<()> { if self.copy { self.virtual_protect(winapi::PAGE_WRITECOPY) } else { self.virtual_protect(winapi::PAGE_READWRITE) } } #[inline] pub fn ptr(&self) -> *const u8 { self.ptr as *const u8 } #[inline] pub fn mut_ptr(&mut self) -> *mut u8 { self.ptr as *mut u8 } #[inline] pub fn len(&self) -> usize { self.len } } impl Drop for MmapInner { fn drop(&mut self) { let alignment = self.ptr as usize % allocation_granularity(); unsafe { let ptr = self.ptr.offset(-(alignment as isize)); assert!( kernel32::UnmapViewOfFile(ptr) != 0, "unable to unmap mmap: {}", io::Error::last_os_error() ); } } } unsafe impl Sync for MmapInner {} unsafe impl Send for MmapInner {} fn protection_supported(handle: RawHandle, protection: winapi::DWORD) -> bool { unsafe { let handle = kernel32::CreateFileMappingW(handle, ptr::null_mut(), protection, 0, 0, ptr::null()); if handle == ptr::null_mut() { return false; } kernel32::CloseHandle(handle); true } } fn allocation_granularity() -> usize { unsafe { let mut info = mem::zeroed(); kernel32::GetSystemInfo(&mut info); return info.dwAllocationGranularity as usize; } }
pub fn map_exec(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let write = protection_supported(file.as_raw_handle(), winapi::PAGE_READWRITE); let mut access = winapi::FILE_MAP_READ | winapi::FILE_MAP_EXECUTE; let protection = if write { access |= winapi::FILE_MAP_WRITE; winapi::PAGE_EXECUTE_READWRITE } else { winapi::PAGE_EXECUTE_READ }; let mut inner = MmapInner::new(file, protection, access, offset, len, false)?; if write { inner.make_exec()?; } Ok(inner) }
function_block-full_function
[ { "content": "fn main() {\n\n env_logger::init().unwrap();\n\n\n\n info!(\"All is well.\"); \n\n}\n", "file_path": "example/example.rs", "rank": 0, "score": 15112.634085037585 }, { "content": "fn main() {\n\n use std::io::Read;\n\n\n\n let mut resp = reqwest::get(\"https://www.ru...
Rust
src/services/mod.rs
eduardocanellas/lagoinha-rs
1b6fbc47bcc9801e1b9e0b55808a0e0619742fa0
pub mod cepla; pub mod correios; pub mod viacep; extern crate serde; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, Debug)] pub struct Address { pub cep: String, pub address: String, pub details: String, pub neighborhood: String, pub state: String, pub city: String, } pub trait Addressable { fn to_address(&self) -> Address; } impl Addressable for viacep::Address { fn to_address(&self) -> Address { let addr = Address { cep: self.cep.clone(), address: self.address.clone(), details: self.details.clone(), neighborhood: self.neighborhood.clone(), state: self.state.clone(), city: self.city.clone(), }; addr } } impl Addressable for correios::Address { fn to_address(&self) -> Address { let addr = Address { cep: self.cep.clone(), address: self.address.clone(), details: "".to_string(), neighborhood: self.neighborhood.clone(), state: self.state.clone(), city: self.city.clone(), }; addr } } impl Addressable for cepla::Address { fn to_address(&self) -> Address { let addr = Address { cep: self.cep.clone(), address: self.address.clone(), details: self.details.clone(), neighborhood: self.neighborhood.clone(), state: self.state.clone(), city: self.city.clone(), }; addr } } #[cfg(test)] mod tests { use super::cepla; use super::correios; use super::viacep; use super::Addressable; #[test] fn viacep_conversion() { let viac_addr = viacep::Address { cep: "70150-903".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), city: "Brasília".to_string(), state: "DF".to_string(), unidade: "".to_string(), ibge: "5300108".to_string(), gia: "".to_string(), }; let viac_addr = viac_addr.to_address(); let addr = super::Address { cep: "70150-903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), }; assert_eq!(addr.address, viac_addr.address); assert_eq!(addr.state, viac_addr.state); assert_eq!(addr.neighborhood, viac_addr.neighborhood); assert_eq!(addr.city, viac_addr.city); assert_eq!(addr.cep, viac_addr.cep); assert_eq!(addr.details, viac_addr.details); } #[test] fn correios_conversion() { let corr_addr = correios::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), }; let corr_addr = corr_addr.to_address(); let addr = super::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), }; assert_eq!(addr.address, corr_addr.address); assert_eq!(addr.state, corr_addr.state); assert_eq!(addr.neighborhood, corr_addr.neighborhood); assert_eq!(addr.city, corr_addr.city); assert_eq!(addr.cep, corr_addr.cep); } #[test] fn cepla_conversion() { let cepl_addr = cepla::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), }; let cepl_addr = cepl_addr.to_address(); let addr = super::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), }; assert_eq!(addr.address, cepl_addr.address); assert_eq!(addr.state, cepl_addr.state); assert_eq!(addr.neighborhood, cepl_addr.neighborhood); assert_eq!(addr.city, cepl_addr.city); assert_eq!(addr.cep, cepl_addr.cep); assert_eq!(addr.details, cepl_addr.details); } }
pub mod cepla; pub mod correios; pub mod viacep; extern crate serde; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, Debug)] pub struct Address { pub cep: String, pub address: String, pub details: String, pub neighborhood: String, pub state: String, pub city: String, } pub trait Addressable { fn to_address(&self) -> Address; } impl Addressable for viacep::Address { fn to_address(&self) -> Address { let addr = Address { cep: self.cep.clone(), address: self.address.clone(), details: self.details.clone(), neighborhood: self.neighborhood.clone(), state: self.state.clone(), city: self.city.clone(), }; addr } } impl Addressable for correios::Address { fn to_address(&self) -> Address { let addr = Address { cep: self.cep.clone(), address: self.address.clone(), details: "".to_string(), neighborhood: self.neighborhood.clone(), state: self.state.clone(), city: self.city.clone(), }; addr } } impl Addressable for cepla::Address { fn to_address(&self) -> Address { let addr = Address { cep: self.cep.clone(), address: self.address.clone(), details: self.details.clone(), neighborhood: self.neighborhood.clone(), state: self.state.clone(), city: self.city.clone(), }; addr } } #[cfg(test)] mod tests { use super::cepla; use super::correios; use super::viacep; use super::Addressable; #[test] fn viacep_conversion() { let viac_addr = viacep::Address { cep: "70150-903".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), city: "Brasília".to_string(), state: "DF".to_string(), unidade: "".to_string(), ibge: "5300108".to_string(), gia: "".to_string(), }; let viac_addr = viac_addr.to_address(); let addr = super::Address { cep: "70150-903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), }; assert_eq!(addr.address, viac_addr.address); assert_eq!(addr.state, viac_addr.state); assert_eq!(addr.neighborhood, viac_addr.neighborhood); assert_eq!(addr.city, viac_addr.city); assert_eq!(addr.cep, viac_addr.cep); assert_eq!(addr.details, viac_addr.details); } #[test] fn correios_conversion() { let corr_addr = correios::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), }; let corr_addr = corr_addr.to_address(); let addr = super::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), }; assert_eq!(addr.address, corr_addr.address); assert_eq!(addr.state, corr_addr.state); assert_eq!(addr.neighborhood, corr_addr.neighborhood); assert_eq!(addr.city, corr_addr.city); assert_eq!(addr.cep, corr_addr.cep); } #[test
ails); } }
] fn cepla_conversion() { let cepl_addr = cepla::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), }; let cepl_addr = cepl_addr.to_address(); let addr = super::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: "Palácio da Alvorada (Residência Oficial do Presidente da República)" .to_string(), }; assert_eq!(addr.address, cepl_addr.address); assert_eq!(addr.state, cepl_addr.state); assert_eq!(addr.neighborhood, cepl_addr.neighborhood); assert_eq!(addr.city, cepl_addr.city); assert_eq!(addr.cep, cepl_addr.cep); assert_eq!(addr.details, cepl_addr.det
random
[ { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n let mut cep: &str = \"20940040\".as_ref();\n\n if args.len() >= 2 {\n\n cep = &args[1][..];\n\n }\n\n let addr = async_std::task::block_on(lagoinha::get_address(cep, None));\n\n println!(\"{:#?}\", addr);\n...
Rust
src/operation.rs
Tak-Iwamoto/rusty-gql
8244d844f827a524cd91ba815fe5d113f3499927
use std::{ collections::HashMap, ops::Deref, sync::{Arc, Mutex}, }; use graphql_parser::{ query::{Definition, Document, FragmentDefinition, SelectionSet, VariableDefinition}, schema::Directive, }; use crate::{error::GqlError, Variables}; #[derive(Debug)] pub struct OperationInner<'a> { pub operation_type: OperationType, pub directives: Vec<Directive<'a, String>>, pub variable_definitions: Vec<VariableDefinition<'a, String>>, pub selection_set: SelectionSet<'a, String>, pub fragment_definitions: HashMap<String, FragmentDefinition<'a, String>>, pub errors: Mutex<Vec<GqlError>>, pub variables: Variables, } #[derive(Debug)] pub struct Operation<'a>(Arc<OperationInner<'a>>); impl<'a> Operation<'a> { pub fn new(operation: OperationInner<'a>) -> Operation<'a> { Operation(Arc::new(operation)) } } impl<'a> Deref for Operation<'a> { type Target = OperationInner<'a>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug)] struct OperationDefinition<'a> { operation_type: OperationType, directives: Vec<Directive<'a, String>>, variable_definitions: Vec<VariableDefinition<'a, String>>, selection_set: SelectionSet<'a, String>, } #[derive(Clone, Debug)] pub enum OperationType { Query, Mutation, Subscription, } impl ToString for OperationType { fn to_string(&self) -> String { match self { OperationType::Query => String::from("Query"), OperationType::Mutation => String::from("Mutation"), OperationType::Subscription => String::from("Subscription"), } } } pub fn get_operation_definitions<'a>( doc: &'a Document<'a, String>, ) -> Vec<&'a graphql_parser::query::Definition<'a, String>> { doc.definitions .iter() .filter(|def| matches!(def, Definition::Operation(_))) .collect::<Vec<_>>() } pub fn build_operation<'a>( doc: &'a Document<'a, String>, operation_name: Option<String>, variables: Variables, ) -> Result<Operation<'a>, GqlError> { let mut fragment_definitions = HashMap::new(); for def in &doc.definitions { if let Definition::Fragment(fragment) = def { let name = fragment.name.to_string(); fragment_definitions.insert(name, fragment.to_owned()); } } if operation_name.is_none() && get_operation_definitions(doc).len() > 1 { return Err(GqlError::new( "Must provide operation name if multiple operation exist", None, )); }; let mut operation_definitions: HashMap<String, OperationDefinition> = HashMap::new(); let no_name_key = "no_operation_name"; for definition in doc.clone().definitions { if let Definition::Operation(operation) = definition { match operation { graphql_parser::query::OperationDefinition::SelectionSet(selection_set) => { operation_definitions.insert( no_name_key.to_string(), OperationDefinition { operation_type: OperationType::Query, selection_set, directives: vec![], variable_definitions: vec![], }, ); } graphql_parser::query::OperationDefinition::Query(query) => { let query_name = query.name.unwrap_or_else(|| no_name_key.to_string()); operation_definitions.insert( query_name, OperationDefinition { operation_type: OperationType::Query, selection_set: query.selection_set, directives: query.directives, variable_definitions: query.variable_definitions, }, ); } graphql_parser::query::OperationDefinition::Mutation(mutation) => { let mutation_name = mutation.name.unwrap_or_else(|| no_name_key.to_string()); operation_definitions.insert( mutation_name, OperationDefinition { operation_type: OperationType::Mutation, selection_set: mutation.selection_set, directives: mutation.directives, variable_definitions: mutation.variable_definitions, }, ); } graphql_parser::query::OperationDefinition::Subscription(subscription) => { let subscription_name = subscription.name.unwrap_or_else(|| no_name_key.to_string()); operation_definitions.insert( subscription_name, OperationDefinition { operation_type: OperationType::Subscription, selection_set: subscription.selection_set, directives: subscription.directives, variable_definitions: subscription.variable_definitions, }, ); } } } } match operation_name { Some(name) => { let target_def = operation_definitions.get(name.as_str()); match target_def { Some(definition) => { let definition = definition.clone(); Ok(Operation(Arc::new(OperationInner { operation_type: definition.operation_type, fragment_definitions, directives: definition.directives, variable_definitions: definition.variable_definitions, selection_set: definition.selection_set, errors: Default::default(), variables, }))) } None => Err(GqlError::new( format!("operationName: {} is not contained in query", name), None, )), } } None => match operation_definitions.get(&no_name_key.to_string()) { Some(definition) => { let definition = definition.clone(); Ok(Operation(Arc::new(OperationInner { operation_type: definition.operation_type, fragment_definitions, directives: definition.directives, variable_definitions: definition.variable_definitions, selection_set: definition.selection_set, errors: Default::default(), variables, }))) } None => match operation_definitions.values().next() { Some(definition) => { let definition = definition.clone(); Ok(Operation(Arc::new(OperationInner { operation_type: definition.operation_type, fragment_definitions, directives: definition.directives, variable_definitions: definition.variable_definitions, selection_set: definition.selection_set, errors: Default::default(), variables, }))) } None => Err(GqlError::new("operation does not exist", None)), }, }, } } #[cfg(test)] mod tests { use crate::operation::build_operation; #[test] fn build_single_operation() { let parsed_query = graphql_parser::parse_query::<String>(r#"query GetPerson { persons { name age } }"#) .unwrap(); let operation = build_operation(&parsed_query, None, Default::default()); assert!(operation.is_ok()); assert_eq!(operation.unwrap().operation_type.to_string(), "Query"); } #[test] fn build_multiple_operation() { let parsed_query = graphql_parser::parse_query::<String>( r#"query GetPerson { persons { name age } } query GetPet { pets { name kind } }"#, ) .unwrap(); let operation = build_operation( &parsed_query, Some("GetPerson".to_string()), Default::default(), ); assert!(operation.is_ok()); assert_eq!(operation.unwrap().operation_type.to_string(), "Query"); } #[test] fn fails_build_multiple_operation_without_operation_name() { let parsed_query = graphql_parser::parse_query::<String>( r#"query GetPerson { persons { name age } } query GetPet { pets { name kind } }"#, ) .unwrap(); let operation = build_operation(&parsed_query, None, Default::default()); assert!(operation.is_err()); } }
use std::{ collections::HashMap, ops::Deref, sync::{Arc, Mutex}, }; use graphql_parser::{ query::{Definition, Document, FragmentDefinition, SelectionSet, VariableDefinition}, schema::Directive, }; use crate::{error::GqlError, Variables}; #[derive(Debug)] pub struct OperationInner<'a> { pub operation_type: OperationType, pub directives: Vec<Directive<'a, String>>, pub variable_definitions: Vec<VariableDefinition<'a, String>>, pub selection_set: SelectionSet<'a, String>, pub fragment_definitions: HashMap<String, FragmentDefinition<'a, String>>, pub errors: Mutex<Vec<GqlError>>, pub variables: Variables, } #[derive(Debug)] pub struct Operation<'a>(Arc<OperationInner<'a>>); impl<'a> Operation<'a> { pub fn new(operation: OperationInner<'a>) -> Operation<'a> { Operation(Arc::new(operation)) } } impl<'a> Deref for Operation<'a> { type Target = OperationInner<'a>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug)] struct OperationDefinition<'a> { operation_type: OperationType, directives: Vec<Directive<'a, String>>, variable_definitions: Vec<VariableDefinition<'a, String>>, selection_set: SelectionSet<'a, String>, } #[derive(Clone, Debug)] pub enum OperationType { Query, Mutation, Subscription, } impl ToString for OperationType { fn to_string(&self) -> String {
} } pub fn get_operation_definitions<'a>( doc: &'a Document<'a, String>, ) -> Vec<&'a graphql_parser::query::Definition<'a, String>> { doc.definitions .iter() .filter(|def| matches!(def, Definition::Operation(_))) .collect::<Vec<_>>() } pub fn build_operation<'a>( doc: &'a Document<'a, String>, operation_name: Option<String>, variables: Variables, ) -> Result<Operation<'a>, GqlError> { let mut fragment_definitions = HashMap::new(); for def in &doc.definitions { if let Definition::Fragment(fragment) = def { let name = fragment.name.to_string(); fragment_definitions.insert(name, fragment.to_owned()); } } if operation_name.is_none() && get_operation_definitions(doc).len() > 1 { return Err(GqlError::new( "Must provide operation name if multiple operation exist", None, )); }; let mut operation_definitions: HashMap<String, OperationDefinition> = HashMap::new(); let no_name_key = "no_operation_name"; for definition in doc.clone().definitions { if let Definition::Operation(operation) = definition { match operation { graphql_parser::query::OperationDefinition::SelectionSet(selection_set) => { operation_definitions.insert( no_name_key.to_string(), OperationDefinition { operation_type: OperationType::Query, selection_set, directives: vec![], variable_definitions: vec![], }, ); } graphql_parser::query::OperationDefinition::Query(query) => { let query_name = query.name.unwrap_or_else(|| no_name_key.to_string()); operation_definitions.insert( query_name, OperationDefinition { operation_type: OperationType::Query, selection_set: query.selection_set, directives: query.directives, variable_definitions: query.variable_definitions, }, ); } graphql_parser::query::OperationDefinition::Mutation(mutation) => { let mutation_name = mutation.name.unwrap_or_else(|| no_name_key.to_string()); operation_definitions.insert( mutation_name, OperationDefinition { operation_type: OperationType::Mutation, selection_set: mutation.selection_set, directives: mutation.directives, variable_definitions: mutation.variable_definitions, }, ); } graphql_parser::query::OperationDefinition::Subscription(subscription) => { let subscription_name = subscription.name.unwrap_or_else(|| no_name_key.to_string()); operation_definitions.insert( subscription_name, OperationDefinition { operation_type: OperationType::Subscription, selection_set: subscription.selection_set, directives: subscription.directives, variable_definitions: subscription.variable_definitions, }, ); } } } } match operation_name { Some(name) => { let target_def = operation_definitions.get(name.as_str()); match target_def { Some(definition) => { let definition = definition.clone(); Ok(Operation(Arc::new(OperationInner { operation_type: definition.operation_type, fragment_definitions, directives: definition.directives, variable_definitions: definition.variable_definitions, selection_set: definition.selection_set, errors: Default::default(), variables, }))) } None => Err(GqlError::new( format!("operationName: {} is not contained in query", name), None, )), } } None => match operation_definitions.get(&no_name_key.to_string()) { Some(definition) => { let definition = definition.clone(); Ok(Operation(Arc::new(OperationInner { operation_type: definition.operation_type, fragment_definitions, directives: definition.directives, variable_definitions: definition.variable_definitions, selection_set: definition.selection_set, errors: Default::default(), variables, }))) } None => match operation_definitions.values().next() { Some(definition) => { let definition = definition.clone(); Ok(Operation(Arc::new(OperationInner { operation_type: definition.operation_type, fragment_definitions, directives: definition.directives, variable_definitions: definition.variable_definitions, selection_set: definition.selection_set, errors: Default::default(), variables, }))) } None => Err(GqlError::new("operation does not exist", None)), }, }, } } #[cfg(test)] mod tests { use crate::operation::build_operation; #[test] fn build_single_operation() { let parsed_query = graphql_parser::parse_query::<String>(r#"query GetPerson { persons { name age } }"#) .unwrap(); let operation = build_operation(&parsed_query, None, Default::default()); assert!(operation.is_ok()); assert_eq!(operation.unwrap().operation_type.to_string(), "Query"); } #[test] fn build_multiple_operation() { let parsed_query = graphql_parser::parse_query::<String>( r#"query GetPerson { persons { name age } } query GetPet { pets { name kind } }"#, ) .unwrap(); let operation = build_operation( &parsed_query, Some("GetPerson".to_string()), Default::default(), ); assert!(operation.is_ok()); assert_eq!(operation.unwrap().operation_type.to_string(), "Query"); } #[test] fn fails_build_multiple_operation_without_operation_name() { let parsed_query = graphql_parser::parse_query::<String>( r#"query GetPerson { persons { name age } } query GetPet { pets { name kind } }"#, ) .unwrap(); let operation = build_operation(&parsed_query, None, Default::default()); assert!(operation.is_err()); } }
match self { OperationType::Query => String::from("Query"), OperationType::Mutation => String::from("Mutation"), OperationType::Subscription => String::from("Subscription"), }
if_condition
[ { "content": "pub fn get_type_name(ty: &Type<'_, String>) -> String {\n\n match ty {\n\n Type::NamedType(named_type) => named_type.to_string(),\n\n Type::ListType(list) => get_type_name(list),\n\n Type::NonNullType(non_null) => get_type_name(non_null),\n\n }\n\n}\n\n\n", "file_pat...
Rust
src/encoding/unmarshal.rs
KevinKelley/hobbits-rs
1b2a4f3c8634921a379aa70992fe000973cf130b
pub use crate::encoding::envelope::Envelope; pub use crate::encoding::EwpError; pub fn unmarshal(msg: &[u8]) -> Result<Envelope,EwpError> { let index = msg.iter().position(|&r| r == '\n' as u8); let index = index.ok_or( EwpError::new("message request must contain 2 lines") )?; let hdr = &msg[0..index]; let payload = &msg[(index+1)..]; let hdr_str = String::from_utf8(hdr.to_vec())?; let hdr_parts: Vec<&str> = hdr_str.split(' ').collect(); if hdr_parts.len() != 5 { return Err(EwpError::new("not all metadata provided")) } if hdr_parts[0] != "EWP" { return Err(EwpError::new("malformed EWP envelope: must start with 'EWP'")) } let version = hdr_parts[1]; if !version.contains('.') { return Err(EwpError::new("EWP version cannot be parsed")) } if version.parse::<f32>().is_err() { return Err(EwpError::new("version should be of the form 0.0")) } let protocol = hdr_parts[2]; if protocol != "GOSSIP" && protocol != "RPC" && protocol != "PING" { return Err(EwpError::new("communication protocol unsupported")) } let msg_hdr_len: usize = hdr_parts[3].parse() .map_err(|_| EwpError::new("incorrect metadata format, cannot parse header-length"))?; let msg_bdy_len: usize = hdr_parts[4].parse() .map_err(|_| EwpError::new("incorrect metadata format, cannot parse body-length"))?; if payload.len() != msg_hdr_len + msg_bdy_len { return Err(EwpError::new(&format!("unexpected payload size: {} != {} + {}", payload.len(), msg_hdr_len, msg_bdy_len))) } let msg_hdr = &payload[0..msg_hdr_len]; let msg_bdy = &payload[msg_hdr_len..]; Ok( Envelope { version: version.to_string(), protocol: protocol.to_string(), header: msg_hdr.to_owned(), body: msg_bdy.to_owned() }) } #[cfg(test)] mod tests { use super::{Envelope, unmarshal}; #[test] fn test_unmarshal_successful() { struct Test { message: Vec<u8>, output: Envelope } let tests: Vec<Test> = vec!( Test { message: "EWP 13.05 RPC 16 14\nthis is a headerthis is a body".to_string().into_bytes(), output: Envelope { version: "13.05".to_string(), protocol: "RPC".to_string(), header: "this is a header".to_string().into_bytes(), body: "this is a body".to_string().into_bytes(), }, }, Test { message: "EWP 13.05 GOSSIP 7 12\ntestingtesting body".to_string().into_bytes(), output: Envelope { version: "13.05".to_string(), protocol: "GOSSIP".to_string(), header: "testing".to_string().into_bytes(), body: "testing body".to_string().into_bytes(), }, }, Test { message: "EWP 1230329483.05392489 RPC 4 4\ntesttest".to_string().into_bytes(), output: Envelope { version: "1230329483.05392489".to_string(), protocol: "RPC".to_string(), header: "test".to_string().into_bytes(), body: "test".to_string().into_bytes(), }, }, ); for t in tests.iter() { let unmarshalled = unmarshal(&t.message); if let Ok(msg) = unmarshalled { println!("{}", t.output); assert!(msg == t.output); } else { assert!(false); } } } #[test] fn test_unmarshal_unsuccessful() { use super::*; struct Test { message: Vec<u8>, err: EwpError } let tests: Vec<Test> = vec!( Test { message: "EWP 13.05 RPC blahblahblah json 16 14this is a headerthis is a body".to_string().into_bytes(), err: EwpError::new("message request must contain 2 lines"), }, Test { message: "EWP 13.05 7 12\ntestingtesting body".to_string().into_bytes(), err: EwpError::new("not all metadata provided"), }, Test { message: "EWP 123032948392489 RPC 4 4\ntesttest".to_string().into_bytes(), err: EwpError::new("EWP version cannot be parsed"), }, Test { message: "EWP 123032948.392489 notrpc 4 4\ntesttest".to_string().into_bytes(), err: EwpError::new("communication protocol unsupported"), }, Test { message: "EWP 123032948.392489 GOSSIP f 4\ntesttest".to_string().into_bytes(), err: EwpError::new("incorrect metadata format, cannot parse header-length"), }, Test { message: "EWP 123032948.392489 GOSSIP 4 f\ntesttest".to_string().into_bytes(), err: EwpError::new("incorrect metadata format, cannot parse body-length"), }, ); for t in tests.iter() { let unmarshalled = unmarshal(&t.message); match unmarshalled { Ok(msg) => { println!("expected: {}", &t.err); println!("received: {}", msg); assert!(msg != msg) } Err(err) => { println!("expected: '{}'", t.err.details); println!("received: '{}'", err.details); assert!(t.err.details == err.details) } } } } }
pub use crate::encoding::envelope::Envelope; pub use crate::encoding::EwpError; pub fn unmarshal(msg: &[u8]) -> Result<Envelope,EwpError> { let index = msg.iter().position(|&r| r == '\n' as u8); let index = index.ok_or( EwpError::new("message request must contain 2 lines") )?; let hdr = &msg[0..index]; let payload = &msg[(index+1)..]; let hdr_str = String::from_utf8(hdr.to_vec())?; let hdr_parts: Vec<&str> = hdr_str.split(' ').collect(); if hdr_parts.len() != 5 { return Err(EwpError::new("not all metadata provided")) } if hdr_parts[0] != "EWP" { return Err(EwpError::new("malformed EWP envelope: must start with 'EWP'")) } let version = hdr_parts[1]; if !version.contains('.') { return Err(EwpError::new("EWP version cannot be parsed")) } if version.parse::<f32>().is_err() { return Err(EwpError::new("version should be of the form 0.0")) } let protocol = hdr_parts[2]; if protocol != "GOSSIP" && protocol != "RPC" && protocol != "PING" { return Err(EwpError::new("communication protocol unsupported")) } let msg_hdr_len: usize = hdr_parts[3].parse() .map_err(|_| EwpError::new("incorrect metadata format, cannot parse header-length"))?; let msg_bdy_len: usize = hdr_parts[4].parse() .map_err(|_| EwpError::new("incorrect metadata format, cannot parse body-length"))?; if payload.len() != msg_hdr_len + msg_bdy_len { return Err(EwpError::new(&format!("unexpected payload size: {} != {} + {}", payload.len(), msg_hdr_len, msg_bdy_len))) } let msg_hdr = &payload[0..msg_hdr_len]; let msg_bdy = &payload[msg_hdr_len..]; Ok( Envelope { version: version.to_string(), protocol: protocol.to_string(), header: msg_hdr.to_owned(), body: msg_bdy.to_owned() }) } #[cfg(test)] mod tests { use super::{Envelope, unmarshal}; #[test] fn test_unmarshal_successful() { struct Test { message: Vec<u8>, output: Envelope } let tests: Vec<Test> = vec!( Test { message: "EWP 13.05 RPC 16 14\nthis is a headerthis is a body".to_string().into_bytes(), output: Envelope { version: "13.05".to_string(), protocol: "RPC".to_string(), header: "this is a header".to_string().into_bytes(), body: "this is a body".to_string().into_bytes(), }, }, Test { message: "EWP 13.05 GOSSIP 7 12\ntestingtesting body".to_string().into_bytes(), output: Envelope { version: "13.05".to_string(), protocol: "GOSSIP".to_string(), header: "testing".to_string().into_bytes(), body: "testing body".to_string().into_bytes(), }, }, Test { message: "EWP 1230329483.05392489 RPC 4 4\ntesttest".to_string().into_bytes(), output: Envelope { version: "1230329483.05392489".to_string(), protocol: "RPC".to_string(), header: "test".to_string().into_bytes(), body: "test".to_string().into_bytes(), }, }, ); for t in tests.iter() { let unmarshalled = unmarshal(&t.message); if let Ok(msg) = unmarshalled { println!("{}", t.output); assert!(msg == t.output); } else { assert!(false); } } } #[test] fn test_unmarshal_unsuccessful() {
}
use super::*; struct Test { message: Vec<u8>, err: EwpError } let tests: Vec<Test> = vec!( Test { message: "EWP 13.05 RPC blahblahblah json 16 14this is a headerthis is a body".to_string().into_bytes(), err: EwpError::new("message request must contain 2 lines"), }, Test { message: "EWP 13.05 7 12\ntestingtesting body".to_string().into_bytes(), err: EwpError::new("not all metadata provided"), }, Test { message: "EWP 123032948392489 RPC 4 4\ntesttest".to_string().into_bytes(), err: EwpError::new("EWP version cannot be parsed"), }, Test { message: "EWP 123032948.392489 notrpc 4 4\ntesttest".to_string().into_bytes(), err: EwpError::new("communication protocol unsupported"), }, Test { message: "EWP 123032948.392489 GOSSIP f 4\ntesttest".to_string().into_bytes(), err: EwpError::new("incorrect metadata format, cannot parse header-length"), }, Test { message: "EWP 123032948.392489 GOSSIP 4 f\ntesttest".to_string().into_bytes(), err: EwpError::new("incorrect metadata format, cannot parse body-length"), }, ); for t in tests.iter() { let unmarshalled = unmarshal(&t.message); match unmarshalled { Ok(msg) => { println!("expected: {}", &t.err); println!("received: {}", msg); assert!(msg != msg) } Err(err) => { println!("expected: '{}'", t.err.details); println!("received: '{}'", err.details); assert!(t.err.details == err.details) } } } }
function_block-function_prefix_line
[ { "content": "/// Marshal takes a parsed message and encodes it to a wire protocol message\n\npub fn marshal(msg: &Envelope) -> Result<Vec<u8>, EwpError> {\n\n\n\n if msg.version == \"\" { return Err(EwpError::new(\"missing version!\")) }\n\n if msg.protocol == \"\" { return Err(EwpError::new(\"missing pr...
Rust
kiln_lib/src/kafka.rs
simplybusiness/Kiln
884e96059622c72e99254ac737bee25aee964adf
use addr::{parser::DomainName, psl::List}; use openssl_probe::ProbeResult; use rdkafka::config::ClientConfig; use rdkafka::consumer::stream_consumer::StreamConsumer; use rdkafka::error::KafkaError; use rdkafka::producer::future_producer::FutureProducer; use std::fmt::Display; #[derive(Debug, Clone)] pub struct KafkaBootstrapTlsConfig(Vec<String>); #[derive(Debug)] pub enum ValidationFailureReason { Missing, PresentButEmpty, CouldNotBeParsed, } impl Display for ValidationFailureReason { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ValidationFailureReason::Missing => f.write_str("value is missing"), ValidationFailureReason::PresentButEmpty => f.write_str("value is present but empty"), ValidationFailureReason::CouldNotBeParsed => f.write_str("value could not be parsed"), } } } #[derive(thiserror::Error, Debug)] pub enum KafkaConfigError { #[error("Required environment variable {var} failed validation because {reason}")] RequiredValueValidationFailure { var: String, reason: ValidationFailureReason, }, #[error("Optional environment variable {var} failed validation because {reason}")] OptionalValueValidationFailure { var: String, reason: ValidationFailureReason, }, #[error("Kafka client could not be created")] KafkaError(#[from] KafkaError), #[error("Could not find TLS trust store")] TlsTrustStore, } pub fn get_bootstrap_config<I>(vars: &mut I) -> Result<KafkaBootstrapTlsConfig, KafkaConfigError> where I: Iterator<Item = (String, String)>, { let local_vars: Vec<(String, String)> = vars.collect(); let disable_kafka_domain_validation = match local_vars .iter() .find(|var| var.0 == "DISABLE_KAFKA_DOMAIN_VALIDATION") { None => Ok(false), Some(var) => { if var.1.is_empty() { return Err(KafkaConfigError::OptionalValueValidationFailure { var: "DISABLE_KAFKA_DOMAIN_VALIDATION".into(), reason: ValidationFailureReason::PresentButEmpty, }); } else { match var.1.as_ref() { "true" => Ok(true), "false" => Ok(false), _ => Err(KafkaConfigError::OptionalValueValidationFailure { var: "DISABLE_KAFKA_DOMAIN_VALIDATION".into(), reason: ValidationFailureReason::CouldNotBeParsed, }), } } } }?; let kafka_bootstrap_tls = match local_vars.iter().find(|var| var.0 == "KAFKA_BOOTSTRAP_TLS") { None => Err(KafkaConfigError::RequiredValueValidationFailure { var: "KAFKA_BOOTSTRAP_TLS".into(), reason: ValidationFailureReason::Missing, }), Some(var) => { if var.1.is_empty() { return Err(KafkaConfigError::RequiredValueValidationFailure { var: "KAFKA_BOOTSTRAP_TLS".into(), reason: ValidationFailureReason::PresentButEmpty, }); } else { let raw_hosts: Vec<String> = var.1.split(',').map(|s| s.to_owned()).collect(); let valid = raw_hosts.iter().all(|x| { let parts: Vec<&str> = x.split(':').collect(); let domain_valid = if disable_kafka_domain_validation { true } else { List.parse_domain_name(parts[0]) .map(|name| name.has_known_suffix()) .unwrap_or(false) }; let port_valid = u16::from_str_radix(parts[1], 10).is_ok(); domain_valid && port_valid }); if valid { Ok(raw_hosts) } else { Err(KafkaConfigError::RequiredValueValidationFailure { var: "KAFKA_BOOTSTRAP_TLS".into(), reason: ValidationFailureReason::CouldNotBeParsed, }) } } } }?; Ok(KafkaBootstrapTlsConfig(kafka_bootstrap_tls)) } pub fn build_kafka_producer( config: KafkaBootstrapTlsConfig, ) -> Result<FutureProducer, KafkaConfigError> { let cert_probe_result = openssl_probe::probe(); let cert_location = match cert_probe_result { ProbeResult { cert_file, .. } if cert_file.is_some() => Ok(cert_file), ProbeResult { cert_dir, .. } if cert_dir.is_some() => Ok(cert_dir), _ => Err(KafkaConfigError::TlsTrustStore), }?; ClientConfig::new() .set("metadata.broker.list", &config.0.join(",")) .set("compression.type", "gzip") .set("security.protocol", "SSL") .set("ssl.cipher.suites", "ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256") .set("ssl.ca.location", cert_location.unwrap().to_string_lossy()) .set("message.max.bytes", "10000000") .create() .map_err(|err| err.into()) } pub fn build_kafka_consumer( config: KafkaBootstrapTlsConfig, consumer_group_name: String, ) -> Result<StreamConsumer, KafkaConfigError> { let cert_probe_result = openssl_probe::probe(); let cert_location = match cert_probe_result { ProbeResult { cert_file, .. } if cert_file.is_some() => Ok(cert_file), ProbeResult { cert_dir, .. } if cert_dir.is_some() => Ok(cert_dir), _ => Err(KafkaConfigError::TlsTrustStore), }?; ClientConfig::new() .set("metadata.broker.list", &config.0.join(",")) .set("group.id", &consumer_group_name) .set("compression.type", "gzip") .set("security.protocol", "SSL") .set("ssl.cipher.suites", "ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256") .set("ssl.ca.location", cert_location.unwrap().to_string_lossy()) .set("fetch.message.max.bytes", "10000000") .create() .map_err(|err| err.into()) } #[cfg(test)] mod tests { use super::*; #[allow(unused_must_use)] #[tokio::test] async fn creating_kafka_producer_does_not_return_a_client_config_error() { let config = KafkaBootstrapTlsConfig(vec!["host1:1234".to_string(), "host2:1234".to_string()]); build_kafka_producer(config).unwrap(); } #[allow(unused_must_use)] #[tokio::test] async fn creating_kafka_consumer_does_not_return_a_client_config_error() { let config = KafkaBootstrapTlsConfig(vec!["host1:1234".to_string(), "host2:1234".to_string()]); build_kafka_consumer(config, "TestConsumerGroup".to_string()).unwrap(); } #[test] fn get_bootstrap_config_returns_config_when_environment_vars_present_and_valid() { let hostname = "my.kafka.host.example.com:1234,my.second.kafka.host.example.com:1234".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname)].into_iter(); let expected = vec![ "my.kafka.host.example.com:1234".to_owned(), "my.second.kafka.host.example.com:1234".to_owned(), ]; let actual = get_bootstrap_config(&mut fake_vars).expect("expected Ok(_) value"); assert_eq!(actual.0, expected); } #[test] fn get_bootstrap_config_returns_error_when_environment_vars_missing() { let mut fake_vars = std::iter::empty::<(String, String)>(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value is missing" ) } #[test] fn get_bootstrap_config_returns_error_when_environment_vars_present_but_empty() { let hostname = "".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone())].into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value is present but empty" ) } #[test] fn get_bootstrap_config_returns_error_when_hostname_invalid_and_domain_validation_enabled() { let hostname = "kafka:1234".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone())].into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value could not be parsed" ) } #[test] fn get_bootstrap_config_returns_configration_when_hostname_not_a_valid_domain_and_domain_validation_disabled( ) { let hostname = "kafka:1234".to_owned(); let mut fake_vars = vec![ ("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone()), ( "DISABLE_KAFKA_DOMAIN_VALIDATION".to_owned(), "true".to_owned(), ), ] .into_iter(); let expected = vec![hostname.clone()]; let actual = get_bootstrap_config(&mut fake_vars).expect("expected Ok(_) value"); assert_eq!(actual.0, expected) } #[test] fn get_bootstrap_config_returns_error_when_port_number_invalid() { let hostname = "my.kafka.host.example.com:1234567".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone())].into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value could not be parsed" ) } #[test] fn get_bootstrap_config_returns_error_when_disable_kafka_domain_validation_present_but_empty() { let mut fake_vars = vec![("DISABLE_KAFKA_DOMAIN_VALIDATION".to_owned(), "".to_owned())].into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Optional environment variable DISABLE_KAFKA_DOMAIN_VALIDATION failed validation because value is present but empty" ) } #[test] fn get_bootstrap_config_returns_error_when_disable_kafka_domain_validation_present_but_invalid() { let mut fake_vars = vec![( "DISABLE_KAFKA_DOMAIN_VALIDATION".to_owned(), "blah".to_owned(), )] .into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Optional environment variable DISABLE_KAFKA_DOMAIN_VALIDATION failed validation because value could not be parsed" ) } }
use addr::{parser::DomainName, psl::List}; use openssl_probe::ProbeResult; use rdkafka::config::ClientConfig; use rdkafka::consumer::stream_consumer::StreamConsumer; use rdkafka::error::KafkaError; use rdkafka::producer::future_producer::FutureProducer; use std::fmt::Display; #[derive(Debug, Clone)] pub struct KafkaBootstrapTlsConfig(Vec<String>); #[derive(Debug)] pub enum ValidationFailureReason { Missing, PresentButEmpty, CouldNotBeParsed, } impl Display for ValidationFailureReason { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ValidationFailureReason::Missing => f.write_str("value is missing"), ValidationFailureReason::PresentButEmpty => f.write_str("value is present but empty"), ValidationFailureReason::CouldNotBeParsed => f.write_str("value could not be parsed"), } } } #[derive(thiserror::Error, Debug)] pub enum KafkaConfigError { #[error("Required environment variable {var} failed validation because {reason}")] RequiredValueValidationFailure { var: String, reason: ValidationFailureReason, }, #[error("Optional environment variable {var} failed validation because {reason}")] OptionalValueValidationFailure { var: String, reason: ValidationFailureReason, }, #[error("Kafka client could not be created")] KafkaError(#[from] KafkaError), #[error("Could not find TLS trust store")] TlsTrustStore, } pub fn get_bootstrap_config<I>(vars: &mut I) -> Result<KafkaBootstrapTlsConfig, KafkaConfigError> where I: Iterator<Item = (String, String)>, { let local_vars: Vec<(String, String)> = vars.collect(); let disable_kafka_domain_validation = match local_vars .iter() .find(|var| var.0 == "DISABLE_KAFKA_DOMAIN_VALIDATION") { None => Ok(false), Some(var) => { if var.1.is_empty() { return Err(KafkaConfigError::OptionalValueValidationFailure { var: "DISABLE_KAFKA_DOMAIN_VALIDATION".into(), reason: ValidationFailureReason::PresentButEmpty, }); } else { match var.1.as_ref() { "true" => Ok(true), "false" => Ok(false), _ => Err(KafkaConfigError::OptionalValueValidationFailure { var: "DISABLE_KAFKA_DOMAIN_VALIDATION".into(), reason: ValidationFailureReason::CouldNotBeParsed, }), } } } }?; let kafka_bootstrap_tls = match local_vars.iter().find(|var| var.0 == "KAFKA_BOOTSTRAP_TLS") { None => Err(KafkaConfigError::RequiredValueValidationFailure { var: "KAFKA_BOOTSTRAP_TLS".into(), reason: ValidationFailureReason::Missing, }), Some(var) => { if var.1.is_empty() { return Err(KafkaConfigError::RequiredValueValidationFailure { var: "KAFKA_BOOTSTRAP_TLS".into(), reason: ValidationFailureReason::PresentButEmpty, }); } else { let raw_hosts: Vec<String> = var.1.split(',').map(|s| s.to_owned()).collect(); let valid = raw_hosts.iter().all(|x| { let parts: Vec<&str> = x.split(':').collect(); let domain_valid = if disable_kafka_domain_validation { true } else { List.parse_domain_name(parts[0]) .map(|name| name.has_known_suffix()) .unwrap_or(false) }; let port_valid = u16::from_str_radix(parts[1], 10).is_ok(); domain_valid && port_valid }); if valid { Ok(raw_hosts) } else { Err(KafkaConfigError::RequiredValueValidationFailure { var: "KAFKA_BOOTSTRAP_TLS".into(), reason: ValidationFailureReason::CouldNotBeParsed, }) } } } }?; Ok(KafkaBootstrapTlsConfig(kafka_bootstrap_tls)) } pub fn build_kafka_producer( config: KafkaBootstrapTlsConfig, ) -> Result<FutureProducer, KafkaConfigError> { let cert_probe_result = openssl_probe::probe(); let cert_location = match cert_probe_result { ProbeResult { cert_file, .. } if cert_file.is_some() => Ok(cert_file), ProbeResult { cert_dir, .. } if cert_dir.is_some() => Ok(cert_dir), _ => Err(KafkaConfigError::TlsTrustStore), }?; ClientConfig::new() .set("metadata.broker.list", &config.0.join(",")) .set("compression.type", "gzip") .set("security.protocol", "SSL") .set("ssl.cipher.suites", "ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256") .set("ssl.ca.location", cert_location.unwrap().to_string_lossy()) .set("message.max.bytes", "10000000") .create() .map_err(|err| err.into()) } pub fn build_kafka_consumer( config: KafkaBootstrapTlsConfig, consumer_group_name: String, ) -> Result<StreamConsumer, KafkaConfigError> { let cert_probe_result = openssl_probe::probe(); let cert_location = match cert_probe_result { ProbeResult { cert_file, .. } if cert_file.is_some() => Ok(cert_file), ProbeResult { cert_dir, .. } if cert_dir.is_some() => Ok(cert_dir), _ => Err(KafkaConfigError::TlsTrustStore), }?; ClientConfig::new() .set("metadata.broker.list", &config.0.join(",")) .set("group.id", &consumer_group_name) .set("compression.type", "gzip") .set("security.protocol", "SSL") .set("ssl.cipher.suites", "ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256") .set("ssl.ca.location", cert_location.unwrap().to_string_lossy()) .set("fetch.message.max.bytes", "10000000") .create() .map_err(|err| err.into()) } #[cfg(test)] mod tests { use super::*; #[allow(unused_must_use)] #[tokio::test] async fn creating_kafka_producer_does_not_return_a_client_config_error() { let config = KafkaBootstrapTlsConfig(vec!["host1:1234".to_string(), "host2:1234".to_string()]); build_kafka_producer(config).unwrap(); } #[allow(unused_must_use)] #[tokio::test] async fn creating_kafka_consumer_does_not_return_a_client_config_error() { let config = KafkaBootstrapTlsConfig(vec!["host1:1234".to_string(), "host2:1234".to_string()]); build_kafka_consumer(config, "TestConsumerGroup".to_string()).unwrap(); } #[test] fn get_bootstrap_config_returns_config_when_environment_vars_present_and_valid() { let hostname = "my.kafka.host.example.com:1234,my.second.kafka.host.example.com:1234".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname)].into_iter(); let expected = vec![ "my.kafka.host.example.com:1234".to_owned(), "my.second.kafka.host.example.com:1234".to_owned(), ]; let actual = get_bootstrap_config(&mut fake_vars).expect("expected Ok(_) value"); assert_eq!(actual.0, expected); } #[test] fn get_bootstrap_config_returns_error_when_environment_vars_missing() { let mut fake_vars = std::iter::empty::<(String, String)>(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value is missing" ) } #[test] fn get_bootstrap_config_returns_error_when_environment_vars_present_but_empty() { let hostname = "".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone())].into_iter();
#[test] fn get_bootstrap_config_returns_error_when_hostname_invalid_and_domain_validation_enabled() { let hostname = "kafka:1234".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone())].into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value could not be parsed" ) } #[test] fn get_bootstrap_config_returns_configration_when_hostname_not_a_valid_domain_and_domain_validation_disabled( ) { let hostname = "kafka:1234".to_owned(); let mut fake_vars = vec![ ("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone()), ( "DISABLE_KAFKA_DOMAIN_VALIDATION".to_owned(), "true".to_owned(), ), ] .into_iter(); let expected = vec![hostname.clone()]; let actual = get_bootstrap_config(&mut fake_vars).expect("expected Ok(_) value"); assert_eq!(actual.0, expected) } #[test] fn get_bootstrap_config_returns_error_when_port_number_invalid() { let hostname = "my.kafka.host.example.com:1234567".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone())].into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value could not be parsed" ) } #[test] fn get_bootstrap_config_returns_error_when_disable_kafka_domain_validation_present_but_empty() { let mut fake_vars = vec![("DISABLE_KAFKA_DOMAIN_VALIDATION".to_owned(), "".to_owned())].into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Optional environment variable DISABLE_KAFKA_DOMAIN_VALIDATION failed validation because value is present but empty" ) } #[test] fn get_bootstrap_config_returns_error_when_disable_kafka_domain_validation_present_but_invalid() { let mut fake_vars = vec![( "DISABLE_KAFKA_DOMAIN_VALIDATION".to_owned(), "blah".to_owned(), )] .into_iter(); let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Optional environment variable DISABLE_KAFKA_DOMAIN_VALIDATION failed validation because value could not be parsed" ) } }
let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value is present but empty" ) }
function_block-function_prefix_line
[ { "content": "#[derive(Clone, SerdeValue, Serialize, Deserialize)]\n\nstruct EventType(Vec<String>);\n\n\n", "file_path": "slack-connector/src/main.rs", "rank": 1, "score": 122833.64715094889 }, { "content": "#[derive(Clone, SerdeValue, Serialize, Deserialize)]\n\nstruct EventType(Vec<String...
Rust
src/get_stats.rs
razorheadfx/project-cleanup
8444bb77da3b5ed969bcd28f4daf4c09363a5fc8
use std::{ thread, process }; use std::path::PathBuf; use std::sync::mpsc::channel; use std::collections::HashMap; use colored::*; use humansize::{ FileSize, file_size_opts as options }; use crate::languages::*; use crate::file_utils::{ fname, walk_files }; use crate::spinner::Spinner; #[derive(Debug)] pub struct Stats { pub size_deps : u64, pub size_src : u64, pub modified : u64 } pub struct StatsResult { stats : HashMap<PathBuf, Stats>, langs : HashMap<Language, u32>, total_size_src : u64, total_size_deps_candelete : u64, total_size_deps_modified : u64 } pub fn get(project_paths : Vec<PathBuf>) -> HashMap<PathBuf, Stats> { let (tx, rc) = channel(); thread::spawn(move || { let mut stats = HashMap::new(); let mut langs = HashMap::new(); langs.insert(NODE, 0); langs.insert(RUST, 0); langs.insert(JAVA, 0); let mut total_size_src = 0; let mut total_size_deps_candelete = 0; let mut total_size_deps_modified = 0; for path in project_paths { let _ = tx.send(None); let lang = identify(&path).unwrap(); if let Some(lang_counter) = langs.get_mut(&lang) { *lang_counter += 1; } let size_src = walk_files(&path, &|p| !lang.get_paths().contains(&fname(&&p))) .into_iter() .filter_map(|p| p.metadata().ok()) .map(|d| d.len()) .fold(0, |acc, i| acc + i); total_size_src += size_src; let mut size_deps = 0; for p in lang.get_paths() { size_deps += walk_files(&path.join(p), &|_| true) .into_iter() .filter_map(|p| p.metadata().ok()) .map(|d| d.len()) .fold(0, |acc, i| acc + i); } let modified = walk_files(&path, &|p| !lang.get_paths().contains(&fname(&&p))) .into_iter() .filter_map(|p| p.metadata().ok()) .filter_map(|d| d.modified().ok()) .filter_map(|m| m.elapsed().ok()) .map(|e| e.as_secs()) .min().unwrap(); if modified > 2592000 { total_size_deps_candelete += size_deps; } else { total_size_deps_modified += size_deps; } stats.insert(path.clone(), Stats {size_deps, size_src, modified}); } let _ = tx.send(Some(StatsResult {stats, langs, total_size_src, total_size_deps_candelete, total_size_deps_modified})); }); println!("Analysing projects"); let mut spinner = Spinner::new("Analysing projects..."); let mut i = 0; loop { let data = rc.recv(); if let Err(err) = data { println!("Error in thread: {}", err); process::exit(0); } let data = data.unwrap(); if let Some(res) = data { let results : StatsResult = res; spinner.finish(format!("Analysed {} projects", results.stats.len()).as_str()); for (lang, count) in results.langs { if count == 1 { println!(" - {} {} project", count.to_string().bold(), lang.name()); } else if count > 1 { println!(" - {} {} projects", count.to_string().bold(), lang.name()); } } println!(" {} of source code and project files", format_size(results.total_size_src).bold()); if results.total_size_deps_candelete > 0 || results.total_size_deps_modified > 0 { if results.total_size_deps_candelete == 0 { println!(" No dependencies & builds over 1 month old"); } else { println!(" {} of dependencies & builds over 1 month old", format_size(results.total_size_deps_candelete).bold()); } if results.total_size_deps_modified == 0 { println!(" No recently used dependencies & builds"); } else { println!(" {} of recently used dependencies & builds", format_size(results.total_size_deps_modified).bold()); } } return results.stats; } i += 1; spinner.update(format!("Analysing {} projects...", i).as_str()); } } pub fn format_size(size : u64) -> String { return size.file_size(options::CONVENTIONAL).unwrap(); }
use std::{ thread, process }; use std::path::PathBuf; use std::sync::mpsc::channel; use std::collections::HashMap; use colored::*; use humansize::{ FileSize, file_size_opts as options }; use crate::languages::*; use crate::file_utils::{ fname, walk_files }; use crate::spinner::Spinner; #[derive(Debug)] pub struct Stats { pub size_deps : u64, pub size_src : u64, pub modified : u64 } pub struct StatsResult { stats : HashMap<PathBuf, Stats>, langs : HashMap<Language, u32>, total_size_src : u64, total_size_deps_candelete : u64, total_size_deps_modified : u64 }
pub fn format_size(size : u64) -> String { return size.file_size(options::CONVENTIONAL).unwrap(); }
pub fn get(project_paths : Vec<PathBuf>) -> HashMap<PathBuf, Stats> { let (tx, rc) = channel(); thread::spawn(move || { let mut stats = HashMap::new(); let mut langs = HashMap::new(); langs.insert(NODE, 0); langs.insert(RUST, 0); langs.insert(JAVA, 0); let mut total_size_src = 0; let mut total_size_deps_candelete = 0; let mut total_size_deps_modified = 0; for path in project_paths { let _ = tx.send(None); let lang = identify(&path).unwrap(); if let Some(lang_counter) = langs.get_mut(&lang) { *lang_counter += 1; } let size_src = walk_files(&path, &|p| !lang.get_paths().contains(&fname(&&p))) .into_iter() .filter_map(|p| p.metadata().ok()) .map(|d| d.len()) .fold(0, |acc, i| acc + i); total_size_src += size_src; let mut size_deps = 0; for p in lang.get_paths() { size_deps += walk_files(&path.join(p), &|_| true) .into_iter() .filter_map(|p| p.metadata().ok()) .map(|d| d.len()) .fold(0, |acc, i| acc + i); } let modified = walk_files(&path, &|p| !lang.get_paths().contains(&fname(&&p))) .into_iter() .filter_map(|p| p.metadata().ok()) .filter_map(|d| d.modified().ok()) .filter_map(|m| m.elapsed().ok()) .map(|e| e.as_secs()) .min().unwrap(); if modified > 2592000 { total_size_deps_candelete += size_deps; } else { total_size_deps_modified += size_deps; } stats.insert(path.clone(), Stats {size_deps, size_src, modified}); } let _ = tx.send(Some(StatsResult {stats, langs, total_size_src, total_size_deps_candelete, total_size_deps_modified})); }); println!("Analysing projects"); let mut spinner = Spinner::new("Analysing projects..."); let mut i = 0; loop { let data = rc.recv(); if let Err(err) = data { println!("Error in thread: {}", err); process::exit(0); } let data = data.unwrap(); if let Some(res) = data { let results : StatsResult = res; spinner.finish(format!("Analysed {} projects", results.stats.len()).as_str()); for (lang, count) in results.langs { if count == 1 { println!(" - {} {} project", count.to_string().bold(), lang.name()); } else if count > 1 { println!(" - {} {} projects", count.to_string().bold(), lang.name()); } } println!(" {} of source code and project files", format_size(results.total_size_src).bold()); if results.total_size_deps_candelete > 0 || results.total_size_deps_modified > 0 { if results.total_size_deps_candelete == 0 { println!(" No dependencies & builds over 1 month old"); } else { println!(" {} of dependencies & builds over 1 month old", format_size(results.total_size_deps_candelete).bold()); } if results.total_size_deps_modified == 0 { println!(" No recently used dependencies & builds"); } else { println!(" {} of recently used dependencies & builds", format_size(results.total_size_deps_modified).bold()); } } return results.stats; } i += 1; spinner.update(format!("Analysing {} projects...", i).as_str()); } }
function_block-full_function
[ { "content": "/// Gets the filename of a given path\n\npub fn fname(path : &Path) -> &str {\n\n\tpath.file_name().unwrap_or(OsStr::new(\"\")).to_str().unwrap_or(\"\")\n\n}\n", "file_path": "src/file_utils/mod.rs", "rank": 0, "score": 70209.53629687006 }, { "content": "pub fn identify(p : &Pa...
Rust
src/connectivity/bluetooth/profiles/bt-avrcp/src/metrics/mod.rs
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
use { fuchsia_bluetooth::types::PeerId, fuchsia_inspect::{self as inspect, NumericProperty}, fuchsia_inspect_derive::Inspect, parking_lot::Mutex, std::{collections::HashSet, sync::Arc}, }; use crate::profile::{AvrcpControllerFeatures, AvrcpTargetFeatures}; pub const METRICS_NODE_NAME: &str = "metrics"; #[derive(Default, Inspect)] struct PeerSupportMetrics { target_peers_supporting_browsing: inspect::UintProperty, target_peers_supporting_cover_art: inspect::UintProperty, controller_peers_supporting_browsing: inspect::UintProperty, controller_peers_supporting_cover_art: inspect::UintProperty, distinct_target_peers_supporting_browsing: inspect::UintProperty, distinct_target_peers_supporting_cover_art: inspect::UintProperty, distinct_controller_peers_supporting_browsing: inspect::UintProperty, distinct_controller_peers_supporting_cover_art: inspect::UintProperty, #[inspect(skip)] tg_browse_peers: HashSet<PeerId>, #[inspect(skip)] tg_cover_art_peers: HashSet<PeerId>, #[inspect(skip)] ct_browse_peers: HashSet<PeerId>, #[inspect(skip)] ct_cover_art_peers: HashSet<PeerId>, } #[derive(Default, Inspect)] struct MetricsNodeInner { connection_errors: inspect::UintProperty, control_connections: inspect::UintProperty, browse_connections: inspect::UintProperty, distinct_peers: inspect::UintProperty, #[inspect(skip)] distinct_peers_set: HashSet<PeerId>, control_channel_collisions: inspect::UintProperty, support_node: PeerSupportMetrics, inspect_node: inspect::Node, } impl MetricsNodeInner { fn check_distinct_peer(&mut self, id: PeerId) { if self.distinct_peers_set.insert(id) { self.distinct_peers.add(1); } } fn controller_supporting_browsing(&mut self, id: PeerId) { self.support_node.controller_peers_supporting_browsing.add(1); if self.support_node.ct_browse_peers.insert(id) { self.support_node.distinct_controller_peers_supporting_browsing.add(1); } } fn controller_supporting_cover_art(&mut self, id: PeerId) { self.support_node.controller_peers_supporting_cover_art.add(1); if self.support_node.ct_cover_art_peers.insert(id) { self.support_node.distinct_controller_peers_supporting_cover_art.add(1); } } fn target_supporting_browsing(&mut self, id: PeerId) { self.support_node.target_peers_supporting_browsing.add(1); if self.support_node.tg_browse_peers.insert(id) { self.support_node.distinct_target_peers_supporting_browsing.add(1); } } fn target_supporting_cover_art(&mut self, id: PeerId) { self.support_node.target_peers_supporting_cover_art.add(1); if self.support_node.tg_cover_art_peers.insert(id) { self.support_node.distinct_target_peers_supporting_cover_art.add(1); } } } #[derive(Clone, Default, Inspect)] pub struct MetricsNode { #[inspect(forward)] inner: Arc<Mutex<MetricsNodeInner>>, } impl MetricsNode { pub fn new_peer(&self, id: PeerId) { self.inner.lock().check_distinct_peer(id); } pub fn connection_error(&self) { self.inner.lock().connection_errors.add(1); } pub fn control_connection(&self) { self.inner.lock().control_connections.add(1); } pub fn browse_connection(&self) { self.inner.lock().browse_connections.add(1); } pub fn control_collision(&self) { self.inner.lock().control_channel_collisions.add(1); } pub fn controller_features(&self, id: PeerId, features: AvrcpControllerFeatures) { let mut inner = self.inner.lock(); if features.contains(AvrcpControllerFeatures::SUPPORTSBROWSING) { inner.controller_supporting_browsing(id); } if features.supports_cover_art() { inner.controller_supporting_cover_art(id); } } pub fn target_features(&self, id: PeerId, features: AvrcpTargetFeatures) { let mut inner = self.inner.lock(); if features.contains(AvrcpTargetFeatures::SUPPORTSBROWSING) { inner.target_supporting_browsing(id); } if features.contains(AvrcpTargetFeatures::SUPPORTSCOVERART) { inner.target_supporting_cover_art(id); } } } #[cfg(test)] mod tests { use super::*; use {fuchsia_inspect::assert_inspect_tree, fuchsia_inspect_derive::WithInspect}; #[test] fn multiple_peers_connection_updates_to_shared_node() { let inspect = inspect::Inspector::new(); let metrics = MetricsNode::default().with_inspect(inspect.root(), "metrics").unwrap(); let (id1, metrics1) = (PeerId(2220), metrics.clone()); let (id2, metrics2) = (PeerId(7982), metrics.clone()); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 0u64, control_connections: 0u64, browse_connections: 0u64, distinct_peers: 0u64, control_channel_collisions: 0u64, } }); metrics1.new_peer(id1); metrics1.connection_error(); metrics1.new_peer(id2); metrics2.control_connection(); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 1u64, control_connections: 1u64, browse_connections: 0u64, distinct_peers: 2u64, control_channel_collisions: 0u64, } }); metrics1.connection_error(); metrics1.connection_error(); metrics1.control_connection(); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 3u64, control_connections: 2u64, browse_connections: 0u64, distinct_peers: 2u64, control_channel_collisions: 0u64, } }); metrics1.new_peer(id1); metrics1.control_collision(); metrics1.control_connection(); metrics1.browse_connection(); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 3u64, control_connections: 3u64, browse_connections: 1u64, distinct_peers: 2u64, control_channel_collisions: 1u64, } }); } #[test] fn controller_peers_service_updates() { let inspect = inspect::Inspector::new(); let metrics = MetricsNode::default().with_inspect(inspect.root(), "metrics").unwrap(); let id1 = PeerId(1102); let tg_service1 = AvrcpTargetFeatures::empty(); let ct_service1 = AvrcpControllerFeatures::empty(); metrics.controller_features(id1, ct_service1); metrics.target_features(id1, tg_service1); assert_inspect_tree!(inspect, root: { metrics: contains { target_peers_supporting_browsing: 0u64, distinct_target_peers_supporting_browsing: 0u64, target_peers_supporting_cover_art: 0u64, distinct_target_peers_supporting_cover_art: 0u64, controller_peers_supporting_browsing: 0u64, distinct_controller_peers_supporting_browsing: 0u64, controller_peers_supporting_cover_art: 0u64, distinct_controller_peers_supporting_cover_art: 0u64, } }); let id2 = PeerId(1102); let ct_service2 = AvrcpControllerFeatures::all(); let tg_service2 = AvrcpTargetFeatures::all(); metrics.controller_features(id2, ct_service2); metrics.target_features(id2, tg_service2); assert_inspect_tree!(inspect, root: { metrics: contains { target_peers_supporting_browsing: 1u64, distinct_target_peers_supporting_browsing: 1u64, target_peers_supporting_cover_art: 1u64, distinct_target_peers_supporting_cover_art: 1u64, controller_peers_supporting_browsing: 1u64, distinct_controller_peers_supporting_browsing: 1u64, controller_peers_supporting_cover_art: 1u64, distinct_controller_peers_supporting_cover_art: 1u64, } }); metrics.controller_features(id2, ct_service2); metrics.target_features(id2, tg_service2); assert_inspect_tree!(inspect, root: { metrics: contains { target_peers_supporting_browsing: 2u64, distinct_target_peers_supporting_browsing: 1u64, target_peers_supporting_cover_art: 2u64, distinct_target_peers_supporting_cover_art: 1u64, controller_peers_supporting_browsing: 2u64, distinct_controller_peers_supporting_browsing: 1u64, controller_peers_supporting_cover_art: 2u64, distinct_controller_peers_supporting_cover_art: 1u64, } }); } }
use { fuchsia_bluetooth::types::PeerId, fuchsia_inspect::{self as inspect, NumericProperty}, fuchsia_inspect_derive::Inspect, parking_lot::Mutex, std::{collections::HashSet, sync::Arc}, }; use crate::profile::{AvrcpControllerFeatures, AvrcpTargetFeatures}; pub const METRICS_NODE_NAME: &str = "metrics"; #[derive(Default, Inspect)] struct PeerSupportMetrics { target_peers_supporting_browsing: inspect::UintProperty, target_peers_supporting_cover_art: inspect::UintProperty, controller_peers_supporting_browsing: inspect::UintProperty, controller_peers_supporting_cover_art: inspect::UintProperty, distinct_target_peers_supporting_browsing: inspect::UintProperty, distinct_target_peers_supporting_cover_art: inspect::UintProperty, distinct_controller_peers_supporting_browsing: inspect::UintProperty, distinct_controller_peers_supporting_cover_art: inspect::UintProperty, #[inspect(skip)] tg_browse_peers: HashSet<PeerId>, #[inspect(skip)] tg_cover_art_peers: HashSet<PeerId>, #[inspect(skip)] ct_browse_peers: HashSet<PeerId>, #[inspect(skip)] ct_cover_art_peers: HashSet<PeerId>, } #[derive(Default, Inspect)] struct MetricsNodeInner { connection_errors: inspect::UintProperty, control_connections: inspect::UintProperty, browse_connections: inspect::UintProperty, distinct_peers: inspect::UintProperty, #[inspect(skip)] distinct_peers_set: HashSet<PeerId>, control_channel_collisions: inspect::UintProperty, support_node: PeerSupportMetrics, inspect_node: inspect::Node, } impl MetricsNodeInner { fn check_distinct_peer(&mut self, id: PeerId) { if self.distinct_peers_set.insert(id) { self.distinct_peers.add(1); } } fn controller_supporting_browsing(&mut self, id: PeerId) { self.support_node.controller_peers_supporting_browsing.add(1); if self.support_node.ct_browse_peers.insert(id) { self.support_node.distinct_controller_peers_supporting_browsing.add(1); } } fn controller_supporting_cover_art(&mut self, id: PeerId) { self.support_node.controller_peers_supporting_cover_art.add(1); if self.support_node.ct_cover_art_peers.insert(id) { self.support_node.distinct_controller_peers_supporting_cover_art.add(1); } } fn target_supporting_browsing(&mut self, id: PeerId) { self.support_node.target_peers_supporting_browsing.add(1); if self.support_node.tg_browse_peers.insert(id) { self.support_node.distinct_target_peers_supporting_browsing.add(1); } } fn target_supporting_cover_art(&mut self, id: PeerId) { self.support_node.target_peers_supporting_cover_art.add(1); if self.support_node.tg_cover_art_peers.insert(id) { self.support_node.distinct_target_peers_supporting_cover_art.add(1); } } } #[derive(Clone, Default, Inspect)] pub struct MetricsNode { #[inspect(forward)] inner: Arc<Mutex<MetricsNodeInner>>, } impl MetricsNode { pub fn new_peer(&self, id: PeerId) { self.inner.lock().check_distinct_peer(id); } pub fn connection_error(&self) { self.inner.lock().connection_errors.add(1); } pub fn control_connection(&self) { self.inner.lock().control_connections.add(1); } pub fn browse_connection(&self) { self.inner.lock().browse_connections.add(1); } pub fn control_collision(&self) { self.inner.lock().control_channel_collisions.add(1); } pub fn controller_features(&self, id: PeerId, features: AvrcpControllerFeatures) { let mut inner = self.inner.lock(); if features.contains(AvrcpControllerFeatures::SUPPORTSBROWSING) { inner.controller_supporting_browsing(id); } if features.supports_cover_art() { inner.controller_supporting_cover_art(id); } } pub fn target_features(&self, id: PeerId, features: AvrcpTargetFeatures) { let mut inner = self.inner.lock(); if features.contains(AvrcpTargetFeatures::SUPPORTSBROWSING) { inner.target_supporting_browsing(id); } if features.contains(AvrcpTargetFeatures::SUPPORTSCOVERART) { inner.target_supporting_cover_art(id); } } } #[cfg(test)] mod tests { use super::*; use {fuchsia_inspect::assert_inspect_tree, fuchsia_inspect_derive::WithInspect}; #[test] fn multiple_peers_connection_updates_to_shared_node() { let inspect = inspect::Inspector::new(); let metrics = MetricsNode::default().with_inspect(inspect.root(), "metrics").unwrap(); let (id1, metrics1) = (PeerId(2220), metrics.clone()); let (id2, metrics2) = (PeerId(7982), metrics.clone()); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 0u64, control_connections: 0u64, browse_connections: 0u64, distinct_peers: 0u64, control_channel_collisions: 0u64, } }); metrics1.new_peer(id1); metrics1.connection_error(); metrics1.new_peer(id2); metric
r(id1); metrics1.control_collision(); metrics1.control_connection(); metrics1.browse_connection(); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 3u64, control_connections: 3u64, browse_connections: 1u64, distinct_peers: 2u64, control_channel_collisions: 1u64, } }); } #[test] fn controller_peers_service_updates() { let inspect = inspect::Inspector::new(); let metrics = MetricsNode::default().with_inspect(inspect.root(), "metrics").unwrap(); let id1 = PeerId(1102); let tg_service1 = AvrcpTargetFeatures::empty(); let ct_service1 = AvrcpControllerFeatures::empty(); metrics.controller_features(id1, ct_service1); metrics.target_features(id1, tg_service1); assert_inspect_tree!(inspect, root: { metrics: contains { target_peers_supporting_browsing: 0u64, distinct_target_peers_supporting_browsing: 0u64, target_peers_supporting_cover_art: 0u64, distinct_target_peers_supporting_cover_art: 0u64, controller_peers_supporting_browsing: 0u64, distinct_controller_peers_supporting_browsing: 0u64, controller_peers_supporting_cover_art: 0u64, distinct_controller_peers_supporting_cover_art: 0u64, } }); let id2 = PeerId(1102); let ct_service2 = AvrcpControllerFeatures::all(); let tg_service2 = AvrcpTargetFeatures::all(); metrics.controller_features(id2, ct_service2); metrics.target_features(id2, tg_service2); assert_inspect_tree!(inspect, root: { metrics: contains { target_peers_supporting_browsing: 1u64, distinct_target_peers_supporting_browsing: 1u64, target_peers_supporting_cover_art: 1u64, distinct_target_peers_supporting_cover_art: 1u64, controller_peers_supporting_browsing: 1u64, distinct_controller_peers_supporting_browsing: 1u64, controller_peers_supporting_cover_art: 1u64, distinct_controller_peers_supporting_cover_art: 1u64, } }); metrics.controller_features(id2, ct_service2); metrics.target_features(id2, tg_service2); assert_inspect_tree!(inspect, root: { metrics: contains { target_peers_supporting_browsing: 2u64, distinct_target_peers_supporting_browsing: 1u64, target_peers_supporting_cover_art: 2u64, distinct_target_peers_supporting_cover_art: 1u64, controller_peers_supporting_browsing: 2u64, distinct_controller_peers_supporting_browsing: 1u64, controller_peers_supporting_cover_art: 2u64, distinct_controller_peers_supporting_cover_art: 1u64, } }); } }
s2.control_connection(); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 1u64, control_connections: 1u64, browse_connections: 0u64, distinct_peers: 2u64, control_channel_collisions: 0u64, } }); metrics1.connection_error(); metrics1.connection_error(); metrics1.control_connection(); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 3u64, control_connections: 2u64, browse_connections: 0u64, distinct_peers: 2u64, control_channel_collisions: 0u64, } }); metrics1.new_pee
function_block-random_span
[]
Rust
src/record.rs
marcsch/seq_io
3d461a3651fb975cd509fd7f580f1b44ccd9b9d3
use memchr::memchr; use std::borrow::Cow; use std::io; use std::str; pub use crate::core::{QualRecordPosition, SeqRecordPosition}; pub trait BaseRecord { fn head(&self) -> &[u8]; fn seq(&self) -> &[u8]; fn full_seq(&self) -> Cow<[u8]>; fn full_seq_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]> where F: FnOnce() -> &'s mut Vec<u8>; fn num_seq_lines(&self) -> usize; fn has_quality(&self) -> bool; fn opt_qual(&self) -> Option<&[u8]>; fn opt_full_qual(&self) -> Option<Cow<[u8]>>; fn opt_full_qual_given<'s, F>(&'s self, owned_fn: F) -> Option<Cow<'s, [u8]>> where F: FnOnce() -> &'s mut Vec<u8>; fn num_qual_lines(&self) -> usize; fn write<W>(&self, writer: W) -> io::Result<()> where W: io::Write; #[inline] fn id_bytes(&self) -> &[u8] { let head = self.head(); if let Some(pos) = memchr(b' ', head) { return &head[..pos]; } head } #[inline] fn id(&self) -> Result<&str, str::Utf8Error> { str::from_utf8(self.id_bytes()) } #[inline] fn desc_bytes(&self) -> Option<&[u8]> { let head = self.head(); if let Some(pos) = memchr(b' ', head) { return Some(&head[pos + 1..]); } None } #[inline] fn desc(&self) -> Option<Result<&str, str::Utf8Error>> { self.desc_bytes().map(str::from_utf8) } #[inline] fn id_desc_bytes(&self) -> (&[u8], Option<&[u8]>) { let head = self.head(); if let Some(pos) = memchr(b' ', head) { return (&head[..pos], Some(&head[pos + 1..])); } (head, None) } #[inline] fn id_desc(&self) -> Result<(&str, Option<&str>), str::Utf8Error> { let (id, desc) = self.id_desc_bytes(); Ok((str::from_utf8(id)?, desc.map(str::from_utf8).transpose()?)) } } impl<'a, R> BaseRecord for &'a R where R: BaseRecord, { fn head(&self) -> &[u8] { (**self).head() } fn seq(&self) -> &[u8] { (**self).seq() } fn full_seq(&self) -> Cow<[u8]> { (**self).full_seq() } fn full_seq_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]> where F: FnOnce() -> &'s mut Vec<u8>, { (**self).full_seq_given(owned_fn) } fn num_seq_lines(&self) -> usize { (**self).num_seq_lines() } fn id_bytes(&self) -> &[u8] { (**self).id_bytes() } fn id(&self) -> Result<&str, std::str::Utf8Error> { (**self).id() } fn desc_bytes(&self) -> Option<&[u8]> { (**self).desc_bytes() } fn desc(&self) -> Option<Result<&str, std::str::Utf8Error>> { (**self).desc() } fn id_desc_bytes(&self) -> (&[u8], Option<&[u8]>) { (**self).id_desc_bytes() } fn id_desc(&self) -> Result<(&str, Option<&str>), std::str::Utf8Error> { (**self).id_desc() } fn has_quality(&self) -> bool { (**self).has_quality() } fn opt_qual(&self) -> Option<&[u8]> { (**self).opt_qual() } fn opt_full_qual(&self) -> Option<Cow<[u8]>> { (**self).opt_full_qual() } fn opt_full_qual_given<'s, F: FnOnce() -> &'s mut Vec<u8>>( &'s self, owned_fn: F, ) -> Option<Cow<'s, [u8]>> { (**self).opt_full_qual_given(owned_fn) } fn num_qual_lines(&self) -> usize { (**self).num_qual_lines() } fn write<W: io::Write>(&self, writer: W) -> io::Result<()> { (**self).write(writer) } }
use memchr::memchr; use std::borrow::Cow; use std::io; use std::str; pub use crate::core::{QualRecordPosition, SeqRecordPosition}; pub trait BaseRecord { fn head(&self) -> &[u8]; fn seq(&self) -> &[u8]; fn full_seq(&self) -> Cow<[u8]>; fn full_seq_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]> where F: FnOnce() -> &'s mut Vec<u8>; fn num_seq_lines(&self) -> usize; fn has_quality(&self) -> bool; fn opt_qual(&self) -> Option<&[u8]>; fn opt_full_qual(&self) -> Option<Cow<[u8]>>; fn opt_full_qual_given<'s, F>(&'s self, owned_fn: F) -> Option<Cow<'s, [u8]>> where F: FnOnce() -> &'s mut Vec<u8>; fn num_qual_lines(&self) -> usize; fn write<W>(&self, writer: W) -> io::Result<()> where W: io::Write; #[inline] fn id_bytes(&self) -> &[u8] { let head = self.head(); if let Some(pos) = memchr(b' ', head) { return &head[..pos]; } head } #[inline] fn id(&self) -> Result<&str, str::Utf8Error> { str::from_utf8(self.id_bytes()) } #[inline] fn desc_bytes(&self) -> Option<&[u8]> { let head = self.head(); if let Some(pos) = memchr(b' ', head) { return Some(&head[pos + 1..]); } None } #[inline] fn desc(&self) -> Option<Result<&str, str::Utf8Error>> { self.desc_bytes().map(str::from_utf8) } #[inline] fn id_desc_bytes(&self) -> (&[u8], Option<&[u8]>) { let head = self.head(); if let Some(pos) = memchr(b' ', head) { return (&head[..pos], Some(&head[pos + 1..])); } (head, None) } #[inline] fn id_desc(&self) -> Result<(&str, Option<&str>), str::Utf8Error> { let (id, desc) = self.id_desc_bytes(); Ok((str::from_utf8(id)?, desc.map(str::from_utf8).transpose()?)) } } impl<'a, R> BaseRecord for &'a R where R: BaseRecord, { fn head(&self) -> &[u8] { (**self).head() } fn seq(&self) -> &[u8] { (**self).seq() } fn full_seq(&self) -> Cow<[u8]> { (**self).full_seq() } fn full_seq_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]> where F: FnOnce() -> &'s mut Vec<u8>, { (**self).full_seq_given(owned_fn) } fn num_seq_lines(&self) -> usize { (**self).num_seq_lines() } fn id_bytes(&self) -> &[u8] { (**self).id_bytes() } fn id(&self) -> Result<&str, std::str::Utf8Error> { (**self).id() } fn desc_bytes(&self) -> Option<&[u8]> { (**self).desc_bytes() } fn desc(&self) -> Option<Result<&str, std::str::Utf8Error>> { (**self).desc() } fn id_desc_bytes(&self) -> (&[u8], Option<&[u8]>) { (**self).id_desc_bytes() } fn id_desc(&self) -> Result<(&str, Option<&str>), std::str::Utf8Error> { (**self).id_desc() } fn has_quality(&self) -> bool { (**self).has_quality() } fn opt_qual(&self) -> Option<&[u8]> { (**self).opt_qual() } fn opt_full_qual(&self) -> Option<Cow<[u8]>> { (**self).opt_full_qual() }
fn num_qual_lines(&self) -> usize { (**self).num_qual_lines() } fn write<W: io::Write>(&self, writer: W) -> io::Result<()> { (**self).write(writer) } }
fn opt_full_qual_given<'s, F: FnOnce() -> &'s mut Vec<u8>>( &'s self, owned_fn: F, ) -> Option<Cow<'s, [u8]>> { (**self).opt_full_qual_given(owned_fn) }
function_block-full_function
[ { "content": "#[inline]\n\npub fn write_wrap<W, H>(mut writer: W, head: H, seq: &[u8], wrap: usize) -> io::Result<()>\n\nwhere\n\n W: io::Write,\n\n H: HeadWriter,\n\n{\n\n write_head(&mut writer, head)?;\n\n write_wrap_seq(writer, seq, wrap)\n\n}\n\n\n\n/// Writes data to the FASTA format. Wraps th...
Rust
examples/hashrocket-bench.rs
hobinjk/tokio-websocket
b54adc78740ce7caf442e54e906b0a41b6daf7a8
extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate websocket; extern crate serde_json; use serde_json::Value; use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use std::io::{Error, ErrorKind}; use tokio_core::net::TcpListener; use tokio_core::reactor::Core; use tokio_io::AsyncRead; use futures::{Future, Stream, Sink}; use futures::sync::mpsc; use websocket::{Request, WebSocketCodec, new_text_frame, Opcode, Frame}; const NULL_PAYLOAD: &'static Value = &Value::Null; enum Message { Echo(Frame), Broadcast(Frame, Frame), None(), } fn process_frame(frame: Frame) -> Message { if frame.header.opcode == Opcode::Close { return Message::Echo(frame); } if frame.header.opcode != Opcode::Text { return Message::None(); } let payload = frame.payload_string().unwrap(); if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(&payload) { if let Some(&Value::String(ref s)) = obj.get("type") { if s == "echo" { return Message::Echo(frame); } if s == "broadcast" { let msg = format!(r#"{{"type":"broadcastResult","payload":{}}}"#, obj.get("payload").unwrap_or(NULL_PAYLOAD)); return Message::Broadcast(frame, new_text_frame(&msg, None)); } } } Message::None() } fn main() { let addr = "0.0.0.0:8084".parse().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); let socket = TcpListener::bind(&addr, &handle).unwrap(); let connections = Rc::new(RefCell::new(HashMap::new())); let srv = socket.incoming().for_each(move |(conn, addr)| { let (sink, stream) = conn.framed(WebSocketCodec::new()).split(); let (tx, rx) = mpsc::unbounded(); connections.borrow_mut().insert(addr, tx); let connections_inner = connections.clone(); let reader = stream.for_each(move |req| { let mut conns = connections_inner.borrow_mut(); match req { Request::Frame(frame) => { match process_frame(frame) { Message::None() => {}, Message::Echo(frame) => { if frame.header.opcode == Opcode::Close { conns.remove(&addr); return Err(Error::new(ErrorKind::Other, "close requested")) } let tx = conns.get_mut(&addr).unwrap(); let masked_frame = new_text_frame(&frame.payload_string().unwrap(), None); mpsc::UnboundedSender::send(&mut std::borrow::BorrowMut::borrow_mut(tx), masked_frame).unwrap(); }, Message::Broadcast(broadcast_frame, echo_frame) => { let masked_frame = new_text_frame(&broadcast_frame.payload_string().unwrap(), None); for (&t_addr, tx) in conns.iter_mut() { mpsc::UnboundedSender::send(&mut std::borrow::BorrowMut::borrow_mut(tx), masked_frame.clone()).unwrap(); if addr == t_addr { mpsc::UnboundedSender::send(&mut std::borrow::BorrowMut::borrow_mut(tx), echo_frame.clone()).unwrap(); } } }, } }, Request::Open() => { let tx = conns.get_mut(&addr).unwrap(); mpsc::UnboundedSender::send(&mut std::borrow::BorrowMut::borrow_mut(tx), new_text_frame("this message is dropped", None)).unwrap(); } } Ok(()) }); let connections = connections.clone(); let writer = rx.map_err(|_| Error::new(ErrorKind::Other, "receiver error")).fold(sink, |sink, msg| { sink.send(msg) }); let reader = reader.map_err(|_| Error::new(ErrorKind::Other, "transmitter error")); let conn = reader.map(|_| ()).select(writer.map(|_| ())); handle.spawn(conn.then(move |_| { connections.borrow_mut().remove(&addr); Ok(()) })); Ok(()) }); core.run(srv).unwrap(); }
extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate websocket; extern crate serde_json; use serde_json::Value; use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use std::io::{Error, ErrorKind}; use tokio_core::net::TcpListener; use tokio_core::reactor::Core; use tokio_io::AsyncRead; use futures::{Future, Stream, Sink}; use futures::sync::mpsc; use websocket::{Request, WebSocketCodec, new_text_frame, Opcode, Frame}; const NULL_PAYLOAD: &'static Value = &Value::Null; enum Message { Echo(Frame), Broadcast(Frame, Frame), None(), } fn process_frame(frame: Frame) -> Message { if frame.header.opcode == Opcode::Close { return Message::Echo(frame); } if frame.header.opcode != Opcode::Text { return Message::None(); } let payload = frame.payload_string().unwrap(); if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(&pa
if frame.header.opcode == Opcode::Close { conns.remove(&addr); return Err(Error::new(ErrorKind::Other, "close requested")) } let tx = conns.get_mut(&addr).unwrap(); let masked_frame = new_text_frame(&frame.payload_string().unwrap(), None); mpsc::UnboundedSender::send(&mut std::borrow::BorrowMut::borrow_mut(tx), masked_frame).unwrap(); }, Message::Broadcast(broadcast_frame, echo_frame) => { let masked_frame = new_text_frame(&broadcast_frame.payload_string().unwrap(), None); for (&t_addr, tx) in conns.iter_mut() { mpsc::UnboundedSender::send(&mut std::borrow::BorrowMut::borrow_mut(tx), masked_frame.clone()).unwrap(); if addr == t_addr { mpsc::UnboundedSender::send(&mut std::borrow::BorrowMut::borrow_mut(tx), echo_frame.clone()).unwrap(); } } }, } }, Request::Open() => { let tx = conns.get_mut(&addr).unwrap(); mpsc::UnboundedSender::send(&mut std::borrow::BorrowMut::borrow_mut(tx), new_text_frame("this message is dropped", None)).unwrap(); } } Ok(()) }); let connections = connections.clone(); let writer = rx.map_err(|_| Error::new(ErrorKind::Other, "receiver error")).fold(sink, |sink, msg| { sink.send(msg) }); let reader = reader.map_err(|_| Error::new(ErrorKind::Other, "transmitter error")); let conn = reader.map(|_| ()).select(writer.map(|_| ())); handle.spawn(conn.then(move |_| { connections.borrow_mut().remove(&addr); Ok(()) })); Ok(()) }); core.run(srv).unwrap(); }
yload) { if let Some(&Value::String(ref s)) = obj.get("type") { if s == "echo" { return Message::Echo(frame); } if s == "broadcast" { let msg = format!(r#"{{"type":"broadcastResult","payload":{}}}"#, obj.get("payload").unwrap_or(NULL_PAYLOAD)); return Message::Broadcast(frame, new_text_frame(&msg, None)); } } } Message::None() } fn main() { let addr = "0.0.0.0:8084".parse().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); let socket = TcpListener::bind(&addr, &handle).unwrap(); let connections = Rc::new(RefCell::new(HashMap::new())); let srv = socket.incoming().for_each(move |(conn, addr)| { let (sink, stream) = conn.framed(WebSocketCodec::new()).split(); let (tx, rx) = mpsc::unbounded(); connections.borrow_mut().insert(addr, tx); let connections_inner = connections.clone(); let reader = stream.for_each(move |req| { let mut conns = connections_inner.borrow_mut(); match req { Request::Frame(frame) => { match process_frame(frame) { Message::None() => {}, Message::Echo(frame) => {
random
[ { "content": "pub fn opcode_to_u8(opcode: Opcode) -> u8 {\n\n match opcode {\n\n Opcode::Continuation => 0,\n\n Opcode::Text => 1,\n\n Opcode::Binary => 2,\n\n Opcode::Close => 8,\n\n Opcode::Ping => 9,\n\n Opcode::Pong => 10,\n\n }\n\n}\n\n\n", "file_path": "...
Rust
src/args.rs
JoshMcguigan/waysay
7d2744d8de03d5a261ea4905efe67584ec8f07d3
#[derive(Clone)] pub struct Args { pub message: String, pub buttons: Vec<ArgButton>, pub message_type: String, pub detailed_message: bool, pub detailed_message_contents: String, } #[derive(Clone)] pub struct ArgButton { pub text: String, pub action: String, } pub fn parse(args: impl Iterator<Item = String>) -> Result<Args, String> { let mut message = None; let mut message_type = None; let mut buttons = vec![]; let mut detailed_message = false; let mut args = args.skip(1); loop { match args.next().as_deref() { Some("-m") | Some("--message") => { let message_arg = args.next(); if message_arg.is_some() { message = message_arg; } else { return Err("missing required arg message (-m/--message)".into()); } } Some("-t") | Some("--type") => { let message_type_arg = args.next(); if message_type_arg.is_some() { message_type = message_type_arg; } else { return Err("missing required arg type (-t/--type)".into()); } } Some("-l") | Some("--detailed-message") => { detailed_message = true; } Some("-b") | Some("--button") | Some("-B") | Some("--button-no-terminal") => { let text = args.next(); let action = args.next(); match (text, action) { (Some(text), Some(action)) => buttons.push(ArgButton { text, action }), (None, _) => return Err("button missing text".into()), (Some(_), None) => return Err("button missing action".into()), } } Some(arg) => return Err(format!("invalid arg '{}'", arg)), None => break, } } if let Some(message) = message { Ok(Args { message, buttons, message_type: message_type.unwrap_or_else(|| "error".into()), detailed_message, detailed_message_contents: String::new(), }) } else { Err("missing required arg message (-m/--message)".into()) } } #[cfg(test)] mod tests { use super::parse; #[test] fn no_args() { let input = vec!["waysay".into()]; assert_eq!( "missing required arg message (-m/--message)", parse(input.into_iter()).err().unwrap(), ); } #[test] fn unsupported_arg() { let input = vec!["waysay".into(), "--not-a-real-thing".into()]; assert_eq!( "invalid arg '--not-a-real-thing'", parse(input.into_iter()).err().unwrap(), ); } #[test] fn message_short_flag() { let input = vec!["waysay".into(), "-m".into(), "hello from waysay".into()]; let args = parse(input.into_iter()).unwrap(); assert_eq!("hello from waysay", args.message,); } #[test] fn message_long_flag() { let input = vec![ "waysay".into(), "--message".into(), "hello from waysay".into(), ]; let args = parse(input.into_iter()).unwrap(); assert_eq!("hello from waysay", args.message,); } }
#[derive(Clone)] pub struct Args { pub message: String, pub buttons: Vec<ArgButton>, pub message_type: String, pub detailed_message: bool, pub detailed_message_contents: String, } #[derive(Clone)] pub struct ArgButton { pub text: String, pub action: String, } pub fn parse(args: impl Iterator<Item = String>) -> Result<Args, String> { let mut message = None; let mut message_type = None; let mut buttons = vec![]; let mut detailed_message = false; let mut args = args.skip(1); loop { match args.next().as_deref() { Some("-m") | Some("--message") => { let message_arg = args.next(); if message_arg.is_some() { message = message_arg; } else { return Err("missing required arg message (-m/--message)".into()); } } Some("-t") | Some("--type") => { let message_type_arg = args.next(); if message_type_arg.is_some() { message_type = message_type_arg; } else { return Err("missing required arg type (-t/--type)".into()); } } Some("-l") | Some("--detailed-message") => { detailed_message = true; } Some("-b") | Some("--button") | Some("-B") | Some("--button-no-terminal") => { let text = args.next(); let action = args.next(); match (text, action) { (Some(text), Some(action)) => buttons.push(ArgButton { text, action }), (None, _) => return Err("button missing text".into()), (Some(_), None) => return Err("button missing action".into()), } } Some(arg) => return Err(format!("invalid arg '{}'", arg)), None => break, } } if let Some(message) = message {
} else { Err("missing required arg message (-m/--message)".into()) } } #[cfg(test)] mod tests { use super::parse; #[test] fn no_args() { let input = vec!["waysay".into()]; assert_eq!( "missing required arg message (-m/--message)", parse(input.into_iter()).err().unwrap(), ); } #[test] fn unsupported_arg() { let input = vec!["waysay".into(), "--not-a-real-thing".into()]; assert_eq!( "invalid arg '--not-a-real-thing'", parse(input.into_iter()).err().unwrap(), ); } #[test] fn message_short_flag() { let input = vec!["waysay".into(), "-m".into(), "hello from waysay".into()]; let args = parse(input.into_iter()).unwrap(); assert_eq!("hello from waysay", args.message,); } #[test] fn message_long_flag() { let input = vec![ "waysay".into(), "--message".into(), "hello from waysay".into(), ]; let args = parse(input.into_iter()).unwrap(); assert_eq!("hello from waysay", args.message,); } }
Ok(Args { message, buttons, message_type: message_type.unwrap_or_else(|| "error".into()), detailed_message, detailed_message_contents: String::new(), })
call_expression
[ { "content": "struct Surface {\n\n args: Args,\n\n surface: wl_surface::WlSurface,\n\n layer_surface: Main<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>,\n\n next_render_event: Rc<Cell<Option<RenderEvent>>>,\n\n pools: DoubleMemPool,\n\n dimensions: (u32, u32),\n\n /// X, Y coordinates of curr...
Rust
src/application/engine.rs
hoangpq/crayon
f37a5e8c23b7c1d12583e585012960ab0ee922fb
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use crate::sched::prelude::LatchProbe; use crate::window::prelude::{Event, EventListener, EventListenerHandle, WindowEvent}; use super::lifecycle::LifecycleListener; use super::Params; type Result<T> = ::std::result::Result<T, ::failure::Error>; pub struct EngineSystem { events: EventListenerHandle, state: Arc<EngineState>, headless: bool, } struct EngineState { alive: AtomicBool, } impl EventListener for Arc<EngineState> { fn on(&mut self, v: &Event) -> Result<()> { if let Event::Window(WindowEvent::Closed) = *v { self.alive.store(false, Ordering::Relaxed); } Ok(()) } } impl Drop for EngineSystem { fn drop(&mut self) { crate::window::detach(self.events); unsafe { crate::res::discard(); crate::input::discard(); crate::video::discard(); crate::window::discard(); crate::sched::discard(); } } } impl EngineSystem { pub unsafe fn new(params: Params) -> Result<Self> { #[cfg(not(target_arch = "wasm32"))] crate::sched::setup(4, None, None); #[cfg(target_arch = "wasm32")] crate::sched::setup(0, None, None); crate::window::setup(params.window)?; crate::video::setup()?; crate::input::setup(params.input); crate::res::setup(params.res)?; let state = Arc::new(EngineState { alive: AtomicBool::new(true), }); let sys = EngineSystem { events: crate::window::attach(state.clone()), state, headless: false, }; Ok(sys) } pub unsafe fn new_headless(params: Params) -> Result<Self> { #[cfg(not(target_arch = "wasm32"))] crate::sched::setup(4, None, None); #[cfg(target_arch = "wasm32")] crate::sched::setup(0, None, None); crate::window::headless(); crate::video::headless(); crate::input::setup(params.input); crate::res::setup(params.res)?; let state = Arc::new(EngineState { alive: AtomicBool::new(false), }); let sys = EngineSystem { events: crate::window::attach(state.clone()), state, headless: true, }; Ok(sys) } #[inline] pub fn shutdown(&self) { self.state.alive.store(false, Ordering::Relaxed); } #[inline] pub fn headless(&self) -> bool { self.headless } pub fn run_oneshot(&self) -> Result<()> { super::foreach(|v| v.on_pre_update())?; super::foreach(|v| v.on_update())?; super::foreach(|v| v.on_render())?; super::foreach_rev(|v| v.on_post_update())?; Ok(()) } pub fn run<L, T, T2>(&self, latch: L, closure: T) -> Result<()> where L: LatchProbe + 'static, T: FnOnce() -> Result<T2> + 'static, T2: LifecycleListener + Send + 'static, { let state = self.state.clone(); let mut closure = Some(closure); super::sys::run_forever( move || { super::foreach(|v| v.on_pre_update())?; super::foreach_rev(|v| v.on_post_update())?; Ok(!latch.is_set()) }, move || { let mut v = None; std::mem::swap(&mut closure, &mut v); let application = crate::application::attach(v.unwrap()()?); let state = state.clone(); super::sys::run_forever( move || { super::foreach(|v| v.on_pre_update())?; super::foreach(|v| v.on_update())?; super::foreach(|v| v.on_render())?; super::foreach_rev(|v| v.on_post_update())?; Ok(state.alive.load(Ordering::Relaxed)) }, move || { unsafe { crate::sched::terminate() }; crate::application::detach(application); unsafe { super::late_discard() }; Ok(()) }, )?; Ok(()) }, )?; Ok(()) } }
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use crate::sched::prelude::LatchProbe; use crate::window::prelude::{Event, EventListener, EventListenerHandle, WindowEvent}; use super::lifecycle::LifecycleListener; use super::Params; type Result<T> = ::std::result::Result<T, ::failure::Error>; pub struct EngineSystem { events: EventListenerHandle, state: Arc<EngineState>, headless: bool, } struct EngineState { alive: AtomicBool, } impl EventListener for Arc<EngineState> { fn on(&mut self, v: &Event) -> Result<()> { if let Event::Window(WindowEvent::Closed) = *v { self.alive.store(false, Ordering::Relaxed); } Ok(()) } } impl Drop for EngineSystem { fn drop(&mut self) { crate::window::detach(self.events); unsafe { crate::res::discard(); crate::input::discard(); crate::video::discard(); crate::window::discard(); crate::sched::discard(); } } } impl EngineSystem { pub unsafe fn new(params: Params) -> Result<Self> { #[cfg(not(target_arch = "wasm32"))] crate::sched::setup(4, None, None); #[cfg(target_arch = "wasm32")] crate::sched::setup(0, None, None); crate::window::setup(params.window)?; crate::video::setup()?; crate::input::setup(params.input); crate::res::setup(params.res)?; let state = Arc::new(EngineState { alive: AtomicBool::new(true), }); let sys = EngineSystem { events: crate::window::attach(state.clone()), state, headless: false, }; Ok(sys) }
#[inline] pub fn shutdown(&self) { self.state.alive.store(false, Ordering::Relaxed); } #[inline] pub fn headless(&self) -> bool { self.headless } pub fn run_oneshot(&self) -> Result<()> { super::foreach(|v| v.on_pre_update())?; super::foreach(|v| v.on_update())?; super::foreach(|v| v.on_render())?; super::foreach_rev(|v| v.on_post_update())?; Ok(()) } pub fn run<L, T, T2>(&self, latch: L, closure: T) -> Result<()> where L: LatchProbe + 'static, T: FnOnce() -> Result<T2> + 'static, T2: LifecycleListener + Send + 'static, { let state = self.state.clone(); let mut closure = Some(closure); super::sys::run_forever( move || { super::foreach(|v| v.on_pre_update())?; super::foreach_rev(|v| v.on_post_update())?; Ok(!latch.is_set()) }, move || { let mut v = None; std::mem::swap(&mut closure, &mut v); let application = crate::application::attach(v.unwrap()()?); let state = state.clone(); super::sys::run_forever( move || { super::foreach(|v| v.on_pre_update())?; super::foreach(|v| v.on_update())?; super::foreach(|v| v.on_render())?; super::foreach_rev(|v| v.on_post_update())?; Ok(state.alive.load(Ordering::Relaxed)) }, move || { unsafe { crate::sched::terminate() }; crate::application::detach(application); unsafe { super::late_discard() }; Ok(()) }, )?; Ok(()) }, )?; Ok(()) } }
pub unsafe fn new_headless(params: Params) -> Result<Self> { #[cfg(not(target_arch = "wasm32"))] crate::sched::setup(4, None, None); #[cfg(target_arch = "wasm32")] crate::sched::setup(0, None, None); crate::window::headless(); crate::video::headless(); crate::input::setup(params.input); crate::res::setup(params.res)?; let state = Arc::new(EngineState { alive: AtomicBool::new(false), }); let sys = EngineSystem { events: crate::window::attach(state.clone()), state, headless: true, }; Ok(sys) }
function_block-full_function
[ { "content": "#[inline]\n\npub fn headless() -> bool {\n\n ctx().headless()\n\n}\n\n\n", "file_path": "src/application/mod.rs", "rank": 0, "score": 275338.7219091743 }, { "content": "#[inline]\n\npub fn create_surface(params: SurfaceParams) -> Result<SurfaceHandle> {\n\n ctx().create_s...
Rust
src/tests.rs
korken89/lbfgs-rs
a7a58926622da66c1893cc3cff22999226983528
use crate::*; #[test] #[should_panic] fn lbfgs_panic_zero_n() { let mut _e = Lbfgs::new(0, 1); } #[test] #[should_panic] fn lbfgs_panic_zero_mem() { let mut _e = Lbfgs::new(1, 0); } #[test] #[should_panic] fn lbfgs_panic_apply_size_grad() { let mut e = Lbfgs::new(5, 5); e.update_hessian(&[0.0; 4], &[0.0; 5]); } #[test] #[should_panic] fn lbfgs_panic_apply_state() { let mut e = Lbfgs::new(5, 5); e.update_hessian(&[0.0; 5], &[0.0; 4]); } #[test] #[should_panic] fn lbfgs_panic_cbfgs_alpha() { let mut _e = Lbfgs::new(5, 5).with_cbfgs_alpha(-1.0); } #[test] #[should_panic] fn lbfgs_panic_cbfgs_epsilon() { let mut _e = Lbfgs::new(5, 5).with_cbfgs_epsilon(-1.0); } #[test] fn lbfgs_buffer_storage() { let mut e = Lbfgs::new(2, 3); e.update_hessian(&[1.0, 1.0], &[1.5, 1.5]); assert_eq!(e.active_size, 0); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[2.0, 2.0], &[2.5, 2.5]) ); assert_eq!(e.active_size, 1); assert_eq!(&e.s[0], &[1.0, 1.0]); assert_eq!(&e.y[0], &[1.0, 1.0]); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-3.0, -3.0], &[-3.5, -3.5]) ); assert_eq!(e.active_size, 2); assert_eq!(&e.s[0], &[-6.0, -6.0]); assert_eq!(&e.s[1], &[1.0, 1.0]); assert_eq!(&e.y[0], &[-5.0, -5.0]); assert_eq!(&e.y[1], &[1.0, 1.0]); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-4.0, -4.0], &[-4.5, -4.5]) ); assert_eq!(e.active_size, 3); assert_eq!(&e.s[0], &[-1.0, -1.0]); assert_eq!(&e.s[1], &[-6.0, -6.0]); assert_eq!(&e.s[2], &[1.0, 1.0]); assert_eq!(&e.y[0], &[-1.0, -1.0]); assert_eq!(&e.y[1], &[-5.0, -5.0]); assert_eq!(&e.y[2], &[1.0, 1.0]); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[5.0, 5.0], &[5.5, 5.5]) ); assert_eq!(e.active_size, 3); assert_eq!(&e.s[0], &[10.0, 10.0]); assert_eq!(&e.s[1], &[-1.0, -1.0]); assert_eq!(&e.s[2], &[-6.0, -6.0]); assert_eq!(&e.y[0], &[9.0, 9.0]); assert_eq!(&e.y[1], &[-1.0, -1.0]); assert_eq!(&e.y[2], &[-5.0, -5.0]); } #[test] fn lbfgs_apply_finite() { let mut e = Lbfgs::new(2, 3); e.update_hessian(&[1.0, 1.0], &[1.5, 1.5]); let mut g = [1.0, 1.0]; e.apply_hessian(&mut g); unit_test_utils::assert_is_finite_array(&g, "g"); } #[test] fn correctneess_buff_empty() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); e.apply_hessian(&mut g); let correct_dir = [-3.1, 1.5, 2.1]; unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); } #[test] fn correctneess_buff_1() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); e.apply_hessian(&mut g); let correct_dir = [-1.100601247872944, -0.086568349404424, 0.948633011911515]; let alpha_correct = -1.488372093023256; let rho_correct = 2.325581395348837; unit_test_utils::assert_nearly_equal(alpha_correct, e.alpha[0], 1e-8, 1e-10, "alpha"); unit_test_utils::assert_nearly_equal(rho_correct, e.rho[0], 1e-8, 1e-10, "rho"); unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); } #[test] fn correctneess_buff_2() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.75, 0.9, -1.9], &[0.19, 0.19, -0.44]) ); e.apply_hessian(&mut g); let correct_dir = [-1.814749861477524, 0.895232314736337, 1.871795942557546]; unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); } #[test] fn correctneess_buff_overfull() { let mut e = Lbfgs::new(3, 3); let mut g = [-2.0, 0.2, -0.3]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::Rejection, e.update_hessian( &[-0.5, 0.6, -1.2], &[0.419058177461747, 0.869843029576958, 0.260313940846084] ) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.75, 0.9, -1.9], &[0.19, 0.19, -0.44]) ); for _i in 1..10 { assert_eq!( UpdateStatus::Rejection, e.update_hessian( &[1., 2., 3.], &[-0.534522483824849, 0.774541920588438, -0.338187119117343] ) ); } assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-2.25, 3.5, -3.1], &[0.39, 0.39, -0.84]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-3.75, 6.3, -4.3], &[0.49, 0.59, -1.24]) ); e.apply_hessian(&mut g); println!("{:#.3?}", e); let gamma_correct = 0.077189939288812; let alpha_correct = [-0.044943820224719, -0.295345104333868, -1.899418829910887]; let rho_correct = [1.123595505617978, 1.428571428571429, 13.793103448275861]; let dir_correct = [-0.933604237447365, -0.078865807539102, 1.016318412551302]; unit_test_utils::assert_nearly_equal(gamma_correct, e.gamma, 1e-8, 1e-10, "gamma"); unit_test_utils::assert_nearly_equal_array(&alpha_correct, &e.alpha, 1e-8, 1e-10, "alpha"); unit_test_utils::assert_nearly_equal_array(&rho_correct, &e.rho[0..3], 1e-8, 1e-10, "rho"); unit_test_utils::assert_nearly_equal_array(&dir_correct, &g, 1e-8, 1e-10, "direction"); } #[test] fn correctneess_reset() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); e.apply_hessian(&mut g); let correct_dir = [-1.100601247872944, -0.086568349404424, 0.948633011911515]; let alpha_correct = -1.488372093023256; let rho_correct = 2.325581395348837; unit_test_utils::assert_nearly_equal(alpha_correct, e.alpha[0], 1e-8, 1e-10, "alpha"); unit_test_utils::assert_nearly_equal(rho_correct, e.rho[0], 1e-8, 1e-10, "rho"); unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); e.reset(); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); e.apply_hessian(&mut g); unit_test_utils::assert_nearly_equal(alpha_correct, e.alpha[0], 1e-8, 1e-10, "alpha"); unit_test_utils::assert_nearly_equal(rho_correct, e.rho[0], 1e-8, 1e-10, "rho"); unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); } #[test] fn reject_perpendicular_sy() { let n = 3; let mem = 5; let mut lbfgs = Lbfgs::new(n, mem).with_sy_epsilon(1e-8); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!(0, lbfgs.active_size); assert_eq!( UpdateStatus::Rejection, lbfgs.update_hessian( &[-0.5, 0.6, -1.2], &[0.419058177461747, 0.869843029576958, 0.260313940846084] ) ); assert_eq!(0, lbfgs.active_size); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); assert_eq!(1, lbfgs.active_size); assert_eq!( UpdateStatus::Rejection, lbfgs.update_hessian(&[1.1, 2., 3.], &[-0.5, 0.7, -0.3]) ); assert_eq!(1, lbfgs.active_size); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[-0.75, 0.9, -1.9], &[0.19, 0.19, -0.44]) ); assert_eq!(2, lbfgs.active_size); } #[test] fn reject_norm_s_zero() { let n = 3; let mem = 5; let mut lbfgs = Lbfgs::new(n, mem); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[1.0, 2.0, -1.0], &[5.0, 5.0, 5.0]) ); assert_eq!( UpdateStatus::Rejection, lbfgs.update_hessian( &[ 1.0 + std::f64::MIN_POSITIVE, 2.0 + std::f64::MIN_POSITIVE, -1.0 + std::f64::MIN_POSITIVE ], &[5.0, 5.0, 5.0] ) ); } #[test] fn reject_cfbs_condition() { let n = 3; let mem = 5; let mut lbfgs = Lbfgs::new(n, mem) .with_sy_epsilon(1e-8) .with_cbfgs_alpha(1.0) .with_cbfgs_epsilon(1e-4); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::Rejection, lbfgs.update_hessian(&[-0.838, 0.260, 0.479], &[-0.5, 0.6, -1.2]) ); }
use crate::*; #[test] #[should_panic] fn lbfgs_panic_zero_n() { let mut _e = Lbfgs::new(0, 1); } #[test] #[should_panic] fn lbfgs_panic_zero_mem() { let mut _e = Lbfgs::new(1, 0); } #[test] #[should_panic] fn lbfgs_panic_apply_size_grad() { let mut e = Lbfgs::new(5, 5); e.update_hessian(&[0.0; 4], &[0.0; 5]); } #[test] #[should_panic] fn lbfgs_panic_apply_state() { let mut e = Lbfgs::new(5, 5); e.update_hessian(&[0.0; 5], &[0.0; 4]); } #[test] #[should_panic] fn lbfgs_panic_cbfgs_alpha() { let mut _e = Lbfgs::new(5, 5).with_cbfgs_alpha(-1.0); } #[test] #[should_panic] fn lbfgs_panic_cbfgs_epsilon() { let mut _e = Lbfgs::new(5, 5).with_cbfgs_epsilon(-1.0); } #[test] fn lbfgs_buffer_storage() { let mut e = Lbfgs::new(2, 3); e.update_hessian(&[1.0, 1.0], &[1.5, 1.5]); assert_eq!(e.active_size, 0); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[2.0, 2.0], &[2.5, 2.5]) ); assert_eq!(e.active_size, 1); assert_eq!(&e.s[0], &[1.0, 1.0]); assert_eq!(&e.y[0], &[1.0, 1.0]); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-3.0, -3.0], &[-3.5, -3.5]) ); assert_eq!(e.active_size, 2); assert_eq!(&e.s[0], &[-6.0, -6.0]); assert_eq!(&e.s[1], &[1.0, 1.0]); assert_eq!(&e.y[0], &[-5.0, -5.0]); assert_eq!(&e.y[1], &[1.0, 1.0]); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-4.0, -4.0], &[-4.5, -4.5]) ); assert_eq!(e.active_size, 3); assert_eq!(&e.s[0], &[-1.0, -1.0]); assert_eq!(&e.s[1], &[-6.0, -6.0]); assert_eq!(&e.s[2], &[1.0, 1.0]); assert_eq!(&e.y[0], &[-1.0, -1.0]); assert_eq!(&e.y[1], &[-5.0, -5.0]); assert_eq!(&e.y[2], &[1.0, 1.0]); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[5.0, 5.0], &[5.5, 5.5]) ); assert_eq!(e.active_size, 3); assert_eq!(&e.s[0], &[10.0, 10.0]); assert_eq!(&e.s[1], &[-1.0, -1.0]); assert_eq!(&e.s[2], &[-6.0, -6.0]); assert_eq!(&e.y[0], &[9.0, 9.0]); assert_eq!(&e.y[1], &[-1.0, -1.0]); assert_eq!(&e.y[2], &[-5.0, -5.0]); } #[test] fn lbfgs_apply_finite() { let mut e = Lbfgs::new(2, 3); e.update_hessian(&[1.0, 1.0], &[1.5, 1.5]); let mut g = [1.0, 1.0]; e.apply_hessian(&mut g); unit_test_utils::assert_is_finite_array(&g, "g"); } #[test] fn correctneess_buff_empty() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); e.apply_hessian(&mut g); let correct_dir = [-3.1, 1.5, 2.1]; unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); } #[test] fn correctneess_buff_1() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); e.apply_hessian(&mut g); let correct_dir = [-1.100601247872944, -0.086568349404424, 0.948633011911515]; let alpha_correct = -1.488372093023256; let rho_correct = 2.325581395348837; unit_test_utils::assert_nearly_equal(alpha_correct, e.alpha[0], 1e-8, 1e-10, "alpha"); unit_test_utils::assert_nearly_equal(rho_correct, e.rho[0], 1e-8, 1e-10, "rho"); unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); } #[test] fn correctneess_buff_2() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.75, 0.9, -1.9], &[0.19, 0.19, -0.44]) ); e.apply_hessian(&mut g); let correct_dir = [-1.814749861477524, 0.895232314736337, 1.871795942557546]; unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); } #[test] fn correctneess_buff_overfull() { let mut e = Lbfgs::new(3, 3); let mut g = [-2.0, 0.2, -0.3]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::Rejection, e.update_hessian( &[-0.5, 0.6, -1.2], &[0.419058177461747, 0.869843029576958, 0.260313940846084] ) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.75, 0.9, -1.9], &[0.19, 0.19, -0.44]) ); for _i in 1..10 { assert_eq!( UpdateStatus::Rejection, e.update_hessian( &[1., 2., 3.], &[-0.534522483824849, 0.774541920588438, -0.338187119117343] ) ); } assert_
#[test] fn correctneess_reset() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); e.apply_hessian(&mut g); let correct_dir = [-1.100601247872944, -0.086568349404424, 0.948633011911515]; let alpha_correct = -1.488372093023256; let rho_correct = 2.325581395348837; unit_test_utils::assert_nearly_equal(alpha_correct, e.alpha[0], 1e-8, 1e-10, "alpha"); unit_test_utils::assert_nearly_equal(rho_correct, e.rho[0], 1e-8, 1e-10, "rho"); unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); e.reset(); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); e.apply_hessian(&mut g); unit_test_utils::assert_nearly_equal(alpha_correct, e.alpha[0], 1e-8, 1e-10, "alpha"); unit_test_utils::assert_nearly_equal(rho_correct, e.rho[0], 1e-8, 1e-10, "rho"); unit_test_utils::assert_nearly_equal_array(&correct_dir, &g, 1e-8, 1e-10, "direction"); } #[test] fn reject_perpendicular_sy() { let n = 3; let mem = 5; let mut lbfgs = Lbfgs::new(n, mem).with_sy_epsilon(1e-8); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!(0, lbfgs.active_size); assert_eq!( UpdateStatus::Rejection, lbfgs.update_hessian( &[-0.5, 0.6, -1.2], &[0.419058177461747, 0.869843029576958, 0.260313940846084] ) ); assert_eq!(0, lbfgs.active_size); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[-0.5, 0.6, -1.2], &[0.1, 0.2, -0.3]) ); assert_eq!(1, lbfgs.active_size); assert_eq!( UpdateStatus::Rejection, lbfgs.update_hessian(&[1.1, 2., 3.], &[-0.5, 0.7, -0.3]) ); assert_eq!(1, lbfgs.active_size); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[-0.75, 0.9, -1.9], &[0.19, 0.19, -0.44]) ); assert_eq!(2, lbfgs.active_size); } #[test] fn reject_norm_s_zero() { let n = 3; let mem = 5; let mut lbfgs = Lbfgs::new(n, mem); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[1.0, 2.0, -1.0], &[5.0, 5.0, 5.0]) ); assert_eq!( UpdateStatus::Rejection, lbfgs.update_hessian( &[ 1.0 + std::f64::MIN_POSITIVE, 2.0 + std::f64::MIN_POSITIVE, -1.0 + std::f64::MIN_POSITIVE ], &[5.0, 5.0, 5.0] ) ); } #[test] fn reject_cfbs_condition() { let n = 3; let mem = 5; let mut lbfgs = Lbfgs::new(n, mem) .with_sy_epsilon(1e-8) .with_cbfgs_alpha(1.0) .with_cbfgs_epsilon(1e-4); assert_eq!( UpdateStatus::UpdateOk, lbfgs.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::Rejection, lbfgs.update_hessian(&[-0.838, 0.260, 0.479], &[-0.5, 0.6, -1.2]) ); }
eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-2.25, 3.5, -3.1], &[0.39, 0.39, -0.84]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-3.75, 6.3, -4.3], &[0.49, 0.59, -1.24]) ); e.apply_hessian(&mut g); println!("{:#.3?}", e); let gamma_correct = 0.077189939288812; let alpha_correct = [-0.044943820224719, -0.295345104333868, -1.899418829910887]; let rho_correct = [1.123595505617978, 1.428571428571429, 13.793103448275861]; let dir_correct = [-0.933604237447365, -0.078865807539102, 1.016318412551302]; unit_test_utils::assert_nearly_equal(gamma_correct, e.gamma, 1e-8, 1e-10, "gamma"); unit_test_utils::assert_nearly_equal_array(&alpha_correct, &e.alpha, 1e-8, 1e-10, "alpha"); unit_test_utils::assert_nearly_equal_array(&rho_correct, &e.rho[0..3], 1e-8, 1e-10, "rho"); unit_test_utils::assert_nearly_equal_array(&dir_correct, &g, 1e-8, 1e-10, "direction"); }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn scalar_mult<T>(a: &mut [T], s: T)\n\nwhere\n\n T: Float,\n\n{\n\n a.iter_mut().for_each(|out| *out = s * (*out));\n\n}\n\n\n\n/// Calculates out = out + s * a\n", "file_path": "src/vec_ops.rs", "rank": 8, "score": 39979.04309943656 }, { "content": "#[i...
Rust
src/iam.rs
NathanHowell/google-cloud-storage-rs
f599aa4009c9475225ba1a6fbcd2961836992e69
use crate::google::iam::v1::{Policy, TestIamPermissionsResponse}; use crate::google::storage::v1::{ GetIamPolicyRequest, SetIamPolicyRequest, TestIamPermissionsRequest, }; use crate::query::{PushIf, Query}; use crate::request::Request; use crate::urls::Urls; use crate::{Client, Result}; use reqwest::Method; use std::fmt::Debug; use url::Url; fn iam_url<'a, R, F>(base_url: Url, iam_request: Option<&'a R>, resource: F) -> Result<Url> where F: FnOnce(&'a R) -> &'a str, { let request = iam_request.ok_or(crate::Error::Other { source: "Expected iam_request field".into(), #[cfg(feature = "backtrace")] backtrace: std::backtrace::Backtrace::capture(), })?; let resource = resource(request); base_url.bucket(resource)?.join_segment("iam") } impl Query for GetIamPolicyRequest { fn request_query(&mut self) -> Vec<(&'static str, String)> { let mut query = self.common_request_params.take().request_query(); let mut requested_policy_version = self .iam_request .take() .and_then(|r| r.options) .map(|o| o.requested_policy_version); query.push_if_opt( "optionsRequestedPolicyVersion", &mut requested_policy_version, ); query } } impl Request for GetIamPolicyRequest { const REQUEST_METHOD: Method = Method::GET; type Response = Policy; fn request_path(&self, base_url: Url) -> Result<Url> { iam_url(base_url, self.iam_request.as_ref(), |r| &r.resource) } } impl Query for SetIamPolicyRequest { fn request_query(&mut self) -> Vec<(&'static str, String)> { self.common_request_params.take().request_query() } } impl Request for SetIamPolicyRequest { const REQUEST_METHOD: Method = Method::PUT; type Response = Policy; fn scope(&self) -> &'static str { crate::request::Scope::FULL_CONTROL } fn request_path(&self, base_url: Url) -> Result<Url> { iam_url(base_url, self.iam_request.as_ref(), |r| &r.resource) } } impl Query for TestIamPermissionsRequest { fn request_query(&mut self) -> Vec<(&'static str, String)> { let mut query = self.common_request_params.take().request_query(); query.extend( self.iam_request .take() .into_iter() .flat_map(|request| request.permissions) .map(|v| ("permissions", v)) .collect::<Vec<_>>(), ); query } } impl Request for TestIamPermissionsRequest { const REQUEST_METHOD: Method = Method::GET; type Response = TestIamPermissionsResponse; fn request_path(&self, base_url: Url) -> Result<Url> { Ok( iam_url(base_url, self.iam_request.as_ref(), |r| &r.resource)? .join("testPermissions")?, ) } } impl Client { #[doc = " Gets the IAM policy for the specified bucket."] #[tracing::instrument] pub async fn get_bucket_iam_policy( &self, request: impl Into<GetIamPolicyRequest> + Debug, ) -> crate::Result<Policy> { let request = request.into(); self.invoke(request).await } #[doc = " Updates an IAM policy for the specified bucket."] #[tracing::instrument] pub async fn set_bucket_iam_policy( &self, request: impl Into<SetIamPolicyRequest> + Debug, ) -> crate::Result<Policy> { let mut request = request.into(); let policy = request.iam_request.take().and_then(|r| r.policy); self.invoke_json(request, policy).await } #[doc = " Tests a set of permissions on the given bucket to see which, if"] #[doc = " any, are held by the caller."] #[tracing::instrument] pub async fn test_bucket_iam_permissions( &self, request: impl Into<TestIamPermissionsRequest> + Debug, ) -> crate::Result<TestIamPermissionsResponse> { let request = request.into(); self.invoke(request).await } }
use crate::google::iam::v1::{Policy, TestIamPermissionsResponse}; use crate::google::storage::v1::{ GetIamPolicyRequest, SetIamPolicyRequest, TestIamPermissionsRequest, }; use crate::query::{PushIf, Query}; use crate::request::Request; use crate::urls::Urls; use crate::{Client, Result}; use reqwest::Method; use std::fmt::Debug; use url::Url; fn iam_url<'a, R, F>(base_url: Url, iam_request: Option<&'a R>, resource: F) -> Result<Url> where F: FnOnce(&'a R) -> &'a str, { let request = iam_request.ok_or(crate::Error::Other { source: "Expected iam_request field".into(), #[cfg(feature = "backtrace")] backtrace: std::backtrace::Backtrace::capture(), })?; let resource = resource(request); base_url.bucket(resource)?.join_segment("iam") } impl Query for GetIamPolicyRequest { fn request_query(&mut self) -> Vec<(&'static str, String)> { let mut query = self.common_request_params.tak
} impl Request for GetIamPolicyRequest { const REQUEST_METHOD: Method = Method::GET; type Response = Policy; fn request_path(&self, base_url: Url) -> Result<Url> { iam_url(base_url, self.iam_request.as_ref(), |r| &r.resource) } } impl Query for SetIamPolicyRequest { fn request_query(&mut self) -> Vec<(&'static str, String)> { self.common_request_params.take().request_query() } } impl Request for SetIamPolicyRequest { const REQUEST_METHOD: Method = Method::PUT; type Response = Policy; fn scope(&self) -> &'static str { crate::request::Scope::FULL_CONTROL } fn request_path(&self, base_url: Url) -> Result<Url> { iam_url(base_url, self.iam_request.as_ref(), |r| &r.resource) } } impl Query for TestIamPermissionsRequest { fn request_query(&mut self) -> Vec<(&'static str, String)> { let mut query = self.common_request_params.take().request_query(); query.extend( self.iam_request .take() .into_iter() .flat_map(|request| request.permissions) .map(|v| ("permissions", v)) .collect::<Vec<_>>(), ); query } } impl Request for TestIamPermissionsRequest { const REQUEST_METHOD: Method = Method::GET; type Response = TestIamPermissionsResponse; fn request_path(&self, base_url: Url) -> Result<Url> { Ok( iam_url(base_url, self.iam_request.as_ref(), |r| &r.resource)? .join("testPermissions")?, ) } } impl Client { #[doc = " Gets the IAM policy for the specified bucket."] #[tracing::instrument] pub async fn get_bucket_iam_policy( &self, request: impl Into<GetIamPolicyRequest> + Debug, ) -> crate::Result<Policy> { let request = request.into(); self.invoke(request).await } #[doc = " Updates an IAM policy for the specified bucket."] #[tracing::instrument] pub async fn set_bucket_iam_policy( &self, request: impl Into<SetIamPolicyRequest> + Debug, ) -> crate::Result<Policy> { let mut request = request.into(); let policy = request.iam_request.take().and_then(|r| r.policy); self.invoke_json(request, policy).await } #[doc = " Tests a set of permissions on the given bucket to see which, if"] #[doc = " any, are held by the caller."] #[tracing::instrument] pub async fn test_bucket_iam_permissions( &self, request: impl Into<TestIamPermissionsRequest> + Debug, ) -> crate::Result<TestIamPermissionsResponse> { let request = request.into(); self.invoke(request).await } }
e().request_query(); let mut requested_policy_version = self .iam_request .take() .and_then(|r| r.options) .map(|o| o.requested_policy_version); query.push_if_opt( "optionsRequestedPolicyVersion", &mut requested_policy_version, ); query }
function_block-function_prefixed
[ { "content": "fn acl_url(base_url: Url, bucket: &str, object: &str) -> Result<Url> {\n\n base_url.bucket(bucket)?.object(object)?.join_segment(\"acl\")\n\n}\n\n\n\nimpl Query for InsertObjectAccessControlRequest {\n\n fn request_query(&mut self) -> Vec<(&'static str, String)> {\n\n let mut query = ...
Rust
sdk/guardduty/src/lens.rs
eduardomourar/aws-sdk-rust
58569c863afbe7bc442da8254df6c3970111de38
pub(crate) fn reflens_structure_crate_output_get_usage_statistics_output_next_token( input: &crate::output::GetUsageStatisticsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_detectors_output_next_token( input: &crate::output::ListDetectorsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_filters_output_next_token( input: &crate::output::ListFiltersOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_findings_output_next_token( input: &crate::output::ListFindingsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_invitations_output_next_token( input: &crate::output::ListInvitationsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_ip_sets_output_next_token( input: &crate::output::ListIpSetsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_members_output_next_token( input: &crate::output::ListMembersOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_organization_admin_accounts_output_next_token( input: &crate::output::ListOrganizationAdminAccountsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_publishing_destinations_output_next_token( input: &crate::output::ListPublishingDestinationsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_threat_intel_sets_output_next_token( input: &crate::output::ListThreatIntelSetsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_detectors_output_detector_ids( input: crate::output::ListDetectorsOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.detector_ids { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_filters_output_filter_names( input: crate::output::ListFiltersOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.filter_names { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_findings_output_finding_ids( input: crate::output::ListFindingsOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.finding_ids { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_invitations_output_invitations( input: crate::output::ListInvitationsOutput, ) -> std::option::Option<std::vec::Vec<crate::model::Invitation>> { let input = match input.invitations { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_ip_sets_output_ip_set_ids( input: crate::output::ListIpSetsOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.ip_set_ids { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_members_output_members( input: crate::output::ListMembersOutput, ) -> std::option::Option<std::vec::Vec<crate::model::Member>> { let input = match input.members { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_organization_admin_accounts_output_admin_accounts( input: crate::output::ListOrganizationAdminAccountsOutput, ) -> std::option::Option<std::vec::Vec<crate::model::AdminAccount>> { let input = match input.admin_accounts { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_threat_intel_sets_output_threat_intel_set_ids( input: crate::output::ListThreatIntelSetsOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.threat_intel_set_ids { None => return None, Some(t) => t, }; Some(input) }
pub(crate) fn reflens_structure_crate_output_get_usage_statistics_output_next_token( input: &crate::output::GetUsageStatisticsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_detectors_output_next_token( input: &crate::output::ListDetectorsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_filters_output_next_token( input: &crate::output::ListFiltersOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_findings_output_next_token( input: &crate::output::ListFindingsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_invitations_output_next_token( input: &crate::output::ListInvitationsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_ip_sets_output_next_token( input: &crate::output::ListIpSetsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) }
pub(crate) fn reflens_structure_crate_output_list_organization_admin_accounts_output_next_token( input: &crate::output::ListOrganizationAdminAccountsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_publishing_destinations_output_next_token( input: &crate::output::ListPublishingDestinationsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_threat_intel_sets_output_next_token( input: &crate::output::ListThreatIntelSetsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_detectors_output_detector_ids( input: crate::output::ListDetectorsOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.detector_ids { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_filters_output_filter_names( input: crate::output::ListFiltersOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.filter_names { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_findings_output_finding_ids( input: crate::output::ListFindingsOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.finding_ids { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_invitations_output_invitations( input: crate::output::ListInvitationsOutput, ) -> std::option::Option<std::vec::Vec<crate::model::Invitation>> { let input = match input.invitations { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_ip_sets_output_ip_set_ids( input: crate::output::ListIpSetsOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.ip_set_ids { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_members_output_members( input: crate::output::ListMembersOutput, ) -> std::option::Option<std::vec::Vec<crate::model::Member>> { let input = match input.members { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_organization_admin_accounts_output_admin_accounts( input: crate::output::ListOrganizationAdminAccountsOutput, ) -> std::option::Option<std::vec::Vec<crate::model::AdminAccount>> { let input = match input.admin_accounts { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_threat_intel_sets_output_threat_intel_set_ids( input: crate::output::ListThreatIntelSetsOutput, ) -> std::option::Option<std::vec::Vec<std::string::String>> { let input = match input.threat_intel_set_ids { None => return None, Some(t) => t, }; Some(input) }
pub(crate) fn reflens_structure_crate_output_list_members_output_next_token( input: &crate::output::ListMembersOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) }
function_block-function_prefix_line
[]
Rust
semantics/src/traversal/functions.rs
vaporydev/fe
246b23bad148e358ea04b80ca9e4e7a5ce4cec8d
use crate::errors::SemanticError; use crate::namespace::scopes::{ BlockScope, BlockScopeType, ContractDef, ContractScope, Scope, Shared, }; use crate::namespace::types::{ Base, FixedSize, Tuple, Type, }; use crate::traversal::_utils::spanned_expression; use crate::traversal::{ assignments, declarations, expressions, types, }; use crate::{ Context, FunctionAttributes, }; use fe_parser::ast as fe; use fe_parser::span::Spanned; use std::rc::Rc; pub fn func_def( contract_scope: Shared<ContractScope>, context: Shared<Context>, def: &Spanned<fe::ContractStmt>, ) -> Result<(), SemanticError> { if let fe::ContractStmt::FuncDef { qual, name, args, return_type, body, } = &def.node { let function_scope = BlockScope::from_contract_scope(def.span, Rc::clone(&contract_scope)); let name = name.node.to_string(); let param_types = args .iter() .map(|arg| func_def_arg(Rc::clone(&function_scope), arg)) .collect::<Result<Vec<_>, _>>()?; let return_type = return_type .as_ref() .map(|typ| types::type_desc_fixed_size(Scope::Block(Rc::clone(&function_scope)), &typ)) .transpose()? .unwrap_or_else(|| Tuple::empty().to_fixed_size()); if !return_type.is_empty_tuple() { validate_all_paths_return_or_revert(&body)? } let is_public = qual.is_some(); contract_scope.borrow_mut().add_function( name.clone(), is_public, param_types.clone(), return_type.clone(), ); let attributes = FunctionAttributes { name, param_types, return_type, }; context.borrow_mut().add_function(def, attributes); traverse_statements(function_scope, context, body)?; return Ok(()); } unreachable!() } fn traverse_statements( scope: Shared<BlockScope>, context: Shared<Context>, body: &[Spanned<fe::FuncStmt>], ) -> Result<(), SemanticError> { for stmt in body.iter() { func_stmt(Rc::clone(&scope), Rc::clone(&context), stmt)? } Ok(()) } fn validate_all_paths_return_or_revert( block: &[Spanned<fe::FuncStmt>], ) -> Result<(), SemanticError> { for statement in block.iter().rev() { if let fe::FuncStmt::Return { .. } = &statement.node { return Ok(()); } if let fe::FuncStmt::Revert { .. } = &statement.node { return Ok(()); } if let fe::FuncStmt::If { test: _, body, or_else, } = &statement.node { let body_returns = validate_all_paths_return_or_revert(body).is_ok(); let or_else_returns = or_else.is_empty() || validate_all_paths_return_or_revert(or_else).is_ok(); if body_returns && or_else_returns { return Ok(()); } } } Err(SemanticError::MissingReturn) } fn func_def_arg( scope: Shared<BlockScope>, arg: &Spanned<fe::FuncDefArg>, ) -> Result<FixedSize, SemanticError> { let name = arg.node.name.node.to_string(); let typ = types::type_desc_fixed_size(Scope::Block(Rc::clone(&scope)), &arg.node.typ)?; scope.borrow_mut().add_var(name, typ.clone().into_type()); Ok(typ) } fn func_stmt( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { match &stmt.node { fe::FuncStmt::Return { .. } => func_return(scope, context, stmt), fe::FuncStmt::VarDecl { .. } => declarations::var_decl(scope, context, stmt), fe::FuncStmt::Assign { .. } => assignments::assign(scope, context, stmt), fe::FuncStmt::Emit { .. } => emit(scope, context, stmt), fe::FuncStmt::AugAssign { .. } => unimplemented!(), fe::FuncStmt::For { .. } => unimplemented!(), fe::FuncStmt::While { .. } => while_loop(scope, context, stmt), fe::FuncStmt::If { .. } => if_statement(scope, context, stmt), fe::FuncStmt::Assert { .. } => assert(scope, context, stmt), fe::FuncStmt::Expr { .. } => expr(scope, context, stmt), fe::FuncStmt::Pass => unimplemented!(), fe::FuncStmt::Break => break_statement(scope, context, stmt), fe::FuncStmt::Continue => continue_statement(scope, context, stmt), fe::FuncStmt::Revert => Ok(()), } } fn verify_is_boolean( scope: Shared<BlockScope>, context: Shared<Context>, expr: &Spanned<fe::Expr>, ) -> Result<(), SemanticError> { let attributes = expressions::expr(scope, context, expr)?; if let Type::Base(Base::Bool) = attributes.typ { return Ok(()); } Err(SemanticError::TypeError) } fn break_statement( scope: Shared<BlockScope>, _context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Break {} = &stmt.node { return verify_loop_in_scope(scope, SemanticError::BreakWithoutLoop); } unreachable!() } fn continue_statement( scope: Shared<BlockScope>, _context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Continue {} = &stmt.node { return verify_loop_in_scope(scope, SemanticError::ContinueWithoutLoop); } unreachable!() } fn verify_loop_in_scope( scope: Shared<BlockScope>, error: SemanticError, ) -> Result<(), SemanticError> { if scope.borrow().inherits_type(BlockScopeType::Loop) { Ok(()) } else { Err(error) } } fn if_statement( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { match &stmt.node { fe::FuncStmt::If { test, body, or_else, } => { let body_scope = BlockScope::from_block_scope(stmt.span, BlockScopeType::IfElse, Rc::clone(&scope)); traverse_statements(body_scope, Rc::clone(&context), body)?; let or_else_scope = BlockScope::from_block_scope(stmt.span, BlockScopeType::IfElse, Rc::clone(&scope)); traverse_statements(or_else_scope, Rc::clone(&context), or_else)?; verify_is_boolean(scope, context, test) } _ => unreachable!(), } } fn while_loop( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { match &stmt.node { fe::FuncStmt::While { test, body, or_else, } => { if !or_else.is_empty() { unimplemented!(); } let body_scope = BlockScope::from_block_scope(stmt.span, BlockScopeType::Loop, Rc::clone(&scope)); traverse_statements(body_scope, Rc::clone(&context), body)?; verify_is_boolean(scope, context, test) } _ => unreachable!(), } } fn expr( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Expr { value } = &stmt.node { let spanned = spanned_expression(&stmt.span, value); let _attributes = expressions::expr(scope, context, &spanned)?; } Ok(()) } fn emit( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Emit { value: Spanned { node: fe::Expr::Call { func, args }, .. }, } = &stmt.node { let event_name = expressions::expr_name_string(func)?; if let Some(ContractDef::Event(event)) = scope.borrow().contract_def(event_name) { context.borrow_mut().add_emit(stmt, event); } for arg in args.node.iter() { call_arg(Rc::clone(&scope), Rc::clone(&context), arg)?; } return Ok(()); } unreachable!() } fn assert( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Assert { test, msg } = &stmt.node { verify_is_boolean(Rc::clone(&scope), Rc::clone(&context), test)?; if let Some(msg) = msg { let _msg_attributes = expressions::expr(scope, context, msg)?; } return Ok(()); } unreachable!() } fn call_arg( scope: Shared<BlockScope>, context: Shared<Context>, arg: &Spanned<fe::CallArg>, ) -> Result<(), SemanticError> { match &arg.node { fe::CallArg::Arg(value) => { let spanned = spanned_expression(&arg.span, value); let _attributes = expressions::expr(scope, context, &spanned)?; } fe::CallArg::Kwarg(fe::Kwarg { name: _, value }) => { let _attributes = expressions::expr(scope, context, value)?; } }; Ok(()) } fn func_return( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Return { value: Some(value) } = &stmt.node { let attributes = expressions::expr(Rc::clone(&scope), Rc::clone(&context), value)?; match context .borrow() .get_function(scope.borrow().function_scope().borrow().span) { Some(fn_attr) => { if fn_attr.return_type.clone().into_type() != attributes.typ { return Err(SemanticError::TypeError); } } None => unreachable!(), } return Ok(()); } unreachable!() } #[cfg(test)] mod tests { use crate::namespace::scopes::{ ContractDef, ContractScope, ModuleScope, Shared, }; use crate::namespace::types::{ Base, FixedSize, }; use crate::traversal::functions::func_def; use crate::Context; use fe_parser as parser; use std::rc::Rc; fn scope() -> Shared<ContractScope> { let module_scope = ModuleScope::new(); ContractScope::new(module_scope) } fn analyze(scope: Shared<ContractScope>, src: &str) -> Context { let context = Context::new_shared(); let tokens = parser::get_parse_tokens(src).expect("Couldn't parse expression"); let def = &parser::parsers::func_def(&tokens[..]) .expect("Couldn't build func def AST") .1; func_def(scope, Rc::clone(&context), def).expect("Couldn't map func def AST"); Rc::try_unwrap(context) .map_err(|_| "") .unwrap() .into_inner() } #[test] fn simple_func_def() { let scope = scope(); let func_def = "\ def foo(x: u256) -> u256:\ return x + x\ "; let context = analyze(Rc::clone(&scope), func_def); assert_eq!(context.expressions.len(), 3); assert_eq!( scope.borrow().def("foo".to_string()), Some(ContractDef::Function { is_public: false, params: vec![FixedSize::Base(Base::U256)], returns: FixedSize::Base(Base::U256) }) ); } }
use crate::errors::SemanticError; use crate::namespace::scopes::{ BlockScope, BlockScopeType, ContractDef, ContractScope, Scope, Shared, }; use crate::namespace::types::{ Base, FixedSize, Tuple, Type, }; use crate::traversal::_utils::spanned_expression; use crate::traversal::{ assignments, declarations, expressions, types, }; use crate::{ Context, FunctionAttributes, }; use fe_parser::ast as fe; use fe_parser::span::Spanned; use std::rc::Rc; pub fn func_def( contract_scope: Shared<ContractScope>, context: Shared<Context>, def: &Spanned<fe::ContractStmt>, ) -> Result<(), SemanticError> { if let fe::ContractStmt::FuncDef { qual, name, args, return_type, body, } = &def.node { let function_scope = BlockScope::from_contract_scope(def.span, Rc::clone(&contract_scope)); let name = name.node.to_string(); let param_types = args .iter() .map(|arg| func_def_arg(Rc::clone(&function_scope), arg)) .collect::<Result<Vec<_>, _>>()?; let return_type = return_type .as_ref() .map(|typ| types::type_desc_fixed_size(Scope::Block(Rc::clone(&function_scope)), &typ)) .transpose()? .unwrap_or_else(|| Tuple::empty().to_fixed_size()); if !return_type.is_empty_tuple() { validate_all_paths_return_or_revert(&body)? } let is_public = qual.is_some(); contract_scope.borrow_mut().add_function( name.clone(), is_public, param_types.clone(), return_type.clone(), ); let attributes = FunctionAttributes { name, param_types, return_type, }; context.borrow_mut().add_function(def, attributes); traverse_statements(function_scope, context, body)?; return Ok(()); } unreachable!() } fn traverse_statements( scope: Shared<BlockScope>, context: Shared<Context>, body: &[Spanned<fe::FuncStmt>], ) -> Result<(), SemanticError> { for stmt in body.iter() { func_stmt(Rc::clone(&scope), Rc::clone(&context), stmt)? } Ok(()) } fn validate_all_paths_return_or_revert( block: &[Spanned<fe::FuncStmt>], ) -> Result<(), SemanticError> { for statement in block.iter().rev() { if let fe::FuncStmt::Return { .. } = &statement.node { return Ok(()); } if let fe::FuncStmt::Revert { .. } = &statement.node { return Ok(()); } if let fe::FuncStmt::If { test: _, body, or_else, } = &statement.node { let body_returns = validate_all_paths_return_or_revert(body).is_ok(); let or_else_returns = or_else.is_empty() || validate_all_paths_return_or_revert(or_else).is_ok(); if body_returns && or_else_returns { return Ok(()); } } } Err(SemanticError::MissingReturn) } fn func_def_arg( scope: Shared<BlockScope>, arg: &Spanned<fe::FuncDefArg>, ) -> Result<FixedSize, SemanticError> { let name = arg.node.name.node.to_string(); let typ = types::type_desc_fixed_size(Scope::Block(Rc::clone(&scope)), &arg.node.typ)?; scope.borrow_mut().add_var(name, typ.clone().into_type()); Ok(typ) } fn func_stmt( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { match &stmt.node { fe::FuncStmt::Return { .. } => func_return(scope, context, stmt), fe::FuncStmt::VarDecl { .. } => declarations::var_decl(scope, context, stmt), fe::FuncStmt::Assign { .. } => assignments::assign(scope, context, stmt), fe::FuncStmt::Emit { .. } => emit(scope, context, stmt), fe::FuncStmt::AugAssign { .. } => unimplemented!(), fe::FuncStmt::For { .. } => unimplemented!(), fe::FuncStmt::While { .. } => while_loop(scope, context, stmt), fe::FuncStmt::If { .. } => if_statement(scope, context, stmt), fe::FuncStmt::Assert { .. } => assert(scope, context, stmt), fe::FuncStmt::Expr { .. } => expr(scope, context, stmt), fe::FuncStmt::Pass => unimplemented!(), fe::FuncStmt::Break => break_statement(scope, context, stmt), fe::FuncStmt::Continue => continue_statement(scope, context, stmt), fe::FuncStmt::Revert => Ok(()), } } fn verify_is_boolean( scope: Shared<BlockScope>, context: Shared<Context>, expr: &Spanned<fe::Expr>, ) -> Result<(), SemanticError> { let attributes = expressions::expr(scope, context, expr)?; if let Type::Base(Base::Bool) = attributes.typ { return Ok(()); } Err(SemanticError::TypeError) }
fn continue_statement( scope: Shared<BlockScope>, _context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Continue {} = &stmt.node { return verify_loop_in_scope(scope, SemanticError::ContinueWithoutLoop); } unreachable!() } fn verify_loop_in_scope( scope: Shared<BlockScope>, error: SemanticError, ) -> Result<(), SemanticError> { if scope.borrow().inherits_type(BlockScopeType::Loop) { Ok(()) } else { Err(error) } } fn if_statement( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { match &stmt.node { fe::FuncStmt::If { test, body, or_else, } => { let body_scope = BlockScope::from_block_scope(stmt.span, BlockScopeType::IfElse, Rc::clone(&scope)); traverse_statements(body_scope, Rc::clone(&context), body)?; let or_else_scope = BlockScope::from_block_scope(stmt.span, BlockScopeType::IfElse, Rc::clone(&scope)); traverse_statements(or_else_scope, Rc::clone(&context), or_else)?; verify_is_boolean(scope, context, test) } _ => unreachable!(), } } fn while_loop( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { match &stmt.node { fe::FuncStmt::While { test, body, or_else, } => { if !or_else.is_empty() { unimplemented!(); } let body_scope = BlockScope::from_block_scope(stmt.span, BlockScopeType::Loop, Rc::clone(&scope)); traverse_statements(body_scope, Rc::clone(&context), body)?; verify_is_boolean(scope, context, test) } _ => unreachable!(), } } fn expr( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Expr { value } = &stmt.node { let spanned = spanned_expression(&stmt.span, value); let _attributes = expressions::expr(scope, context, &spanned)?; } Ok(()) } fn emit( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Emit { value: Spanned { node: fe::Expr::Call { func, args }, .. }, } = &stmt.node { let event_name = expressions::expr_name_string(func)?; if let Some(ContractDef::Event(event)) = scope.borrow().contract_def(event_name) { context.borrow_mut().add_emit(stmt, event); } for arg in args.node.iter() { call_arg(Rc::clone(&scope), Rc::clone(&context), arg)?; } return Ok(()); } unreachable!() } fn assert( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Assert { test, msg } = &stmt.node { verify_is_boolean(Rc::clone(&scope), Rc::clone(&context), test)?; if let Some(msg) = msg { let _msg_attributes = expressions::expr(scope, context, msg)?; } return Ok(()); } unreachable!() } fn call_arg( scope: Shared<BlockScope>, context: Shared<Context>, arg: &Spanned<fe::CallArg>, ) -> Result<(), SemanticError> { match &arg.node { fe::CallArg::Arg(value) => { let spanned = spanned_expression(&arg.span, value); let _attributes = expressions::expr(scope, context, &spanned)?; } fe::CallArg::Kwarg(fe::Kwarg { name: _, value }) => { let _attributes = expressions::expr(scope, context, value)?; } }; Ok(()) } fn func_return( scope: Shared<BlockScope>, context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Return { value: Some(value) } = &stmt.node { let attributes = expressions::expr(Rc::clone(&scope), Rc::clone(&context), value)?; match context .borrow() .get_function(scope.borrow().function_scope().borrow().span) { Some(fn_attr) => { if fn_attr.return_type.clone().into_type() != attributes.typ { return Err(SemanticError::TypeError); } } None => unreachable!(), } return Ok(()); } unreachable!() } #[cfg(test)] mod tests { use crate::namespace::scopes::{ ContractDef, ContractScope, ModuleScope, Shared, }; use crate::namespace::types::{ Base, FixedSize, }; use crate::traversal::functions::func_def; use crate::Context; use fe_parser as parser; use std::rc::Rc; fn scope() -> Shared<ContractScope> { let module_scope = ModuleScope::new(); ContractScope::new(module_scope) } fn analyze(scope: Shared<ContractScope>, src: &str) -> Context { let context = Context::new_shared(); let tokens = parser::get_parse_tokens(src).expect("Couldn't parse expression"); let def = &parser::parsers::func_def(&tokens[..]) .expect("Couldn't build func def AST") .1; func_def(scope, Rc::clone(&context), def).expect("Couldn't map func def AST"); Rc::try_unwrap(context) .map_err(|_| "") .unwrap() .into_inner() } #[test] fn simple_func_def() { let scope = scope(); let func_def = "\ def foo(x: u256) -> u256:\ return x + x\ "; let context = analyze(Rc::clone(&scope), func_def); assert_eq!(context.expressions.len(), 3); assert_eq!( scope.borrow().def("foo".to_string()), Some(ContractDef::Function { is_public: false, params: vec![FixedSize::Base(Base::U256)], returns: FixedSize::Base(Base::U256) }) ); } }
fn break_statement( scope: Shared<BlockScope>, _context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Break {} = &stmt.node { return verify_loop_in_scope(scope, SemanticError::BreakWithoutLoop); } unreachable!() }
function_block-full_function
[ { "content": "/// Maps a type description node to an enum type.\n\npub fn type_desc(scope: Scope, typ: &Spanned<fe::TypeDesc>) -> Result<Type, SemanticError> {\n\n types::type_desc(&scope.module_scope().borrow().defs, &typ.node)\n\n}\n\n\n", "file_path": "semantics/src/traversal/types.rs", "rank": 0,...
Rust
src/utilities.rs
mandx/privie
1e44e5b942979746383496223390718d48db8fc7
use std::{ fmt::{Display, Formatter}, fs::{File, OpenOptions}, io::{self, stdin, stdout, BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, }; use thiserror::Error as ThisError; #[derive(Debug, ThisError)] pub enum IoUtilsError<P: std::fmt::Debug + Display> { #[error("Could not open `{path}`")] Open { #[source] source: io::Error, path: P, }, #[error("Could not read from `{path}`")] Read { #[source] source: io::Error, path: P, }, #[error("Could not write to `{path}`")] Write { #[source] source: io::Error, path: P, }, #[error("Could not parse `{path}` as JSON")] JsonParse { source: json::Error, path: P }, #[error("STDIN can be used only once")] MultipleStdInRefs, } #[derive(Debug, Clone)] pub struct InputFile { filename: Option<PathBuf>, } impl Display for InputFile { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { match &self.filename { Some(path) => write!(formatter, "{}", path.to_string_lossy()), None => write!(formatter, "{}", Self::DISPLAY_STR), } } } impl std::str::FromStr for InputFile { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "" | "-" | Self::DISPLAY_STR => Self::use_stdin(), s => Self::use_filename(s), }) } } impl Default for InputFile { fn default() -> Self { Self::use_stdin() } } impl InputFile { const DISPLAY_STR: &'static str = "<stdin>"; pub fn use_stdin() -> Self { Self { filename: None } } pub fn use_filename<P: AsRef<Path>>(filename: P) -> Self { Self { filename: Some(filename.as_ref().into()), } } pub fn open(&self) -> Result<impl Read, IoUtilsError<Self>> { match &self.filename { Some(path) => Ok(Box::new(BufReader::new(File::open(path).map_err(|error| { IoUtilsError::Open { source: error, path: self.clone(), } })?)) as Box<dyn Read>), None => Ok(Box::new(BufReader::new(stdin())) as Box<dyn Read>), } } pub fn read(&self) -> Result<String, IoUtilsError<Self>> { let mut reader = self.open()?; let mut buf = String::new(); reader .read_to_string(&mut buf) .map_err(|error| IoUtilsError::Read { source: error, path: self.clone(), })?; Ok(buf) } pub fn read_json(&self) -> Result<json::JsonValue, IoUtilsError<Self>> { json::parse(&self.read()?).map_err(|error| IoUtilsError::JsonParse { source: error, path: self.clone(), }) } pub fn check_stdin_once<'a, I: IntoIterator<Item = &'a Self>>( inputs: I, ) -> Result<(), IoUtilsError<Self>> { let mut found = false; for input in inputs { if input.filename.is_none() { if found { return Err(IoUtilsError::MultipleStdInRefs); } found = true; } } Ok(()) } } #[derive(Debug, Clone)] pub struct OutputFile { filename: Option<PathBuf>, } impl Display for OutputFile { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { match &self.filename { Some(path) => write!(formatter, "{}", path.to_string_lossy()), None => write!(formatter, "{}", Self::DISPLAY_STR), } } } impl std::str::FromStr for OutputFile { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "" | "-" | Self::DISPLAY_STR => Self::use_stdout(), s => Self::use_filename(s), }) } } impl Default for OutputFile { fn default() -> Self { Self::use_stdout() } } impl OutputFile { const DISPLAY_STR: &'static str = "<stdout>"; pub fn use_stdout() -> Self { Self { filename: None } } pub fn use_filename<P: AsRef<Path>>(filename: P) -> Self { Self { filename: Some(filename.as_ref().into()), } } pub fn open(&self) -> Result<impl Write, IoUtilsError<Self>> { match &self.filename { Some(path) => Ok(Box::new(BufWriter::new( OpenOptions::new() .write(true) .truncate(true) .create(true) .open(path) .map_err(|error| IoUtilsError::Open { source: error, path: self.clone(), })?, )) as Box<dyn Write>), None => Ok(Box::new(BufWriter::new(stdout())) as Box<dyn Write>), } } pub fn write<S: AsRef<[u8]>>(&self, content: S) -> Result<(), IoUtilsError<Self>> { self.open()? .write_all(content.as_ref()) .map_err(|error| IoUtilsError::Write { source: error, path: self.clone(), }) } pub fn write_json<J: Into<json::JsonValue>>(&self, data: J) -> Result<(), IoUtilsError<Self>> { self.write(&json::stringify_pretty(data.into(), 2)) } }
use std::{ fmt::{Display, Formatter}, fs::{File, OpenOptions}, io::{self, stdin, stdout, BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, }; use thiserror::Error as ThisError; #[derive(Debug, ThisError)] pub enum IoUtilsError<P: std::fmt::Debug + Display> { #[error("Could not open `{path}`")] Open { #[source] source: io::Error, path: P, }, #[error("Could not read from `{path}`")] Read { #[source] source: io::Error, path: P, }, #[error("Could not write to `{path}`")] Write { #[source] source: io::Error, path: P, }, #[error("Could not parse `{path}` as JSON")] JsonParse { source: json::Error, path: P }, #[error("STDIN can be used only once")] MultipleStdInRefs, } #[derive(Debug, Clone)] pub struct InputFile { filename: Option<PathBuf>, } impl Display for InputFile { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { match &self.filename { Some(path) => write!(formatter, "{}", path.to_string_lossy()), None => write!(formatter, "{}", Self::DISPLAY_STR), } } } impl std::str::FromStr for InputFile { type Err = String; fn from_str(s: &str) -> Result<Self, S
} impl Default for InputFile { fn default() -> Self { Self::use_stdin() } } impl InputFile { const DISPLAY_STR: &'static str = "<stdin>"; pub fn use_stdin() -> Self { Self { filename: None } } pub fn use_filename<P: AsRef<Path>>(filename: P) -> Self { Self { filename: Some(filename.as_ref().into()), } } pub fn open(&self) -> Result<impl Read, IoUtilsError<Self>> { match &self.filename { Some(path) => Ok(Box::new(BufReader::new(File::open(path).map_err(|error| { IoUtilsError::Open { source: error, path: self.clone(), } })?)) as Box<dyn Read>), None => Ok(Box::new(BufReader::new(stdin())) as Box<dyn Read>), } } pub fn read(&self) -> Result<String, IoUtilsError<Self>> { let mut reader = self.open()?; let mut buf = String::new(); reader .read_to_string(&mut buf) .map_err(|error| IoUtilsError::Read { source: error, path: self.clone(), })?; Ok(buf) } pub fn read_json(&self) -> Result<json::JsonValue, IoUtilsError<Self>> { json::parse(&self.read()?).map_err(|error| IoUtilsError::JsonParse { source: error, path: self.clone(), }) } pub fn check_stdin_once<'a, I: IntoIterator<Item = &'a Self>>( inputs: I, ) -> Result<(), IoUtilsError<Self>> { let mut found = false; for input in inputs { if input.filename.is_none() { if found { return Err(IoUtilsError::MultipleStdInRefs); } found = true; } } Ok(()) } } #[derive(Debug, Clone)] pub struct OutputFile { filename: Option<PathBuf>, } impl Display for OutputFile { fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { match &self.filename { Some(path) => write!(formatter, "{}", path.to_string_lossy()), None => write!(formatter, "{}", Self::DISPLAY_STR), } } } impl std::str::FromStr for OutputFile { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "" | "-" | Self::DISPLAY_STR => Self::use_stdout(), s => Self::use_filename(s), }) } } impl Default for OutputFile { fn default() -> Self { Self::use_stdout() } } impl OutputFile { const DISPLAY_STR: &'static str = "<stdout>"; pub fn use_stdout() -> Self { Self { filename: None } } pub fn use_filename<P: AsRef<Path>>(filename: P) -> Self { Self { filename: Some(filename.as_ref().into()), } } pub fn open(&self) -> Result<impl Write, IoUtilsError<Self>> { match &self.filename { Some(path) => Ok(Box::new(BufWriter::new( OpenOptions::new() .write(true) .truncate(true) .create(true) .open(path) .map_err(|error| IoUtilsError::Open { source: error, path: self.clone(), })?, )) as Box<dyn Write>), None => Ok(Box::new(BufWriter::new(stdout())) as Box<dyn Write>), } } pub fn write<S: AsRef<[u8]>>(&self, content: S) -> Result<(), IoUtilsError<Self>> { self.open()? .write_all(content.as_ref()) .map_err(|error| IoUtilsError::Write { source: error, path: self.clone(), }) } pub fn write_json<J: Into<json::JsonValue>>(&self, data: J) -> Result<(), IoUtilsError<Self>> { self.write(&json::stringify_pretty(data.into(), 2)) } }
elf::Err> { Ok(match s { "" | "-" | Self::DISPLAY_STR => Self::use_stdin(), s => Self::use_filename(s), }) }
function_block-function_prefixed
[ { "content": "/// Attempt to decrypt the given ciphertext with the given secret key.\n\n/// Will fail if the secret key doesn't match the public key used to\n\n/// encrypt the payload, or if the ciphertext is not long enough.\n\npub fn open(ciphertext: &[u8], secret_key: &SecretKey) -> Result<Vec<u8>, Error> {\...
Rust
ivy-vulkan/src/descriptors/layout.rs
ten3roberts/ivy
fb5a7645c9f699c2aebf3d1b90c1d1f9e78355fa
use crate::Result; use std::{collections::HashMap, sync::Arc}; use ash::vk::DescriptorSetLayout; use ash::vk::DescriptorSetLayoutCreateInfo; use ash::Device; use parking_lot::RwLock; use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use super::DescriptorSetBinding; use super::MAX_BINDINGS; #[derive(Clone, Debug)] pub struct DescriptorLayoutInfo { bindings: SmallVec<[DescriptorSetBinding; MAX_BINDINGS]>, } unsafe impl Send for DescriptorLayoutInfo {} unsafe impl Sync for DescriptorLayoutInfo {} impl DescriptorLayoutInfo { pub fn new(bindings: &[DescriptorSetBinding]) -> Self { let mut layout = Self { bindings: Default::default(), }; for binding in bindings { layout.insert(*binding); } layout } pub fn bindings(&self) -> &[DescriptorSetBinding] { &self.bindings } pub fn insert(&mut self, binding: DescriptorSetBinding) { let mut len = self.bindings.len(); let mut mid = (len / 2).min(1); loop { if len < 1 { if mid == self.bindings.len() || self.bindings[mid].binding > binding.binding { self.bindings.insert(mid, binding); } else { self.bindings.insert(mid + 1, binding); } break; } match self.bindings[mid].binding.cmp(&binding.binding) { std::cmp::Ordering::Less => { len /= 2; mid += (len as f32 / 2.0).floor() as usize; } std::cmp::Ordering::Equal => { self.bindings[mid] = binding; break; } std::cmp::Ordering::Greater => { len /= 2; mid -= (len as f32 / 2.0).ceil() as usize; } } } } pub fn extend<I: Iterator<Item = DescriptorSetBinding>>(&mut self, bindings: I) { self.bindings.extend(bindings); } pub fn get(&mut self, binding: u32) -> Option<DescriptorSetBinding> { let mut len = self.bindings.len(); let mut mid = (len / 2).max(1); loop { if mid >= self.bindings.len() || len == 0 { return None; } match self.bindings[mid].binding.cmp(&binding) { std::cmp::Ordering::Less => { len /= 2; mid += (len as f32 / 2.0).ceil() as usize; } std::cmp::Ordering::Equal => return Some(self.bindings[mid]), std::cmp::Ordering::Greater => { len /= 2; mid -= (len as f32 / 2.0).ceil() as usize; } } } } } impl Default for DescriptorLayoutInfo { fn default() -> Self { Self { bindings: Default::default(), } } } impl Hash for DescriptorLayoutInfo { fn hash<H: Hasher>(&self, state: &mut H) { for binding in &self.bindings { binding.binding.hash(state); } } } impl PartialEq for DescriptorLayoutInfo { fn eq(&self, other: &Self) -> bool { for (a, b) in self.bindings.iter().zip(&other.bindings) { if a.binding != b.binding || a.descriptor_type != b.descriptor_type || a.descriptor_count != b.descriptor_count || a.stage_flags != b.stage_flags { return false; } } true } } impl Eq for DescriptorLayoutInfo {} pub struct DescriptorLayoutCache { device: Arc<Device>, layouts: RwLock<HashMap<DescriptorLayoutInfo, DescriptorSetLayout>>, } impl DescriptorLayoutCache { pub fn new(device: Arc<Device>) -> Self { Self { device, layouts: RwLock::new(HashMap::new()), } } pub fn get(&self, info: &DescriptorLayoutInfo) -> Result<DescriptorSetLayout> { let guard = self.layouts.read(); if let Some(layout) = guard.get(info) { Ok(*layout) } else { drop(guard); let info = info.clone(); let layout = create(&self.device, &info)?; Ok(*self.layouts.write().entry(info).or_insert(layout)) } } pub fn clear(&mut self) { for (_, layout) in self.layouts.write().drain() { destroy(&self.device, layout); } } } impl Drop for DescriptorLayoutCache { fn drop(&mut self) { self.clear() } } pub fn create(device: &Device, info: &DescriptorLayoutInfo) -> Result<DescriptorSetLayout> { let create_info = DescriptorSetLayoutCreateInfo { binding_count: info.bindings.len() as u32, p_bindings: info.bindings.as_ptr(), ..Default::default() }; let layout = unsafe { device.create_descriptor_set_layout(&create_info, None)? }; Ok(layout) } pub fn destroy(device: &Device, layout: DescriptorSetLayout) { unsafe { device.destroy_descriptor_set_layout(layout, None) } } #[cfg(test)] mod tests { use ash::vk::DescriptorType; use super::*; #[test] fn layout_info_add() { let mut layout = DescriptorLayoutInfo::new(&[]); let mut bindings = [DescriptorSetBinding::default(); 6]; bindings[0] = DescriptorSetBinding { binding: 0, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[0]); eprintln!("Layout: {:?}", layout); bindings[2] = DescriptorSetBinding { binding: 2, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[2]); eprintln!("Layout: {:?}", layout); bindings[1] = DescriptorSetBinding { binding: 1, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[1]); eprintln!("Layout: {:?}", layout); bindings[3] = DescriptorSetBinding { binding: 3, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[3]); eprintln!("Layout: {:?}", layout); bindings[5] = DescriptorSetBinding { binding: 5, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[5]); eprintln!("Layout: {:?}", layout); bindings[4] = DescriptorSetBinding { binding: 4, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[4]); layout.insert(DescriptorSetBinding { binding: 4, descriptor_type: DescriptorType::COMBINED_IMAGE_SAMPLER, descriptor_count: 1, ..Default::default() }); eprintln!("Layout: {:?}", layout); assert!(layout .bindings() .iter() .map(|val| val.binding) .eq([0, 1, 2, 3, 4, 5].iter().cloned())); for binding in &bindings { assert_eq!( Some(binding.binding), layout.get(binding.binding).map(|val| val.binding) ) } assert_eq!(None, layout.get(9).map(|_| ())); } }
use crate::Result; use std::{collections::HashMap, sync::Arc}; use ash::vk::DescriptorSetLayout; use ash::vk::DescriptorSetLayoutCreateInfo; use ash::Device; use parking_lot::RwLock; use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use super::DescriptorSetBinding; use super::MAX_BINDINGS; #[derive(Clone, Debug)] pub struct DescriptorLayoutInfo { bindings: SmallVec<[DescriptorSetBinding; MAX_BINDINGS]>, } unsafe impl Send for DescriptorLayoutInfo {} unsafe impl Sync for DescriptorLayoutInfo {} impl DescriptorLayoutInfo { pub fn new(bindings: &[DescriptorSetBinding]) -> Self { let mut layout = Self { bindings: Default::default(), }; for binding in bindings { layout.insert(*binding); } layout } pub fn bindings(&self) -> &[DescriptorSetBinding] { &self.bindings } pub fn insert(&mut self, binding: DescriptorSetBinding) { let mut len = self.bindings.len(); let mut mid = (len / 2).min(1); loop { if len < 1 { if mid == self.bindings.len() || self.bindings[mid].binding > binding.binding { self.bindings.insert(mid, binding); } else { self.bindings.insert(mid + 1, binding); } break; } match self.bindings[mid].binding.cmp(&binding.binding) { std::cmp::Ordering::Less => { len /= 2; mid += (len as f32 / 2.0).floor() as usize; } std::cmp::Ordering::Equal => { self.bindings[mid] = binding; break; } std::cmp::Ordering::Greater => { len /= 2; mid -= (len as f32 / 2.0).ceil() as usize; } } } } pub fn extend<I: Iterator<Item = DescriptorSetBinding>>(&mut self, bindings: I) { self.bindings.extend(bindings); } pub fn get(&mut self, binding: u32) -> Option<DescriptorSetBinding> { let mut len = self.bindings.len(); let mut mid = (len / 2).max(1); loop { if mid >= self.bindings.len() || len == 0 { return None; } match self.bindings[mid].binding.cmp(&binding) { std::cmp::Ordering::Less => { len /= 2; mid += (len as f32 / 2.0).ceil() as usize; } std::cmp::Ordering::Equal => return Some(self.bindings[mid]), std::cmp::Ordering::Greater => { len /= 2; mid -= (len as f32 / 2.0).ceil() as usize; } } } } } impl Default for DescriptorLayoutInfo { fn default() -> Self { Self { bindings: Default::default(), } } } impl Hash for DescriptorLayoutInfo { fn hash<H: Hasher>(&self, state: &mut H) { for binding in &self.bindings { binding.binding.hash(state); } } } impl PartialEq for DescriptorLayoutInfo {
} impl Eq for DescriptorLayoutInfo {} pub struct DescriptorLayoutCache { device: Arc<Device>, layouts: RwLock<HashMap<DescriptorLayoutInfo, DescriptorSetLayout>>, } impl DescriptorLayoutCache { pub fn new(device: Arc<Device>) -> Self { Self { device, layouts: RwLock::new(HashMap::new()), } } pub fn get(&self, info: &DescriptorLayoutInfo) -> Result<DescriptorSetLayout> { let guard = self.layouts.read(); if let Some(layout) = guard.get(info) { Ok(*layout) } else { drop(guard); let info = info.clone(); let layout = create(&self.device, &info)?; Ok(*self.layouts.write().entry(info).or_insert(layout)) } } pub fn clear(&mut self) { for (_, layout) in self.layouts.write().drain() { destroy(&self.device, layout); } } } impl Drop for DescriptorLayoutCache { fn drop(&mut self) { self.clear() } } pub fn create(device: &Device, info: &DescriptorLayoutInfo) -> Result<DescriptorSetLayout> { let create_info = DescriptorSetLayoutCreateInfo { binding_count: info.bindings.len() as u32, p_bindings: info.bindings.as_ptr(), ..Default::default() }; let layout = unsafe { device.create_descriptor_set_layout(&create_info, None)? }; Ok(layout) } pub fn destroy(device: &Device, layout: DescriptorSetLayout) { unsafe { device.destroy_descriptor_set_layout(layout, None) } } #[cfg(test)] mod tests { use ash::vk::DescriptorType; use super::*; #[test] fn layout_info_add() { let mut layout = DescriptorLayoutInfo::new(&[]); let mut bindings = [DescriptorSetBinding::default(); 6]; bindings[0] = DescriptorSetBinding { binding: 0, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[0]); eprintln!("Layout: {:?}", layout); bindings[2] = DescriptorSetBinding { binding: 2, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[2]); eprintln!("Layout: {:?}", layout); bindings[1] = DescriptorSetBinding { binding: 1, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[1]); eprintln!("Layout: {:?}", layout); bindings[3] = DescriptorSetBinding { binding: 3, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[3]); eprintln!("Layout: {:?}", layout); bindings[5] = DescriptorSetBinding { binding: 5, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[5]); eprintln!("Layout: {:?}", layout); bindings[4] = DescriptorSetBinding { binding: 4, descriptor_type: DescriptorType::UNIFORM_BUFFER, descriptor_count: 1, ..Default::default() }; layout.insert(bindings[4]); layout.insert(DescriptorSetBinding { binding: 4, descriptor_type: DescriptorType::COMBINED_IMAGE_SAMPLER, descriptor_count: 1, ..Default::default() }); eprintln!("Layout: {:?}", layout); assert!(layout .bindings() .iter() .map(|val| val.binding) .eq([0, 1, 2, 3, 4, 5].iter().cloned())); for binding in &bindings { assert_eq!( Some(binding.binding), layout.get(binding.binding).map(|val| val.binding) ) } assert_eq!(None, layout.get(9).map(|_| ())); } }
fn eq(&self, other: &Self) -> bool { for (a, b) in self.bindings.iter().zip(&other.bindings) { if a.binding != b.binding || a.descriptor_type != b.descriptor_type || a.descriptor_count != b.descriptor_count || a.stage_flags != b.stage_flags { return false; } } true }
function_block-full_function
[ { "content": "// Generates a random scalar between -1 and 1\n\npub fn one<R: Rng>(rng: &mut R) -> f32 {\n\n rng.gen_range(-1.0..=1.0)\n\n}\n", "file_path": "ivy-random/src/scalar.rs", "rank": 0, "score": 255513.0309084286 }, { "content": "// Generates a random scalar between 0 and 1\n\npu...
Rust
third-party/fs-mistrust/src/imp.rs
capyloon/api-daemon
ab4e4b60aa9bb617734c64655c0b8940fff098bc
use std::{ fs::{FileType, Metadata}, path::Path, }; #[cfg(target_family = "unix")] use std::os::unix::prelude::MetadataExt; use crate::{ walk::{PathType, ResolvePath}, Error, Result, Type, }; #[cfg(target_family = "unix")] pub(crate) const STICKY_BIT: u32 = 0o1000; fn boxed<'a, I: Iterator<Item = Error> + 'a>(iter: I) -> Box<dyn Iterator<Item = Error> + 'a> { Box::new(iter) } impl<'a> super::Verifier<'a> { pub(crate) fn check_errors(&self, path: &Path) -> impl Iterator<Item = Error> + '_ { if self.mistrust.dangerously_trust_everyone { let meta = match path.metadata() { Ok(meta) => meta, Err(e) => return boxed(vec![Error::inspecting(e, path)].into_iter()), }; let mut errors = Vec::new(); self.check_type(path, PathType::Final, &meta, &mut errors); return boxed(errors.into_iter()); } let rp = match ResolvePath::new(path) { Ok(rp) => rp, Err(e) => return boxed(vec![e].into_iter()), }; let should_retain = move |r: &Result<_>| match (r, &self.mistrust.ignore_prefix) { (Ok((p, _, _)), Some(ignore_prefix)) => !ignore_prefix.starts_with(p), (_, _) => true, }; boxed( rp.filter(should_retain) .flat_map(move |r| match r { Ok((path, path_type, metadata)) => { self.check_one(path.as_path(), path_type, &metadata) } Err(e) => vec![e], }), ) } #[cfg(feature = "walkdir")] pub(crate) fn check_content_errors(&self, path: &Path) -> impl Iterator<Item = Error> + '_ { use std::sync::Arc; if !self.check_contents || self.mistrust.dangerously_trust_everyone { return boxed(std::iter::empty()); } boxed( walkdir::WalkDir::new(path) .follow_links(false) .min_depth(1) .into_iter() .flat_map(move |ent| match ent { Err(err) => vec![Error::Listing(Arc::new(err))], Ok(ent) => match ent.metadata() { Ok(meta) => self .check_one(ent.path(), PathType::Content, &meta) .into_iter() .map(|e| Error::Content(Box::new(e))) .collect(), Err(err) => vec![Error::Listing(Arc::new(err))], }, }), ) } #[cfg(not(feature = "walkdir"))] pub(crate) fn check_content_errors(&self, _path: &Path) -> impl Iterator<Item = Error> + '_ { std::iter::empty() } #[must_use] pub(crate) fn check_one( &self, path: &Path, path_type: PathType, meta: &Metadata, ) -> Vec<Error> { let mut errors = Vec::new(); self.check_type(path, path_type, meta, &mut errors); #[cfg(target_family = "unix")] self.check_permissions(path, path_type, meta, &mut errors); errors } fn check_type( &self, path: &Path, path_type: PathType, meta: &Metadata, errors: &mut Vec<Error>, ) { let want_type = match path_type { PathType::Symlink => { return; } PathType::Intermediate => Type::Dir, PathType::Final => self.enforce_type, PathType::Content => Type::DirOrFile, }; if !want_type.matches(meta.file_type()) { errors.push(Error::BadType(path.into())); } } #[cfg(target_family = "unix")] fn check_permissions( &self, path: &Path, path_type: PathType, meta: &Metadata, errors: &mut Vec<Error>, ) { let uid = meta.uid(); if uid != 0 && Some(uid) != self.mistrust.trust_user { errors.push(Error::BadOwner(path.into(), uid)); } if path_type == PathType::Symlink { return; } let mut forbidden_bits = if !self.readable_okay && path_type == PathType::Final { 0o077 } else { if meta.is_dir() && meta.mode() & STICKY_BIT != 0 && path_type == PathType::Intermediate { 0o000 } else { 0o022 } }; if self.mistrust.trust_group == Some(meta.gid()) { forbidden_bits &= !0o070; } let bad_bits = meta.mode() & forbidden_bits; if bad_bits != 0 { errors.push(Error::BadPermission( path.into(), meta.mode() & 0o777, bad_bits, )); } } } impl super::Type { fn matches(&self, have_type: FileType) -> bool { match self { Type::Dir => have_type.is_dir(), Type::File => have_type.is_file(), Type::DirOrFile => have_type.is_dir() || have_type.is_file(), Type::Anything => true, } } }
use std::{ fs::{FileType, Metadata}, path::Path, }; #[cfg(target_family = "unix")] use std::os::unix::prelude::MetadataExt; use crate::{ walk::{PathType, ResolvePath}, Error, Result, Type, }; #[cfg(target_family = "unix")] pub(crate) const STICKY_BIT: u32 = 0o1000; fn boxed<'a, I: Iterator<Item = Error> + 'a>(iter: I) -> Box<dyn Iterator<Item = Error> + 'a> { Box::new(iter) } impl<'a> super::Verifier<'a> { pub(crate) fn check_errors(&self, path: &Path) -> impl Iterator<Item = Error> + '_ { if self.mistrust.dangerously_trust_everyone { let meta = match path.metadata() { Ok(meta) => meta, Err(e) => return boxed(vec![Error::inspecting(e, path)].into_iter()), }; let mut errors = Vec::new(); self.check_type(path, PathType::Final, &meta, &mut errors); return boxed(errors.into_iter()); } let rp = match ResolvePath::new(path) { Ok(rp) => rp, Err(e) => return boxed(vec![e].into_iter()), }; let should_retain = move |r: &Result<_>| match (r, &self.mistrust.ignore_prefix) { (Ok((p, _, _)), Some(ignore_prefix)) => !ignore_prefix.starts_with(p), (_, _) => true, }; boxed( rp.filter(should_retain) .flat_map(move |r| match r { Ok((path, path_type, metadata)) => { self.check_one(path.as_path(), path_type, &metadata) } Err(e) => vec![e], }), ) } #[cfg(feature = "walkdir")] pub(crate) fn check_content_errors(&self, path: &Path) -> impl Iterator<Item = Error> + '_ { use std::sync::Arc; if !self.check_contents || self.mistrust.dangerously_trust_everyone { return boxed(std::iter::empty()); } boxed( walkdir::WalkDir::new(path) .follow_links(false) .min_depth(1) .into_iter() .flat_map(move |ent| match ent { Err(err) => vec![Error::Listing(Arc::new(err))], Ok(ent) => match ent.metadata() { Ok(meta) => self .check_one(ent.path(), PathType::Content, &meta) .into_iter() .map(|e| Error::Content(Box::new(e))) .collect(), Err(err) => vec![Error::Listing(Arc::new(err))], }, }), ) } #[cfg(not(feature = "walkdir"))] pub(crate) fn check_content_errors(&self, _path: &Path) -> impl Iterator<Item = Error> + '_ { std::iter::empty() } #[must_use] pub(crate) fn check_one( &self, path: &Path,
fg(target_family = "unix")] self.check_permissions(path, path_type, meta, &mut errors); errors } fn check_type( &self, path: &Path, path_type: PathType, meta: &Metadata, errors: &mut Vec<Error>, ) { let want_type = match path_type { PathType::Symlink => { return; } PathType::Intermediate => Type::Dir, PathType::Final => self.enforce_type, PathType::Content => Type::DirOrFile, }; if !want_type.matches(meta.file_type()) { errors.push(Error::BadType(path.into())); } } #[cfg(target_family = "unix")] fn check_permissions( &self, path: &Path, path_type: PathType, meta: &Metadata, errors: &mut Vec<Error>, ) { let uid = meta.uid(); if uid != 0 && Some(uid) != self.mistrust.trust_user { errors.push(Error::BadOwner(path.into(), uid)); } if path_type == PathType::Symlink { return; } let mut forbidden_bits = if !self.readable_okay && path_type == PathType::Final { 0o077 } else { if meta.is_dir() && meta.mode() & STICKY_BIT != 0 && path_type == PathType::Intermediate { 0o000 } else { 0o022 } }; if self.mistrust.trust_group == Some(meta.gid()) { forbidden_bits &= !0o070; } let bad_bits = meta.mode() & forbidden_bits; if bad_bits != 0 { errors.push(Error::BadPermission( path.into(), meta.mode() & 0o777, bad_bits, )); } } } impl super::Type { fn matches(&self, have_type: FileType) -> bool { match self { Type::Dir => have_type.is_dir(), Type::File => have_type.is_file(), Type::DirOrFile => have_type.is_dir() || have_type.is_file(), Type::Anything => true, } } }
path_type: PathType, meta: &Metadata, ) -> Vec<Error> { let mut errors = Vec::new(); self.check_type(path, path_type, meta, &mut errors); #[c
function_block-random_span
[]
Rust
x86asm/src/encode/encoding.rs
project-ela/ela
b59cae869ca4258954583a87725b090a586601c1
use crate::{ common::{modrm::ModRM, rex::Rex, sib::Sib}, instruction::operand::{ immediate::Immediate, memory::{Displacement, Memory}, offset::Offset, register::{self, Register}, }, }; use super::inst::EncodedInst; pub enum RM<'a> { Register(&'a Register), Memory(&'a Memory), } pub fn encode_m(opcode: &[u8], opr1: RM) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr1), None); enc.modrm = Some(encode_modrm(&opr1)); enc.sib = encode_sib(&opr1); enc.disp = encode_disp(&opr1); enc } pub fn encode_o(opcode: u8, opr1: &Register) -> EncodedInst { let mut enc = EncodedInst::new(&[opcode + opr1.number()]); if opr1.only_in_64bit() { enc.rex = Some(Rex::new(false, false, false, opr1.only_in_64bit())); } enc } pub fn encode_i(opcode: &[u8], opr1: &Immediate) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.imm = Some(opr1.clone()); enc } pub fn encode_d(opcode: &[u8], opr1: &Offset) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.imm = match opr1 { Offset::Off8(value) => Some(Immediate::Imm8(*value)), Offset::Off32(value) => Some(Immediate::Imm32(*value)), }; enc } pub fn encode_mi(opcode: &[u8], opr1: RM, opr2: &Immediate) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr1), None); enc.modrm = Some(encode_modrm(&opr1)); enc.sib = encode_sib(&opr1); enc.disp = encode_disp(&opr1); enc.imm = Some(opr2.clone()); enc } pub fn encode_mr(opcode: &[u8], opr1: RM, opr2: &Register) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr1), Some(opr2)); enc.modrm = Some({ let mut modrm = encode_modrm(&opr1); modrm.reg = opr2.number(); modrm }); enc.sib = encode_sib(&opr1); enc.disp = encode_disp(&opr1); enc } pub fn encode_rm(opcode: &[u8], opr1: &Register, opr2: RM) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr2), Some(opr1)); enc.modrm = Some({ let mut modrm = encode_modrm(&opr2); modrm.reg = opr1.number(); modrm }); enc.sib = encode_sib(&opr2); enc.disp = encode_disp(&opr2); enc } pub fn encode_rmi(opcode: &[u8], opr1: &Register, opr2: RM, opr3: &Immediate) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr2), Some(opr1)); enc.modrm = Some({ let mut modrm = encode_modrm(&opr2); modrm.reg = opr1.number(); modrm }); enc.sib = encode_sib(&opr2); enc.disp = encode_disp(&opr2); enc.imm = Some(opr3.clone()); enc } pub fn encode_set(opcode: &[u8], opr1: RM) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = match opr1 { RM::Register(reg) => { if reg.only_in_64bit() { Some(Rex::new(false, false, false, reg.only_in_64bit())) } else { None } } RM::Memory(_) => encode_rex(Some(&opr1), None), }; enc.modrm = Some(encode_modrm(&opr1)); enc.sib = encode_sib(&opr1); enc.disp = encode_disp(&opr1); enc } fn encode_rex(rm: Option<&RM>, reg: Option<&Register>) -> Option<Rex> { let reg_rm = match rm { Some(RM::Register(reg)) => reg, Some(RM::Memory(Memory { base: Some(base), .. })) => base, _ => &Register::Al, }; let reg_reg = reg.unwrap_or(&Register::Al); if reg_rm.size() != register::Size::QWord && reg_reg.size() != register::Size::QWord && !reg_rm.only_in_64bit() && !reg_reg.only_in_64bit() { return None; } Some(Rex::new( true, reg_reg.only_in_64bit(), false, reg_rm.only_in_64bit(), )) } fn encode_modrm(rm: &RM) -> ModRM { match rm { RM::Memory(mem) => match &mem.base { Some(base) => match &mem.disp { None => match base { Register::R12 => ModRM::new(0b00, 0, 0b100), Register::R13 => ModRM::new(0b01, 0, 0b101), _ => ModRM::new(0b00, 0, base.number()), }, Some(Displacement::Disp8(_)) => ModRM::new(0b01, 0, base.number()), Some(Displacement::Disp32(_)) => match base { Register::Rip => ModRM::new(0b00, 0, base.number()), _ => ModRM::new(0b10, 0, base.number()), }, }, None => match mem.disp { None => panic!(), Some(Displacement::Disp8(_)) => panic!(), Some(Displacement::Disp32(_)) => ModRM::new(0b00, 0, 0b100), }, }, RM::Register(reg) => ModRM::new(0b11, 0, reg.number()), } } fn encode_sib(rm: &RM) -> Option<Sib> { match rm { RM::Memory(Memory { base: Some(Register::R12), disp: None, }) => Some(Sib::new(0, 0b100, 0b100)), RM::Memory(Memory { base: None, disp: Some(disp), }) => match disp { Displacement::Disp8(_) => panic!(), Displacement::Disp32(_) => Some(Sib::new(0, 0b100, 0b101)), }, _ => None, } } fn encode_disp(rm: &RM) -> Option<Displacement> { match rm { RM::Memory(Memory { base: Some(Register::R13), disp: None, }) => Some(Displacement::Disp8(0)), RM::Memory(Memory { disp, .. }) => disp.clone(), _ => None, } }
use crate::{ common::{modrm::ModRM, rex::Rex, sib::Sib}, instruction::operand::{ immediate::Immediate, memory::{Displacement, Memory}, offset::Offset, register::{self, Register}, }, }; use super::inst::EncodedInst; pub enum RM<'a> { Register(&'a Register), Memory(&'a Memory), } pub fn encode_m(opcode: &[u8], opr1: RM) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr1), None); enc.modrm = Some(encode_modrm(&opr1)); enc.sib = encode_sib(&opr1); enc.disp = encode_disp(&opr1); enc } pub fn encode_o(opcode: u8, opr1: &Register) -> EncodedInst { let mut enc = EncodedInst::new(&[opcode + opr1.number()]); if opr1.only_in_64bit() { enc.rex = Some(Rex::new(false, false, false, opr1.only_in_64bit())); } enc } pub fn encode_i(opcode: &[u8], opr1: &Immediate) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.imm = Some(opr1.clone()); enc } pub fn encode_d(opcode: &[u8], opr1: &Offset) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.imm = match opr1 { Offset::Off8(value) => Some(Immediate::Imm8(*value)), Offset::Off32(value) => Some(Immediate::Imm32(*value)), }; enc } pub fn encode_mi(opcode: &[u8], opr1: RM, opr2: &Immediate) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr1), None); enc.modrm = Some(encode_modrm(&opr1)); enc.sib = encode_sib(&opr1); enc.disp = encode_disp(&opr1); enc.imm = Some(opr2.clone()); enc } pub fn encode_mr(opcode: &[u8], opr1: RM, opr2: &Register) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr1), Some(opr2)); enc.modrm = Some({ let mut modrm = encode_modrm(&opr1); modrm.reg = opr2.number(); modrm }); enc.sib = encode_sib(&opr1); enc.disp = encode_disp(&opr1); enc } pub fn encode_rm(opcode: &[u8], opr1: &Register, opr2: RM) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr2), Some(opr1)); enc.modrm = Some({ let mut modrm = encode_modrm(&opr2); modrm.reg = opr1.number(); modrm }); enc.sib = encode_sib(&opr2); enc.disp = encode_disp(&opr2); enc } pub fn encode_rmi(opcode: &[u8], opr1: &Register, opr2: RM, opr3: &Immediate) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = encode_rex(Some(&opr2), Some(opr1)); enc.modrm = Some({ let mut modrm = encode_modrm(&opr2); modrm.reg = opr1.number(); modrm }); enc.sib = encode_sib(&opr2); enc.disp = encode_disp(&opr2); enc.imm = Some(opr3.clone()); enc } pub fn encode_set(opcode: &[u8], opr1: RM) -> EncodedInst { let mut enc = EncodedInst::new(opcode); enc.rex = match opr1 { RM::Register(reg) => { if reg.only_in_64bit() { Some(Rex::new(false, false, false, reg.only_in_64bit())) } else { None } } RM::Memory(_) => encode_rex(Some(&opr1), None), }; enc.modrm = Some(encode_modrm(&opr1)); enc.sib = encode_sib(&opr1); enc.disp = encode_disp(&opr1); enc } fn encode_rex(rm: Option<&RM>, reg: Option<&Register>) -> Option<Rex> {
let reg_reg = reg.unwrap_or(&Register::Al); if reg_rm.size() != register::Size::QWord && reg_reg.size() != register::Size::QWord && !reg_rm.only_in_64bit() && !reg_reg.only_in_64bit() { return None; } Some(Rex::new( true, reg_reg.only_in_64bit(), false, reg_rm.only_in_64bit(), )) } fn encode_modrm(rm: &RM) -> ModRM { match rm { RM::Memory(mem) => match &mem.base { Some(base) => match &mem.disp { None => match base { Register::R12 => ModRM::new(0b00, 0, 0b100), Register::R13 => ModRM::new(0b01, 0, 0b101), _ => ModRM::new(0b00, 0, base.number()), }, Some(Displacement::Disp8(_)) => ModRM::new(0b01, 0, base.number()), Some(Displacement::Disp32(_)) => match base { Register::Rip => ModRM::new(0b00, 0, base.number()), _ => ModRM::new(0b10, 0, base.number()), }, }, None => match mem.disp { None => panic!(), Some(Displacement::Disp8(_)) => panic!(), Some(Displacement::Disp32(_)) => ModRM::new(0b00, 0, 0b100), }, }, RM::Register(reg) => ModRM::new(0b11, 0, reg.number()), } } fn encode_sib(rm: &RM) -> Option<Sib> { match rm { RM::Memory(Memory { base: Some(Register::R12), disp: None, }) => Some(Sib::new(0, 0b100, 0b100)), RM::Memory(Memory { base: None, disp: Some(disp), }) => match disp { Displacement::Disp8(_) => panic!(), Displacement::Disp32(_) => Some(Sib::new(0, 0b100, 0b101)), }, _ => None, } } fn encode_disp(rm: &RM) -> Option<Displacement> { match rm { RM::Memory(Memory { base: Some(Register::R13), disp: None, }) => Some(Displacement::Disp8(0)), RM::Memory(Memory { disp, .. }) => disp.clone(), _ => None, } }
let reg_rm = match rm { Some(RM::Register(reg)) => reg, Some(RM::Memory(Memory { base: Some(base), .. })) => base, _ => &Register::Al, };
assignment_statement
[ { "content": "fn add_padding(v: &mut Vec<u8>, offset: usize) {\n\n if offset < v.len() {\n\n return;\n\n }\n\n let padding_len = offset - v.len();\n\n v.extend(&vec![0; padding_len as usize]);\n\n}\n", "file_path": "elfen/src/elf.rs", "rank": 9, "score": 228514.40608285688 }, ...
Rust
yash-semantics/src/lib.rs
magicant/yash-rs
c80497794c126f3d0c378df8a625c69bee0f8567
pub mod assign; mod command_impl; pub mod command_search; pub mod expansion; mod handle_impl; pub mod redir; mod runner; pub mod trap; use annotate_snippets::display_list::DisplayList; use annotate_snippets::snippet::Snippet; use async_trait::async_trait; use std::borrow::Cow; use yash_env::io::Fd; use yash_env::Env; use yash_syntax::source::pretty::Annotation; use yash_syntax::source::pretty::AnnotationType; use yash_syntax::source::pretty::Message; use yash_syntax::source::Location; #[doc(no_inline)] pub use yash_env::semantics::*; #[async_trait(?Send)] pub trait Command { async fn execute(&self, env: &mut Env) -> Result; } #[async_trait(?Send)] pub trait Handle { async fn handle(&self, env: &mut Env) -> Result; } pub async fn print_error( env: &mut Env, title: Cow<'_, str>, label: Cow<'_, str>, location: &Location, ) { let mut a = vec![Annotation { r#type: AnnotationType::Error, label, location: location.clone(), }]; location.line.source.complement_annotations(&mut a); let message = Message { r#type: AnnotationType::Error, title, annotations: a, }; let mut snippet = Snippet::from(&message); snippet.opt.color = true; let s = format!("{}\n", DisplayList::from(snippet)); let _ = env.system.write_all(Fd::STDERR, s.as_bytes()).await; } pub use runner::read_eval_loop; pub use runner::read_eval_loop_boxed; #[cfg(test)] pub(crate) mod tests { use futures_executor::LocalSpawner; use futures_util::task::LocalSpawnExt; use itertools::Itertools; use std::cell::Cell; use std::cell::RefCell; use std::future::ready; use std::future::Future; use std::ops::ControlFlow::{Break, Continue}; use std::pin::Pin; use std::rc::Rc; use yash_env::builtin::Builtin; use yash_env::builtin::Type::{Intrinsic, Special}; use yash_env::io::Fd; use yash_env::job::Pid; use yash_env::semantics::Divert; use yash_env::semantics::ExitStatus; use yash_env::semantics::Field; use yash_env::system::r#virtual::SystemState; use yash_env::system::Errno; use yash_env::variable::Scalar; use yash_env::variable::Scope; use yash_env::variable::Variable; use yash_env::Env; use yash_env::VirtualSystem; #[derive(Clone, Debug)] pub struct LocalExecutor(pub LocalSpawner); impl yash_env::system::r#virtual::Executor for LocalExecutor { fn spawn( &self, task: Pin<Box<dyn Future<Output = ()>>>, ) -> Result<(), Box<dyn std::error::Error>> { self.0 .spawn_local(task) .map_err(|e| Box::new(e) as Box<dyn std::error::Error>) } } pub fn in_virtual_system<F, Fut>(f: F) where F: FnOnce(Env, Pid, Rc<RefCell<SystemState>>) -> Fut, Fut: Future<Output = ()> + 'static, { let system = VirtualSystem::new(); let pid = system.process_id; let state = Rc::clone(&system.state); let mut executor = futures_executor::LocalPool::new(); state.borrow_mut().executor = Some(Rc::new(LocalExecutor(executor.spawner()))); let env = Env::with_system(Box::new(system)); let shared_system = env.system.clone(); let task = f(env, pid, Rc::clone(&state)); let done = Rc::new(Cell::new(false)); let done_2 = Rc::clone(&done); executor .spawner() .spawn_local(async move { task.await; done.set(true); }) .unwrap(); while !done_2.get() { executor.run_until_stalled(); shared_system.select(false).unwrap(); SystemState::select_all(&state); } } fn return_builtin_main( _env: &mut Env, mut args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result>>> { let divert = match args.get(1) { Some(field) if field.value == "-n" => { args.remove(1); Continue(()) } _ => Break(Divert::Return), }; let exit_status = match args.get(1) { Some(field) => field.value.parse().unwrap_or(2), None => 0, }; Box::pin(ready((ExitStatus(exit_status), divert))) } pub fn return_builtin() -> Builtin { Builtin { r#type: Special, execute: return_builtin_main, } } fn local_builtin_main( env: &mut Env, args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result> + '_>> { Box::pin(async move { for Field { value, origin } in args.into_iter().skip(1) { if let Some(eq_index) = value.find('=') { let name = value[..eq_index].to_owned(); let value = value[eq_index + 1..].to_owned(); let value = Variable { value: Scalar(value), last_assigned_location: Some(origin), is_exported: false, read_only_location: None, }; if let Err(error) = env.variables.assign(Scope::Local, name, value) { unimplemented!("assignment error: {:?}", error); } } else { let name = value; if let Some(var) = env.variables.get(&name) { if let Scalar(value) = &var.value { let line = format!("{}={}\n", name, value); if let Err(errno) = env.system.write_all(Fd::STDOUT, line.as_bytes()).await { unimplemented!("write error: {:?}", errno); } } } } } (ExitStatus::SUCCESS, Continue(())) }) } pub fn local_builtin() -> Builtin { Builtin { r#type: Intrinsic, execute: local_builtin_main, } } fn echo_builtin_main( env: &mut Env, args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result> + '_>> { Box::pin(async move { let fields = (&args[1..]).iter().map(|f| &f.value).format(" "); let message = format!("{}\n", fields); let result = match env.system.write_all(Fd::STDOUT, message.as_bytes()).await { Ok(_) => ExitStatus::SUCCESS, Err(_) => ExitStatus::FAILURE, }; (result, Continue(())) }) } pub fn echo_builtin() -> Builtin { Builtin { r#type: Intrinsic, execute: echo_builtin_main, } } fn cat_builtin_main( env: &mut Env, _args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result> + '_>> { async fn inner(env: &mut Env) -> std::result::Result<(), Errno> { let mut buffer = [0; 1024]; loop { let count = env.system.read_async(Fd::STDIN, &mut buffer).await?; if count == 0 { break Ok(()); } env.system.write_all(Fd::STDOUT, &buffer[..count]).await?; } } Box::pin(async move { let result = match inner(env).await { Ok(_) => ExitStatus::SUCCESS, Err(_) => ExitStatus::FAILURE, }; (result, Continue(())) }) } pub fn cat_builtin() -> Builtin { Builtin { r#type: Intrinsic, execute: cat_builtin_main, } } }
pub mod assign; mod command_impl; pub mod command_search; pub mod expansion; mod handle_impl; pub mod redir; mod runner; pub mod trap; use annotate_snippets::display_list::DisplayList; use annotate_snippets::snippet::Snippet; use async_trait::async_trait; use std::borrow::Cow; use yash_env::io::Fd; use yash_env::Env; use yash_syntax::source::pretty::Annotation; use yash_syntax::source::pretty::AnnotationType; use yash_syntax::source::pretty::Message; use yash_syntax::source::Location; #[doc(no_inline)] pub use yash_env::semantics::*; #[async_trait(?Send)] pub trait Command { async fn execute(&self, env: &mut Env) -> Result; } #[async_trait(?Send)] pub trait Handle { async fn handle(&self, env: &mut Env) -> Result; } pub async fn print_error( env: &mut Env, title: Cow<'_, str>, label: Cow<'_, str>, location: &Location, ) { let mut a = vec![Annotation { r#type: AnnotationType::Error, label, location: location.clone(), }]; location.line.source.complement_annotations(&mut a); let message = Message { r#type: AnnotationType::Error, title, annotations: a, }; let mut snippet = Snippet::from(&message); snippet.opt.color = true; let s = format!("{}\n", DisplayList::from(snippet)); let _ = env.system.write_all(Fd::STDERR, s.as_bytes()).await; } pub use runner::read_eval_loop; pub use runner::read_eval_loop_boxed; #[cfg(test)] pub(crate) mod tests { use futures_executor::LocalSpawner; use futures_util::task::LocalSpawnExt; use itertools::Itertools; use std::cell::Cell; use std::cell::RefCell; use std::future::ready; use std::future::Future; use std::ops::ControlFlow::{Break, Continue}; use std::pin::Pin; use std::rc::Rc; use yash_env::builtin::Builtin; use yash_env::builtin::Type::{Intrinsic, Special}; use yash_env::io::Fd; use yash_env::job::Pid; use yash_env::semantics::Divert; use yash_env::semantics::ExitStatus; use yash_env::semantics::Field; use yash_env::system::r#virtual::SystemState; use yash_env::system::Errno; use yash_env::variable::Scalar; use yash_env::variable::Scope; use yash_env::variable::Variable; use yash_env::Env; use yash_env::VirtualSystem; #[derive(Clone, Debug)] pub struct LocalExecutor(pub LocalSpawner); impl yash_env::system::r#virtual::Executor for LocalExecutor { fn spawn( &self, task: Pin<Box<dyn Future<Output = ()>>>, ) -> Result<(), Box<dyn std::error::Error>> { self.0 .spawn_local(task) .map_err(|e| Box::new(e) as Box<dyn std::error::Error>) } } pub fn in_virtual_system<F, Fut>(f: F) where F: FnOnce(Env, Pid, Rc<RefCell<SystemState>>) -> Fut, Fut: Future<Output = ()> + 'static, { let system = VirtualSystem::new(); let pid = system.process_id; let state = Rc::clone(&system.state); let mut executor = futures_executor::LocalPool::new(); state.borrow_mut().executor = Some(Rc::new(LocalExecutor(executor.spawner()))); let env = Env::with_system(Box::new(system)); let shared_system = env.system.clone(); let task = f(env, pid, Rc::clone(&state)); let done = Rc::new(Cell::new(false)); let done_2 = Rc::clone(&done); executor .spawner() .spawn_local(async move { task.await; done.set(true); }) .unwrap(); while !done_2.get() { executor.run_until_stalled(); shared_system.select(false).unwrap(); SystemState::select_all(&state); } } fn return_builtin_main( _env: &mut Env, mut args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result>>> { let divert = match args.get(1) { Some(field) if field.value == "-n" => { args.remove(1); Continue(()) } _ => Break(Divert::Return), }; let exit_status = match args.get(1) { Some(field) => field.value.parse().unwrap_or(2), None => 0, }; Box::pin(ready((ExitStatus(exit_status), divert))) } pub fn return_builtin() -> Builtin { Builtin { r#type: Special, execute: return_builtin_main, } } fn local_builtin_main( env: &mut Env, args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result> + '_>> { Box::pin(async move { for Field { value, origin } in args.into_iter().skip(1) { if let Some(eq_index) = value.find('=') { let name = value[..eq_index].to_owned(); let value = value[eq_index + 1..].to_owned(); let value = Variable { value: Scalar(value), last_assigned_location: Some(origin), is_exported: false, read_only_location: None, }; if let Err(error) = env.variables.assign(Scope::Local, name, value) { unimplemented!("assignment error: {:?}", error); } } else { let name = value; if let Some(var) = env.variables.get(&name) { if let Scalar(value) = &var.value { let line = format!("{}={}\n", name, value); if let Err(errno) = env.system.write_all(Fd::STDOUT, line.as_bytes()).await { unimplemented!("write error: {:?}", errno); } } } } } (ExitStatus::SUCCESS, Continue(())) }) } pub fn local_builtin() -> Builtin { Builtin { r#type: Intrinsic, execute: local_builtin_main, } } fn echo_builtin_main( env: &mut Env, args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result> + '_>> { Box::pin(async move { let fields = (&args[1..]).iter().map(|f| &f.value).format(" "); let message = format!("{}\n", fields); let result = match env.system.write_all(Fd::STDOUT, message.as_bytes()).await { Ok(_) => ExitStatus::SUCCESS, Err(_) => ExitStatus::FAILURE, }; (result, Continue(())) }) }
fn cat_builtin_main( env: &mut Env, _args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result> + '_>> { async fn inner(env: &mut Env) -> std::result::Result<(), Errno> { let mut buffer = [0; 1024]; loop { let count = env.system.read_async(Fd::STDIN, &mut buffer).await?; if count == 0 { break Ok(()); } env.system.write_all(Fd::STDOUT, &buffer[..count]).await?; } } Box::pin(async move { let result = match inner(env).await { Ok(_) => ExitStatus::SUCCESS, Err(_) => ExitStatus::FAILURE, }; (result, Continue(())) }) } pub fn cat_builtin() -> Builtin { Builtin { r#type: Intrinsic, execute: cat_builtin_main, } } }
pub fn echo_builtin() -> Builtin { Builtin { r#type: Intrinsic, execute: echo_builtin_main, } }
function_block-full_function
[ { "content": "/// Implementation of the return built-in.\n\n///\n\n/// See the [module-level documentation](self) for details.\n\npub fn builtin_main_sync<E: Env>(_env: &mut E, args: Vec<Field>) -> Result {\n\n // TODO Parse arguments correctly\n\n // TODO Reject returning from an interactive session\n\n ...
Rust
src/lib.rs
ordovicia/mix-distribution
eb87605c4dd005f5f49ad2b1a6de18bed1a5b51c
use std::{fmt, marker::PhantomData, ops::AddAssign}; use rand::Rng; use rand_distr::{ uniform::{SampleBorrow, SampleUniform}, weighted::{WeightedError, WeightedIndex}, Distribution, }; pub struct Mix<T, U, X> where T: Distribution<U>, X: SampleUniform + PartialOrd, { distributions: Vec<T>, weights: WeightedIndex<X>, _marker: PhantomData<U>, } impl<T, U, X> Mix<T, U, X> where T: Distribution<U>, X: SampleUniform + PartialOrd, { pub fn new<I, J>(dists: I, weights: J) -> Result<Self, WeightedError> where I: IntoIterator<Item = T>, J: IntoIterator, J::Item: SampleBorrow<X>, X: for<'a> AddAssign<&'a X> + Clone + Default, { Ok(Self { distributions: dists.into_iter().collect(), weights: WeightedIndex::new(weights)?, _marker: PhantomData, }) } pub fn with_zip<W>( dists_weights: impl IntoIterator<Item = (T, W)>, ) -> Result<Self, WeightedError> where W: SampleBorrow<X>, X: for<'a> AddAssign<&'a X> + Clone + Default, { let (distributions, weights): (Vec<_>, Vec<_>) = dists_weights.into_iter().unzip(); Ok(Self { distributions, weights: WeightedIndex::new(weights)?, _marker: PhantomData, }) } } impl<T, U, X> Distribution<U> for Mix<T, U, X> where T: Distribution<U>, X: SampleUniform + PartialOrd, { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> U { let idx = self.weights.sample(rng); self.distributions[idx].sample(rng) } } impl<T, U, X> Clone for Mix<T, U, X> where T: Distribution<U> + Clone, X: SampleUniform + PartialOrd + Clone, X::Sampler: Clone, { fn clone(&self) -> Self { Self { distributions: self.distributions.clone(), weights: self.weights.clone(), _marker: PhantomData, } } } impl<T, U, X> fmt::Debug for Mix<T, U, X> where T: Distribution<U> + fmt::Debug, X: SampleUniform + PartialOrd + fmt::Debug, X::Sampler: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Mix") .field("distributions", &self.distributions) .field("weights", &self.weights) .finish() } } #[cfg(test)] mod tests { use super::*; use rand_distr::{Normal, Uniform}; #[test] #[ignore] fn test_mix_plot() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![ Normal::new(0.0, 1.0).unwrap(), Normal::new(5.0, 2.0).unwrap(), ]; let weights = &[2, 1]; Mix::new(dists, weights).unwrap() }; for _ in 0..30000 { println!("{} # mix", mix.sample(&mut rng)); } } #[test] fn test_mix_2() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1)]; let weights = &[2, 1]; Mix::new(dists, weights).unwrap() }; let data = mix.sample_iter(&mut rng).take(300).collect::<Vec<_>>(); let zeros = data.iter().filter(|&&x| x == 0).count(); let ones = data.iter().filter(|&&x| x == 1).count(); assert_eq!(zeros + ones, 300); assert_eq!((zeros as f64 / 100.0).round() as i32, 2); assert_eq!((ones as f64 / 100.0).round() as i32, 1); } #[test] fn test_mix_3() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![ Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1), Uniform::new_inclusive(2, 2), ]; let weights = &[3, 2, 1]; Mix::new(dists, weights).unwrap() }; let data = mix.sample_iter(&mut rng).take(600).collect::<Vec<_>>(); let zeros = data.iter().filter(|&&x| x == 0).count(); let ones = data.iter().filter(|&&x| x == 1).count(); let twos = data.iter().filter(|&&x| x == 2).count(); assert_eq!(zeros + ones + twos, 600); assert_eq!((zeros as f64 / 100.0).round() as i32, 3); assert_eq!((ones as f64 / 100.0).round() as i32, 2); assert_eq!((twos as f64 / 100.0).round() as i32, 1); } #[test] fn test_weight_f64() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1)]; let weights = &[0.4, 0.6]; Mix::new(dists, weights).unwrap() }; let data = mix.sample_iter(&mut rng).take(1000).collect::<Vec<_>>(); let zeros = data.iter().filter(|&&x| x == 0).count(); let ones = data.iter().filter(|&&x| x == 1).count(); assert_eq!(zeros + ones, 1000); assert_eq!((zeros as f64 / 100.0).round() as i32, 4); assert_eq!((ones as f64 / 100.0).round() as i32, 6); } #[test] fn test_zip() { let mut rng = rand::thread_rng(); let mix = Mix::with_zip(vec![ (Uniform::new_inclusive(0, 0), 2), (Uniform::new_inclusive(1, 1), 1), ]) .unwrap(); let data = mix.sample_iter(&mut rng).take(300).collect::<Vec<_>>(); let zeros = data.iter().filter(|&&x| x == 0).count(); let ones = data.iter().filter(|&&x| x == 1).count(); assert_eq!(zeros + ones, 300); assert_eq!((zeros as f64 / 100.0).round() as i32, 2); assert_eq!((ones as f64 / 100.0).round() as i32, 1); } #[test] fn error_invalid_weights() { let dists = vec![Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1)]; let weights = &[2, 1][0..0]; assert_eq!( Mix::new(dists.clone(), weights).unwrap_err(), WeightedError::NoItem, ); let weights = &[2, -1]; assert_eq!( Mix::new(dists.clone(), weights).unwrap_err(), WeightedError::InvalidWeight, ); let weights = &[0, 0]; assert_eq!( Mix::new(dists, weights).unwrap_err(), WeightedError::AllWeightsZero, ); } }
use std::{fmt, marker::PhantomData, ops::AddAssign}; use rand::Rng; use rand_distr::{ uniform::{SampleBorrow, SampleUniform}, weighted::{WeightedError, WeightedIndex}, Distribution, }; pub struct Mix<T, U, X> where T: Distribution<U>, X: SampleUniform + PartialOrd, { distributions: Vec<T>, weights: WeightedIndex<X>, _marker: PhantomData<U>, } impl<T, U, X> Mix<T, U, X> where T: Distribution<U>, X: SampleUniform + PartialOrd, { pub fn new<I, J>(dists: I, weights: J) -> Result<Self, WeightedError> where I: IntoIterator<Item = T>, J: IntoIterator, J::Item: SampleBorrow<X>, X: for<'a> AddAssign<&'a X> + Clone + Default, { Ok(Self { distributions: dists.into_iter().collect(), weights: WeightedIndex::new(weights)?, _marker: PhantomData, }) } pub fn with_zip<W>( dists_weights: impl IntoIterator<Item = (T, W)>, ) -> Result<Self, WeightedError> where W: SampleBorrow<X>, X: for<'a> AddAssign<&'a X> + Clone + Default, { let (distributions, weights): (Vec<_>, Vec<_>) = dists_weights.into_iter().unzip(); Ok(Self { distributions, weights: WeightedIndex::new(weights)?, _marker: PhantomData, }) } } impl<T, U, X> Distribution<U> for Mix<T, U, X> where T: Distribution<U>, X: SampleUniform + PartialOrd, { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> U { let idx = self.weights.sample(rng); self.distributions[idx].sample(rng) } } impl<T, U, X> Clone for Mix<T, U, X> where T: Distribution<U> + Clone, X: SampleUniform + PartialOrd + Clone, X::Sampler: Clone, { fn clone(&self) -> Self { Self { distributions: self.distributions.clone(), weights: self.weights.clone(), _marker: PhantomData, } } } impl<T, U, X> fmt::Debug for Mix<T, U, X> where T: Distribution<U> + fmt::Debug, X: SampleUniform + PartialOrd + fmt::Debug, X::Sampler: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Mix") .field("distributions", &self.distributions) .field("weights", &self.weights) .finish() } } #[cfg(test)] mod tests { use super::*; use rand_distr::{Normal, Uniform}; #[test] #[ignore] fn test_mix_p
} #[test] fn test_mix_2() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1)]; let weights = &[2, 1]; Mix::new(dists, weights).unwrap() }; let data = mix.sample_iter(&mut rng).take(300).collect::<Vec<_>>(); let zeros = data.iter().filter(|&&x| x == 0).count(); let ones = data.iter().filter(|&&x| x == 1).count(); assert_eq!(zeros + ones, 300); assert_eq!((zeros as f64 / 100.0).round() as i32, 2); assert_eq!((ones as f64 / 100.0).round() as i32, 1); } #[test] fn test_mix_3() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![ Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1), Uniform::new_inclusive(2, 2), ]; let weights = &[3, 2, 1]; Mix::new(dists, weights).unwrap() }; let data = mix.sample_iter(&mut rng).take(600).collect::<Vec<_>>(); let zeros = data.iter().filter(|&&x| x == 0).count(); let ones = data.iter().filter(|&&x| x == 1).count(); let twos = data.iter().filter(|&&x| x == 2).count(); assert_eq!(zeros + ones + twos, 600); assert_eq!((zeros as f64 / 100.0).round() as i32, 3); assert_eq!((ones as f64 / 100.0).round() as i32, 2); assert_eq!((twos as f64 / 100.0).round() as i32, 1); } #[test] fn test_weight_f64() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1)]; let weights = &[0.4, 0.6]; Mix::new(dists, weights).unwrap() }; let data = mix.sample_iter(&mut rng).take(1000).collect::<Vec<_>>(); let zeros = data.iter().filter(|&&x| x == 0).count(); let ones = data.iter().filter(|&&x| x == 1).count(); assert_eq!(zeros + ones, 1000); assert_eq!((zeros as f64 / 100.0).round() as i32, 4); assert_eq!((ones as f64 / 100.0).round() as i32, 6); } #[test] fn test_zip() { let mut rng = rand::thread_rng(); let mix = Mix::with_zip(vec![ (Uniform::new_inclusive(0, 0), 2), (Uniform::new_inclusive(1, 1), 1), ]) .unwrap(); let data = mix.sample_iter(&mut rng).take(300).collect::<Vec<_>>(); let zeros = data.iter().filter(|&&x| x == 0).count(); let ones = data.iter().filter(|&&x| x == 1).count(); assert_eq!(zeros + ones, 300); assert_eq!((zeros as f64 / 100.0).round() as i32, 2); assert_eq!((ones as f64 / 100.0).round() as i32, 1); } #[test] fn error_invalid_weights() { let dists = vec![Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1)]; let weights = &[2, 1][0..0]; assert_eq!( Mix::new(dists.clone(), weights).unwrap_err(), WeightedError::NoItem, ); let weights = &[2, -1]; assert_eq!( Mix::new(dists.clone(), weights).unwrap_err(), WeightedError::InvalidWeight, ); let weights = &[0, 0]; assert_eq!( Mix::new(dists, weights).unwrap_err(), WeightedError::AllWeightsZero, ); } }
lot() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![ Normal::new(0.0, 1.0).unwrap(), Normal::new(5.0, 2.0).unwrap(), ]; let weights = &[2, 1]; Mix::new(dists, weights).unwrap() }; for _ in 0..30000 { println!("{} # mix", mix.sample(&mut rng)); }
function_block-random_span
[ { "content": "# Mixture Distributions\n\n\n\n[![Build Status][build-img]][build-link]\n\n[![mix-distribution][cratesio-img]][cratesio-link]\n\n[![mix-distribution][docsrs-img]][docsrs-link]\n\n\n\n[build-img]: https://travis-ci.com/ordovicia/mix-distribution.svg?branch=master\n\n[build-link]: https://travis-ci....
Rust
lib/src/schema.rs
joepio/atomic
10b1e390d807b3defe0ce0f993b160b4ade46359
use crate::{datatype::DataType, errors::AtomicResult, urls, Resource, Value}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Property { pub class_type: Option<String>, pub data_type: DataType, pub shortname: String, pub subject: String, pub description: String, } impl PartialEq for Property { fn eq(&self, other: &Self) -> bool { self.subject == other.subject } } impl Property { pub fn from_resource(resource: Resource) -> AtomicResult<Property> { let data_type = resource.get(urls::DATATYPE_PROP)?.to_string().parse()?; let shortname = resource.get(urls::SHORTNAME)?.to_string(); let description = resource.get(urls::DESCRIPTION)?.to_string(); let class_type = match resource.get(urls::CLASSTYPE_PROP) { Ok(classtype) => Some(classtype.to_string()), Err(_) => None, }; Ok(Property { class_type, data_type, shortname, description, subject: resource.get_subject().into(), }) } pub fn to_resource(&self) -> AtomicResult<Resource> { let mut resource = Resource::new(self.subject.clone()); resource.set_propval_unsafe( urls::IS_A.into(), Value::ResourceArray(vec![urls::PROPERTY.into()]), )?; resource.set_propval_unsafe(urls::SHORTNAME.into(), Value::Slug(self.shortname.clone()))?; resource.set_propval_unsafe( urls::DESCRIPTION.into(), Value::String(self.description.clone()), )?; resource.set_propval_unsafe( urls::DATATYPE_PROP.into(), Value::AtomicUrl(self.data_type.to_string()), )?; if let Some(classtype) = &self.class_type { resource.set_propval_unsafe( urls::CLASSTYPE_PROP.into(), Value::AtomicUrl(classtype.clone()), )?; } Ok(resource) } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Class { pub requires: Vec<String>, pub recommends: Vec<String>, pub shortname: String, pub description: String, pub subject: String, } impl Class { pub fn from_resource(resource: Resource) -> AtomicResult<Class> { let mut requires = Vec::new(); if let Ok(reqs) = resource.get(urls::REQUIRES) { for prop_sub in reqs.to_vec()? { requires.push(prop_sub.clone()) } } let mut recommends = Vec::new(); if let Ok(recs) = resource.get(urls::RECOMMENDS) { for rec_subject in recs.to_vec()? { recommends.push(rec_subject.clone()) } } let shortname = resource.get(urls::SHORTNAME)?.to_string(); let description = resource.get(urls::DESCRIPTION)?.to_string(); Ok(Class { requires, recommends, shortname, subject: resource.get_subject().into(), description, }) } pub fn to_resource(&self) -> AtomicResult<Resource> { let mut resource = Resource::new(self.subject.clone()); resource.set_propval_unsafe( urls::IS_A.into(), Value::ResourceArray(vec![urls::CLASS.into()]), )?; resource.set_propval_unsafe(urls::SHORTNAME.into(), Value::Slug(self.shortname.clone()))?; resource.set_propval_unsafe( urls::DESCRIPTION.into(), Value::String(self.description.clone()), )?; if !self.requires.is_empty() { resource.set_propval_unsafe( urls::REQUIRES.into(), Value::ResourceArray(self.requires.clone()), )?; } if !self.requires.is_empty() { resource.set_propval_unsafe( urls::RECOMMENDS.into(), Value::ResourceArray(self.recommends.clone()), )?; } Ok(resource) } }
use crate::{datatype::DataType, errors::AtomicResult, urls, Resource, Value}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Property { pub class_type: Option<String>, pub data_type: DataType, pub shortname: String, pub subject: String, pub description: String, } impl PartialEq for Property { fn eq(&self, other: &Self) -> bool { self.subject == other.subject } } impl Property { pub fn from_resource(resource: Resource) -> AtomicResult<Property> { let data_type = resource.get(urls::DATATYPE_PROP)?.to_string().parse()?; let shortname = resource.get(urls::SHORTNAME)?.to_string(); let description = resource.get(urls::DESCRIPTION)?.to_string(); let class_type = match resource.get(urls::CLASSTYPE_PROP) { Ok(classtype) => Some(classtype.to_string()), Err(_) => None, }; Ok(Property { class_type, data_type, shortname, description, subject: resource.get_subject().into(), }) } pub fn to_resource(&self) -> AtomicResult<Resource> { let mut resource = Resource::new(self.subject.clone()); resource.set_propval_unsafe( urls::IS_A.into(), Value::ResourceArray(vec![urls::PROPERTY.into()]), )?; resource.set_propval_unsafe(urls::SHORTNAME.into(), Value::Slug(self.shortname.clone()))?; resource.set_propval_unsafe( urls::DESCRIPTION.into(), Value::String(self.description.clone()), )?; resource.set_propval_unsafe( urls::DATATYPE_PROP.into(), Value::AtomicUrl(self.data_type.to_string()), )?; if let Some(classtype) = &self.class_type { resource.set_propval_unsafe( urls::CLASSTYPE_PROP.into(), Value::AtomicUrl(classtype.clone()), )?; } Ok(resource) } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Class { pub requires: Vec<String>, pub recommends: Vec<String>, pub shortname: String, pub description: String, pub subject: String, } impl Class { pub fn from_resource(resource: Resource) -> AtomicResult<Class> { let mut requires = Vec::new(); if let Ok(reqs) = resource.get(urls::REQUIRES) { for prop_sub in reqs.to_vec()? { requires.push(prop_sub.clone()) } } let mut recommends = Vec::new(); if let Ok(recs) = resource.get(urls::RECOMMENDS) { for rec_subject in recs.to_vec()? { recommends.push(rec_subject.clone()) } } let shortname = resource.get(urls::SHORTNAME)?.to_string(); let description = resource.get(urls::DESCRIPTION)?.to_string(); Ok(Class { requires, recommends, shortname, subject: resource.get_subject().into(), description, }) } pub fn to_resource(&self) -> AtomicResult<Resource> { let mut resource = Resource::new(self.subject.clone()); resource.set_propval_unsafe( urls::IS_A.into(), Value::ResourceArray(vec![urls::CLASS.into()]), )?; resource.set_propval_unsafe(urls::SHORTNAME.into(), Value::Slug(self.shortname.clone()))?; resource.set_propval_unsafe( urls::DESCRIPTION.into(), Value::String(self.description.clone()), )?; if !self.requires.is_empty() { resource.set_propval_unsafe( urls::REQUIRES.into(), Value::ResourceArray(self.requires.clone()), )?; }
Ok(resource) } }
if !self.requires.is_empty() { resource.set_propval_unsafe( urls::RECOMMENDS.into(), Value::ResourceArray(self.recommends.clone()), )?; }
if_condition
[ { "content": "/// Check if something is a URL\n\npub fn is_url(string: &str) -> bool {\n\n // TODO: Probably delete this second one, might break some tests though.\n\n string.starts_with(\"http\") || string.starts_with(\"_:\")\n\n}\n\n\n\nimpl IntoIterator for Mapping {\n\n type Item = (String, String)...
Rust
2019/intcode.rs
yishn/adventofcode2016
4aa4d7c36921f88fbfc617293372b3b814fd9912
#[derive(Clone)] pub struct ProgramState(Vec<i64>, usize, usize); impl ProgramState { pub fn new(program: Vec<i64>) -> ProgramState { ProgramState(program, 0, 0) } pub fn get_mut(&mut self) -> (&mut Vec<i64>, &mut usize, &mut usize) { (&mut self.0, &mut self.1, &mut self.2) } } #[derive(Debug, Copy, Clone)] pub enum ProgramResult { Output(i64), WaitForInput, Halt, } #[derive(Debug)] enum ParameterMode { Position, Immediate, Relative } #[derive(Debug)] enum OperationType { Add, Multiply, Input, Output, JumpIfTrue, JumpIfFalse, LessThan, Equals, SetRelativeBase, Halt } #[derive(Debug)] struct Instruction { operation: OperationType, inputs: Vec<(ParameterMode, i64)> } fn parse_instruction(numbers: &[i64]) -> Instruction { let instruction_code = numbers[0]; let op_code = instruction_code % 100; let (operation, inputs_count) = match op_code { 1 => (OperationType::Add, 3), 2 => (OperationType::Multiply, 3), 3 => (OperationType::Input, 1), 4 => (OperationType::Output, 1), 5 => (OperationType::JumpIfTrue, 2), 6 => (OperationType::JumpIfFalse, 2), 7 => (OperationType::LessThan, 3), 8 => (OperationType::Equals, 3), 9 => (OperationType::SetRelativeBase, 1), 99 => (OperationType::Halt, 0), _ => panic!("Unsupported operation code {}", instruction_code) }; let get_parameter_mode = |i| { match (instruction_code - op_code) / 10i64.pow(2 + i as u32) % 10 { 0 => ParameterMode::Position, 1 => ParameterMode::Immediate, 2 => ParameterMode::Relative, _ => panic!() } }; Instruction { operation, inputs: (0..inputs_count) .map(|i| (get_parameter_mode(i), numbers[i + 1])) .collect() } } pub fn run_program(state: &mut ProgramState, input: Option<i64>) -> ProgramResult { let (program, pointer, relative_base) = state.get_mut(); let mut input = input; fn extend_memory(program: &mut Vec<i64>, index: usize) { while index >= program.len() { program.push(0); } } fn get_instruction_input_index( program: &mut Vec<i64>, instruction: &Instruction, relative_base: usize, index: usize ) -> usize { match instruction.inputs[index] { (ParameterMode::Relative, d) => { let j = (relative_base as i64 + d) as usize; extend_memory(program, j); j }, (_, j) => { extend_memory(program, j as usize); j as usize } } } fn get_instruction_input( program: &mut Vec<i64>, instruction: &Instruction, relative_base: usize, index: usize ) -> i64 { match instruction.inputs[index] { (ParameterMode::Immediate, value) => value, _ => { let j = get_instruction_input_index(program, instruction, relative_base, index); program[j] } } } while *pointer < program.len() { let init_pointer = *pointer; let instruction = parse_instruction(&program[*pointer..]); let (target_value, target_index) = { let mut get_input = |i| { get_instruction_input(program, &instruction, *relative_base, i) }; let (target_value, output_index) = match instruction.operation { OperationType::Add => (Some(get_input(0) + get_input(1)), Some(2)), OperationType::Multiply => (Some(get_input(0) * get_input(1)), Some(2)), OperationType::Input => match input { Some(x) => { input = None; (Some(x), Some(0)) }, _ => return ProgramResult::WaitForInput }, OperationType::Output => (Some(get_input(0)), None), OperationType::LessThan => (Some((get_input(0) < get_input(1)) as i64), Some(2)), OperationType::Equals => (Some((get_input(0) == get_input(1)) as i64), Some(2)), OperationType::JumpIfTrue => { if get_input(0) != 0 { *pointer = get_input(1) as usize; } (None, None) }, OperationType::JumpIfFalse => { if get_input(0) == 0 { *pointer = get_input(1) as usize; } (None, None) }, OperationType::SetRelativeBase => { *relative_base = (*relative_base as i64 + get_input(0)) as usize; (None, None) } OperationType::Halt => break }; ( target_value, output_index.map(|i| { get_instruction_input_index(program, &instruction, *relative_base, i) }) ) }; if *pointer == init_pointer { *pointer += instruction.inputs.len() + 1; } if let Some(target_value) = target_value { if let Some(target_index) = target_index { extend_memory(program, target_index); program[target_index] = target_value; } else { return ProgramResult::Output(target_value); } } } ProgramResult::Halt } pub fn run_program_with_inputs<I>(state: &mut ProgramState, inputs: I) -> (Vec<i64>, ProgramResult) where I: Iterator<Item = i64> { let mut inputs = inputs; let mut outputs = vec![]; let mut result = run_program(state, None); loop { if let ProgramResult::Output(x) = result { outputs.push(x); } result = run_program(state, match result { ProgramResult::WaitForInput => match inputs.next() { Some(x) => Some(x), None => break }, _ => None }); if let ProgramResult::Halt = result { break; } } (outputs, result) } pub fn run_ascii_program_with_input(state: &mut ProgramState, input: &str) -> (String, ProgramResult) { let inputs = input.chars().map(|c| c as i64); let (outputs, result) = run_program_with_inputs(state, inputs); let output = outputs.into_iter() .map(|x| x as u8 as char) .fold(String::new(), |mut acc, x| { acc.push(x); acc }); (output, result) }
#[derive(Clone)] pub struct ProgramState(Vec<i64>, usize, usize); impl ProgramState { pub fn new(program: Vec<i64>) -> ProgramState { ProgramState(program, 0, 0) } pub fn get_mut(&mut self) -> (&mut Vec<i64>, &mut usize, &mut usize) { (&mut self.0, &mut self.1, &mut self.2) } } #[derive(Debug, Copy, Clone)] pub enum ProgramResult { Output(i64), WaitForInput, Halt, } #[derive(Debug)] enum ParameterMode { Position, Immediate, Relative } #[derive(Debug)] enum OperationType { Add, Multiply, Input, Output, JumpIfTrue, JumpIfFalse, LessThan, Equals, SetRelativeBase, Halt } #[derive(Debug)] struct Instruction { operation: OperationType, inputs: Vec<(ParameterMode, i64)> } fn parse_instruction(numbers: &[i64]) -> Instruction { let instruction_code = numbers[0]; let op_code = instruction_code % 100; let (operation, inputs_count) = match op_code { 1 => (OperationType::Add, 3), 2 => (OperationType::Multiply, 3), 3 => (OperationType::Input, 1), 4 => (OperationType::Output, 1), 5 => (OperationType::JumpIfTrue, 2), 6 => (OperationType::JumpIfFalse, 2), 7 => (OperationType::LessThan, 3), 8 => (OperationType::Equals, 3), 9 => (OperationType::SetRelativeBase, 1), 99 => (OperationType::Halt, 0), _ => panic!("Unsupported operation code {}", instruction_code) }; let get_parameter_mode = |i| { match (instruction_code - op_code) / 10i64.pow(2 + i as u32) % 10 { 0 => ParameterMode::Position, 1 => ParameterMode::Immediate, 2 => ParameterMode::Relative, _ => panic!() } }; Instruction { operation, inputs: (0..inputs_count) .map(|i| (get_parameter_mode(i), numbers[i + 1])) .collect() } } pub fn run_program(state: &mut ProgramState, input: Option<i64>) -> ProgramResult { let (program, pointer, relative_base) = state.get_mut(); let mut input = input; fn extend_memory(program: &mut Vec<i64>, index: usize) { while index >= program.len() { program.push(0); } } fn get_instruction_input_index( program: &mut Vec<i64>, instruction: &Instruction, relative_base: usize, index: usize ) -> usize { match instruction.inputs[index] { (ParameterMode::Relative, d) => { let j = (relative_base as i64 + d) as usize; extend_memory(program, j); j }, (_, j) => { extend_memory(program, j as usize); j as usize } } } fn get_instruction_input( program: &mut Vec<i64>, instruction: &Instruction, relative_base: usize, index: usize ) -> i64 { match instruction.inputs[index] { (ParameterMode::Immediate, value) => value, _ => { let j = get_instruction_input_index(program, instruction, relative_base, index); program[j] } } } while *pointer < program.len() { let init_pointer = *pointer; let instruction = parse_instruction(&program[*pointer..]); let (target_value, target_index) = { let mut get_input = |i| { get_instruction_input(program, &instruction, *relative_base, i) }; let (target_value, output_index) = match instruction.operation { OperationType::Add => (Some(get_input(0) + get_input(1)), Some(2)), OperationType::Multiply => (Some(get_input(0) * get_input(1)), Some(2)), OperationType::Input => match input { Some(x) => { input = None; (Some(x), Some(0)) }, _ => return ProgramResult::WaitForInput }, OperationType::Output => (Some(get_input(0)), None), OperationType::LessThan => (Some((get_input(0) < get_input(1)) as i64), Some(2)), OperationType::Equals => (Some((get_input(0) == get_input(1)) as i64), Some(2)), OperationType::JumpIfTrue => { if get_input(0) != 0 { *pointer = get_input(1) as usize; } (None, None) }, OperationType::JumpIfFalse => { if get_input(0) == 0 { *pointer = get_input(1) as usize; } (None, None) }, OperationType::SetRelativeBase => { *relative_base = (*relative_base as i64 + get_input(0)) as usize; (None, None) } OperationType::Halt => break }; ( target_value, output_index.map(|i| { get_instruction_input_index(program, &instruction, *relative_base, i) }) ) }; if *pointer == init_pointer { *pointer += instruction.inputs.len() + 1; } if let Some(target_value) = target_value { if let Some(target_index) = target_index { extend_memory(program, target_index); program[target_index] = target_value; } else { return ProgramResult::Output(target_value); } } } ProgramResult::Halt } pub fn run_program_with_inputs<I>(state: &mut ProgramState, inputs: I) -> (Vec<i64>, ProgramResult) where I: Iterator<Item = i64> { let mut inputs = inputs; let mut outputs = vec![]; let mut result = run_program(state, None); loop { if let ProgramResult::Output(x) = result { outputs.push(x); } result = run_program(state, match result { ProgramResult::WaitForInput => match inputs.next() { Some(x) => Some(x), None => break }, _ => None }); if let ProgramResult::Halt = result { break; } } (outputs, result) }
pub fn run_ascii_program_with_input(state: &mut ProgramState, input: &str) -> (String, ProgramResult) { let inputs = input.chars().map(|c| c as i64); let (outputs, result) = run_program_with_inputs(state, inputs); let output = outputs.into_iter() .map(|x| x as u8 as char) .fold(String::new(), |mut acc, x| { acc.push(x); acc }); (output, result) }
function_block-full_function
[ { "content": "fn run_program(state: (&mut Vec<i64>, &mut usize, &mut usize), input: Option<i64>) -> ProgramResult {\n\n let (program, pointer, relative_base) = state;\n\n let mut input = input;\n\n\n\n fn extend_memory(program: &mut Vec<i64>, index: usize) {\n\n while index >= program.len() {\n\n pro...
Rust
src/cpu.rs
ZacJoffe/chip8-emulator
2ab341a403f204ccbf3ad8dffecaf4f1f7ae0c75
extern crate rand; use rand::Rng; use crate::keypad::Keypad; use crate::graphics::Graphics; pub struct Cpu { i: u16, v: [u8; 16], pc: u16, sp: u16, stack: [u16; 16], mem: [u8; 4096], sound_timer: u8, delay_timer: u8, opcode: u16, pub key: Keypad, pub graphics: Graphics } impl Cpu { pub fn new() -> Cpu { let mut cpu = Cpu { i: 0x200, v: [0; 16], pc: 0x200, sp: 0, stack: [0; 16], mem: [0; 4096], sound_timer: 0, delay_timer: 0, opcode: 0, key: Keypad::new(), graphics: Graphics::new() }; for i in 0..80 { cpu.mem[0x50 + i] = FONTSET[i]; } cpu } pub fn load_game(&mut self, game: Vec<u8>) { let mut data = Vec::new(); for byte in game { data.push(byte); } for (i, &byte) in data.iter().enumerate() { self.mem[i + 0x200] = byte; } } pub fn emulate_cycle(&mut self) { self.opcode = (self.mem[self.pc as usize] as u16) << 8 | (self.mem[(self.pc as usize) + 1] as u16); println!("{:x}", self.opcode); match self.opcode & 0xf000 { 0x0000 => self.instr_0(), 0x1000 => self.instr_1(), 0x2000 => self.instr_2(), 0x3000 => self.instr_3(), 0x4000 => self.instr_4(), 0x5000 => self.instr_5(), 0x6000 => self.instr_6(), 0x7000 => self.instr_7(), 0x8000 => self.instr_8(), 0x9000 => self.instr_9(), 0xa000 => self.instr_a(), 0xb000 => self.instr_b(), 0xc000 => self.instr_c(), 0xd000 => self.instr_d(), 0xe000 => self.instr_e(), 0xf000 => self.instr_f(), _ => self.nop() } if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { if self.sound_timer == 1 { println!("BEEP!"); } self.sound_timer -= 1; } } fn instr_0(&mut self) { match self.opcode & 0x00ff { 0xe0 => self.graphics.clear(), 0xee => { self.sp -= 1; self.pc = self.stack[self.sp as usize]; } _ => self.nop() } self.pc += 2; } fn instr_1(&mut self) { self.pc = self.opcode_nnn(); } fn instr_2(&mut self) { self.stack[self.sp as usize] = self.pc; self.sp += 1; self.pc = self.opcode_nnn(); } fn instr_3(&mut self) { if self.v[self.opcode_x()] == self.opcode_nn() { self.pc += 4; } else { self.pc += 2; } } fn instr_4(&mut self) { if self.v[self.opcode_x()] != self.opcode_nn() { self.pc += 4; } else { self.pc += 2; } } fn instr_5(&mut self) { if self.v[self.opcode_x()] == self.v[self.opcode_y()] { self.pc += 4; } else { self.pc += 2; } } fn instr_6(&mut self) { self.v[self.opcode_x()] = self.opcode_nn(); self.pc += 2; } fn instr_7(&mut self) { self.v[self.opcode_x()] = self.v[self.opcode_x()].wrapping_add(self.opcode_nn()); self.pc += 2; } fn instr_8(&mut self) { match self.opcode & 0x000f { 0 => self.v[self.opcode_x()] = self.v[self.opcode_y()], 1 => self.v[self.opcode_x()] = self.v[self.opcode_x()] | self.v[self.opcode_y()], 2 => self.v[self.opcode_x()] = self.v[self.opcode_x()] & self.v[self.opcode_y()], 3 => self.v[self.opcode_x()] = self.v[self.opcode_x()] ^ self.v[self.opcode_y()], 4 => { if self.v[self.opcode_x()] > 0xff - self.v[self.opcode_y()] { self.v[0xf] = 1; } else { self.v[0xf] = 0; } self.v[self.opcode_x()] = self.v[self.opcode_x()].wrapping_add(self.v[self.opcode_y()]); } 5 => { if self.v[self.opcode_y()] > self.v[self.opcode_x()] { self.v[0xf] = 0; } else { self.v[0xf] = 1; } self.v[self.opcode_x()] = self.v[self.opcode_x()].wrapping_sub(self.v[self.opcode_y()]); } 6 => { self.v[0xf] = self.v[self.opcode_x()] & 0x1; self.v[self.opcode_x()] >>= 1; } 7 => { if self.v[self.opcode_x()] > self.v[self.opcode_y()] { self.v[0xf] = 0; } else { self.v[0xf] = 1; } self.v[self.opcode_x()] = self.v[self.opcode_y()].wrapping_sub(self.v[self.opcode_x()]); } 0xe => { self.v[0xf] = self.v[self.opcode_x()] >> 7; self.v[self.opcode_x()] <<= 1; } _ => self.nop() } self.pc += 2; } fn instr_9(&mut self) { if self.v[self.opcode_x()] != self.v[self.opcode_y()] { self.pc += 4; } else { self.pc += 2; } } fn instr_a(&mut self) { self.i = self.opcode_nnn(); self.pc += 2; } fn instr_b(&mut self) { self.pc = (self.v[0] as u16) + self.opcode_nnn(); } fn instr_c(&mut self) { let mut rng = rand::thread_rng(); let random_num: u8 = rng.gen(); self.v[self.opcode_x()] = random_num & self.opcode_nn(); self.pc += 2; } fn instr_d(&mut self) { let x = self.opcode_x(); let y = self.opcode_y(); let n = self.opcode_n(); self.v[15] = self.graphics.update(self.v[x] as usize, self.v[y] as usize, n, self.i, self.mem); self.pc += 2; } fn instr_e(&mut self) { match (self.opcode & 0x00ff) as u8 { 0x9e => { if self.key.is_pressed(self.v[self.opcode_x()] as usize) { self.pc += 4; } else { self.pc += 2; } } 0xa1 => { if !self.key.is_pressed(self.v[self.opcode_x()] as usize) { self.pc += 4; } else { self.pc += 2; } } _ => self.nop() } } fn instr_f(&mut self) { match self.opcode & 0x00ff { 0x07 => self.v[self.opcode_x()] = self.delay_timer, 0x0a => { let mut pressed: bool = false; for i in 0..16 { if self.key.is_pressed(i as usize) { self.v[self.opcode_x()] = i; pressed = true; } } if !pressed { self.pc -= 2; } } 0x15 => self.delay_timer = self.v[self.opcode_x()], 0x18 => self.sound_timer = self.v[self.opcode_x()], 0x1e => { if self.v[self.opcode_x()] as u16 + self.i > 0x0fff { self.v[0xf] = 1; } else { self.v[0xf] = 0; } self.i = self.i.wrapping_add(self.v[self.opcode_x()] as u16); } 0x29 => self.i = (self.v[self.opcode_x()] as u16 * 5) + 0x50, 0x33 => { self.mem[self.i as usize] = self.v[self.opcode_x() as usize] / 100; self.mem[(self.i + 1) as usize] = (self.v[self.opcode_x() as usize] / 10) % 10; self.mem[(self.i + 2) as usize] = self.v[self.opcode_x() as usize] % 10; } 0x55 => { for i in 0..self.opcode_x() { self.mem[i + self.i as usize] = self.v[i]; } self.i += self.opcode_x() as u16 + 1; } 0x65 => { for i in 0..(self.opcode_x() + 1) { self.v[i] = self.mem[i + self.i as usize]; } self.i += self.opcode_x() as u16 + 1; } _ => self.nop() } self.pc += 2; } fn nop(&self) { println!("Nop instruction"); } fn opcode_x(&self) -> usize { ((self.opcode & 0x0f00) >> 8) as usize } fn opcode_y(&self) -> usize { ((self.opcode & 0x00f0) >> 4) as usize } fn opcode_n(&self) -> u8 { (self.opcode & 0x000f) as u8 } fn opcode_nn(&self) -> u8 { (self.opcode & 0x00ff) as u8 } fn opcode_nnn(&self) -> u16 { (self.opcode & 0x0fff) as u16 } } const FONTSET: [u8; 80] = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0, 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, 0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, 0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0, 0x10, 0xF0, 0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0, 0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80 ];
extern crate rand; use rand::Rng; use crate::keypad::Keypad; use crate::graphics::Graphics; pub struct Cpu { i: u16, v: [u8; 16], pc: u16, sp: u16, stack: [u16; 16], mem: [u8; 4096], sound_timer: u8, delay_timer: u8, opcode: u16, pub key: Keypad, pub graphics: Graphics } impl Cpu { pub fn new() -> Cpu {
for i in 0..80 { cpu.mem[0x50 + i] = FONTSET[i]; } cpu } pub fn load_game(&mut self, game: Vec<u8>) { let mut data = Vec::new(); for byte in game { data.push(byte); } for (i, &byte) in data.iter().enumerate() { self.mem[i + 0x200] = byte; } } pub fn emulate_cycle(&mut self) { self.opcode = (self.mem[self.pc as usize] as u16) << 8 | (self.mem[(self.pc as usize) + 1] as u16); println!("{:x}", self.opcode); match self.opcode & 0xf000 { 0x0000 => self.instr_0(), 0x1000 => self.instr_1(), 0x2000 => self.instr_2(), 0x3000 => self.instr_3(), 0x4000 => self.instr_4(), 0x5000 => self.instr_5(), 0x6000 => self.instr_6(), 0x7000 => self.instr_7(), 0x8000 => self.instr_8(), 0x9000 => self.instr_9(), 0xa000 => self.instr_a(), 0xb000 => self.instr_b(), 0xc000 => self.instr_c(), 0xd000 => self.instr_d(), 0xe000 => self.instr_e(), 0xf000 => self.instr_f(), _ => self.nop() } if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { if self.sound_timer == 1 { println!("BEEP!"); } self.sound_timer -= 1; } } fn instr_0(&mut self) { match self.opcode & 0x00ff { 0xe0 => self.graphics.clear(), 0xee => { self.sp -= 1; self.pc = self.stack[self.sp as usize]; } _ => self.nop() } self.pc += 2; } fn instr_1(&mut self) { self.pc = self.opcode_nnn(); } fn instr_2(&mut self) { self.stack[self.sp as usize] = self.pc; self.sp += 1; self.pc = self.opcode_nnn(); } fn instr_3(&mut self) { if self.v[self.opcode_x()] == self.opcode_nn() { self.pc += 4; } else { self.pc += 2; } } fn instr_4(&mut self) { if self.v[self.opcode_x()] != self.opcode_nn() { self.pc += 4; } else { self.pc += 2; } } fn instr_5(&mut self) { if self.v[self.opcode_x()] == self.v[self.opcode_y()] { self.pc += 4; } else { self.pc += 2; } } fn instr_6(&mut self) { self.v[self.opcode_x()] = self.opcode_nn(); self.pc += 2; } fn instr_7(&mut self) { self.v[self.opcode_x()] = self.v[self.opcode_x()].wrapping_add(self.opcode_nn()); self.pc += 2; } fn instr_8(&mut self) { match self.opcode & 0x000f { 0 => self.v[self.opcode_x()] = self.v[self.opcode_y()], 1 => self.v[self.opcode_x()] = self.v[self.opcode_x()] | self.v[self.opcode_y()], 2 => self.v[self.opcode_x()] = self.v[self.opcode_x()] & self.v[self.opcode_y()], 3 => self.v[self.opcode_x()] = self.v[self.opcode_x()] ^ self.v[self.opcode_y()], 4 => { if self.v[self.opcode_x()] > 0xff - self.v[self.opcode_y()] { self.v[0xf] = 1; } else { self.v[0xf] = 0; } self.v[self.opcode_x()] = self.v[self.opcode_x()].wrapping_add(self.v[self.opcode_y()]); } 5 => { if self.v[self.opcode_y()] > self.v[self.opcode_x()] { self.v[0xf] = 0; } else { self.v[0xf] = 1; } self.v[self.opcode_x()] = self.v[self.opcode_x()].wrapping_sub(self.v[self.opcode_y()]); } 6 => { self.v[0xf] = self.v[self.opcode_x()] & 0x1; self.v[self.opcode_x()] >>= 1; } 7 => { if self.v[self.opcode_x()] > self.v[self.opcode_y()] { self.v[0xf] = 0; } else { self.v[0xf] = 1; } self.v[self.opcode_x()] = self.v[self.opcode_y()].wrapping_sub(self.v[self.opcode_x()]); } 0xe => { self.v[0xf] = self.v[self.opcode_x()] >> 7; self.v[self.opcode_x()] <<= 1; } _ => self.nop() } self.pc += 2; } fn instr_9(&mut self) { if self.v[self.opcode_x()] != self.v[self.opcode_y()] { self.pc += 4; } else { self.pc += 2; } } fn instr_a(&mut self) { self.i = self.opcode_nnn(); self.pc += 2; } fn instr_b(&mut self) { self.pc = (self.v[0] as u16) + self.opcode_nnn(); } fn instr_c(&mut self) { let mut rng = rand::thread_rng(); let random_num: u8 = rng.gen(); self.v[self.opcode_x()] = random_num & self.opcode_nn(); self.pc += 2; } fn instr_d(&mut self) { let x = self.opcode_x(); let y = self.opcode_y(); let n = self.opcode_n(); self.v[15] = self.graphics.update(self.v[x] as usize, self.v[y] as usize, n, self.i, self.mem); self.pc += 2; } fn instr_e(&mut self) { match (self.opcode & 0x00ff) as u8 { 0x9e => { if self.key.is_pressed(self.v[self.opcode_x()] as usize) { self.pc += 4; } else { self.pc += 2; } } 0xa1 => { if !self.key.is_pressed(self.v[self.opcode_x()] as usize) { self.pc += 4; } else { self.pc += 2; } } _ => self.nop() } } fn instr_f(&mut self) { match self.opcode & 0x00ff { 0x07 => self.v[self.opcode_x()] = self.delay_timer, 0x0a => { let mut pressed: bool = false; for i in 0..16 { if self.key.is_pressed(i as usize) { self.v[self.opcode_x()] = i; pressed = true; } } if !pressed { self.pc -= 2; } } 0x15 => self.delay_timer = self.v[self.opcode_x()], 0x18 => self.sound_timer = self.v[self.opcode_x()], 0x1e => { if self.v[self.opcode_x()] as u16 + self.i > 0x0fff { self.v[0xf] = 1; } else { self.v[0xf] = 0; } self.i = self.i.wrapping_add(self.v[self.opcode_x()] as u16); } 0x29 => self.i = (self.v[self.opcode_x()] as u16 * 5) + 0x50, 0x33 => { self.mem[self.i as usize] = self.v[self.opcode_x() as usize] / 100; self.mem[(self.i + 1) as usize] = (self.v[self.opcode_x() as usize] / 10) % 10; self.mem[(self.i + 2) as usize] = self.v[self.opcode_x() as usize] % 10; } 0x55 => { for i in 0..self.opcode_x() { self.mem[i + self.i as usize] = self.v[i]; } self.i += self.opcode_x() as u16 + 1; } 0x65 => { for i in 0..(self.opcode_x() + 1) { self.v[i] = self.mem[i + self.i as usize]; } self.i += self.opcode_x() as u16 + 1; } _ => self.nop() } self.pc += 2; } fn nop(&self) { println!("Nop instruction"); } fn opcode_x(&self) -> usize { ((self.opcode & 0x0f00) >> 8) as usize } fn opcode_y(&self) -> usize { ((self.opcode & 0x00f0) >> 4) as usize } fn opcode_n(&self) -> u8 { (self.opcode & 0x000f) as u8 } fn opcode_nn(&self) -> u8 { (self.opcode & 0x00ff) as u8 } fn opcode_nnn(&self) -> u16 { (self.opcode & 0x0fff) as u16 } } const FONTSET: [u8; 80] = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0, 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, 0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, 0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0, 0x10, 0xF0, 0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0, 0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80 ];
let mut cpu = Cpu { i: 0x200, v: [0; 16], pc: 0x200, sp: 0, stack: [0; 16], mem: [0; 4096], sound_timer: 0, delay_timer: 0, opcode: 0, key: Keypad::new(), graphics: Graphics::new() };
assignment_statement
[ { "content": "fn main() {\n\n let mut cpu = Cpu::new();\n\n let args: Vec<String> = env::args().collect();\n\n\n\n // if no arg is given, then default to pong2.c8\n\n let mut rom = if args.len() < 2 { String::from(\"pong2.c8\") } else { String::from(&args[1]) };\n\n rom = format!(\"roms/{}\", ro...
Rust
src/timers.rs
david-sawatzke/swm050-hal
95cec73c1b15475ded314bd4ed1f517085838f9a
use core::ops::Deref; use embedded_hal::timer::{Cancel, CountDown, Periodic}; use void::Void; use crate::delay::Delay; use crate::syscon::{ClockEnable, Clocks, Syscon}; use crate::time::Hertz; pub(crate) type TimerRegisterBlock = swm050::tmrse0::RegisterBlock; pub struct Timer<TIMER> { clocks: Clocks, pub(crate) timer: TIMER, } impl<TIMER> Timer<TIMER> where TIMER: Deref<Target = TimerRegisterBlock> + ClockEnable, { pub fn timer<T>(timer: TIMER, timeout: T, syscon: &mut Syscon) -> Timer<TIMER> where T: Into<Hertz>, { TIMER::enable(syscon); timer.intctrl.write(|w| w.ena().set_bit()); let mut timer = Timer { timer: timer, clocks: syscon.clocks, }; timer.start(timeout); timer } pub fn release(self) -> TIMER { self.timer } } impl<TIMER> CountDown for Timer<TIMER> where TIMER: Deref<Target = TimerRegisterBlock>, { type Time = Hertz; fn start<T>(&mut self, timeout: T) where T: Into<Hertz>, { self.timer.ctrl.write(|w| w.ena().clear_bit()); self.timer.intoflag.write(|w| unsafe { w.bits(0) }); let frequency = timeout.into().0; let ticks = self.clocks.timsclk().0 / frequency / 2; self.timer.tarval.write(|w| unsafe { w.bits(ticks) }); self.timer.curval.write(|w| unsafe { w.bits(0) }); self.timer.ctrl.write(|w| w.ena().set_bit()); } fn wait(&mut self) -> nb::Result<(), Void> { if self.timer.intoflag.read().bits() == 0 { Err(nb::Error::WouldBlock) } else { self.timer.curval.read(); Ok(()) } } } impl<TIMER> Periodic for Timer<TIMER> where TIMER: Deref<Target = TimerRegisterBlock> {} impl CountDown for Delay { type Time = Hertz; fn start<T>(&mut self, timeout: T) where T: Into<Hertz>, { let frequency = timeout.into().0; let ticks = self.scale * 1_000_000 / frequency; self.countdown = Some((ticks, unsafe { (*self.timer).curval.read().bits() })); } fn wait(&mut self) -> nb::Result<(), Void> { if let Some((ref ticks, ref start_count)) = self.countdown { if unsafe { (*(self.timer)) .curval .read() .bits() .wrapping_sub(*start_count) } < *ticks { Err(nb::Error::WouldBlock) } else { let ticks = *ticks; self.countdown = Some((ticks, unsafe { (*self.timer).curval.read().bits() })); Ok(()) } } else { Err(nb::Error::WouldBlock) } } } impl Periodic for Delay {} impl Cancel for Delay { type Error = (); fn cancel(&mut self) -> Result<(), ()> { self.countdown = None; Ok(()) } }
use core::ops::Deref; use embedded_hal::timer::{Cancel, CountDown, Periodic}; use void::Void; use crate::delay::Delay; use crate::syscon::{ClockEnable, Clocks, Syscon}; use crate::time::Hertz; pub(crate) type TimerRegisterBlock = swm050::tmrse0::RegisterBlock; pub struct Timer<TIMER> { clocks: Clocks, pub(crate) timer: TIMER, } impl<TIMER> Timer<TIMER> where TIMER: Deref<Target = TimerRegisterBlock> + ClockEnable, { pub fn timer<T>(timer: TIMER, timeout: T, syscon: &mut Syscon) -> Timer<TIMER> where T: Into<Hertz>, { TIMER::enable(syscon);
pub fn release(self) -> TIMER { self.timer } } impl<TIMER> CountDown for Timer<TIMER> where TIMER: Deref<Target = TimerRegisterBlock>, { type Time = Hertz; fn start<T>(&mut self, timeout: T) where T: Into<Hertz>, { self.timer.ctrl.write(|w| w.ena().clear_bit()); self.timer.intoflag.write(|w| unsafe { w.bits(0) }); let frequency = timeout.into().0; let ticks = self.clocks.timsclk().0 / frequency / 2; self.timer.tarval.write(|w| unsafe { w.bits(ticks) }); self.timer.curval.write(|w| unsafe { w.bits(0) }); self.timer.ctrl.write(|w| w.ena().set_bit()); } fn wait(&mut self) -> nb::Result<(), Void> { if self.timer.intoflag.read().bits() == 0 { Err(nb::Error::WouldBlock) } else { self.timer.curval.read(); Ok(()) } } } impl<TIMER> Periodic for Timer<TIMER> where TIMER: Deref<Target = TimerRegisterBlock> {} impl CountDown for Delay { type Time = Hertz; fn start<T>(&mut self, timeout: T) where T: Into<Hertz>, { let frequency = timeout.into().0; let ticks = self.scale * 1_000_000 / frequency; self.countdown = Some((ticks, unsafe { (*self.timer).curval.read().bits() })); } fn wait(&mut self) -> nb::Result<(), Void> { if let Some((ref ticks, ref start_count)) = self.countdown { if unsafe { (*(self.timer)) .curval .read() .bits() .wrapping_sub(*start_count) } < *ticks { Err(nb::Error::WouldBlock) } else { let ticks = *ticks; self.countdown = Some((ticks, unsafe { (*self.timer).curval.read().bits() })); Ok(()) } } else { Err(nb::Error::WouldBlock) } } } impl Periodic for Delay {} impl Cancel for Delay { type Error = (); fn cancel(&mut self) -> Result<(), ()> { self.countdown = None; Ok(()) } }
timer.intctrl.write(|w| w.ena().set_bit()); let mut timer = Timer { timer: timer, clocks: syscon.clocks, }; timer.start(timeout); timer }
function_block-function_prefix_line
[ { "content": "pub trait ClockEnable {\n\n fn enable(syscon: &mut Syscon);\n\n}\n\nmacro_rules! clock_enable {\n\n ($PERIPH: ident, $field:ident) => {\n\n impl ClockEnable for swm050::$PERIPH {\n\n fn enable(syscon: &mut Syscon) {\n\n syscon.regs.pclk_en.modify(|_, w| w.$fi...
Rust
Chapter07/users-pool/src/main.rs
dominicbachmann/Hands-On-Microservices-with-Rust
6ca0a00ac8d8bf9123ce4eab2092b57408d8ed1c
use clap::{ crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg, SubCommand, }; use postgres::{Connection, Error}; use r2d2_postgres::{TlsMode, PostgresConnectionManager}; use rayon::prelude::*; use serde_derive::Deserialize; use std::io; fn create_table(conn: &Connection) -> Result<(), Error> { conn.execute("CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, email VARCHAR NOT NULL )", &[]) .map(drop) } fn create_user(conn: &Connection, user: &User) -> Result<(), Error> { conn.execute("INSERT INTO users (name, email) VALUES ($1, $2)", &[&user.name, &user.email]) .map(drop) } fn list_users(conn: &Connection) -> Result<Vec<User>, Error> { let res = conn.query("SELECT name, email FROM users", &[])?.into_iter() .map(|row| { User { name: row.get(0), email: row.get(1), } }) .collect(); Ok(res) } #[derive(Deserialize, Debug)] struct User { name: String, email: String, } const CMD_CREATE: &str = "create"; const CMD_ADD: &str = "add"; const CMD_LIST: &str = "list"; const CMD_IMPORT: &str = "import"; fn main() -> Result<(), failure::Error> { let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .setting(AppSettings::SubcommandRequired) .arg( Arg::with_name("database") .short("d") .long("db") .value_name("ADDR") .help("Sets an address of db connection") .takes_value(true), ) .subcommand(SubCommand::with_name(CMD_CREATE).about("create users table")) .subcommand(SubCommand::with_name(CMD_ADD).about("add user to the table") .arg(Arg::with_name("NAME") .help("Sets the name of a user") .required(true) .index(1)) .arg(Arg::with_name("EMAIL") .help("Sets the email of a user") .required(true) .index(2))) .subcommand(SubCommand::with_name(CMD_LIST).about("print list of users")) .subcommand(SubCommand::with_name(CMD_IMPORT).about("import users from csv")) .get_matches(); let addr = matches.value_of("database") .unwrap_or("postgres://postgres@localhost:5432"); let manager = PostgresConnectionManager::new(addr, TlsMode::None)?; let pool = r2d2::Pool::new(manager)?; let conn = pool.get()?; match matches.subcommand() { (CMD_CREATE, _) => { create_table(&conn)?; } (CMD_ADD, Some(matches)) => { let name = matches.value_of("NAME").unwrap().to_owned(); let email = matches.value_of("EMAIL").unwrap().to_owned(); let user = User { name, email }; create_user(&conn, &user)?; } (CMD_LIST, _) => { let list = list_users(&conn)?; for user in list { println!("Name: {:20} Email: {:20}", user.name, user.email); } } (CMD_IMPORT, _) => { let mut rdr = csv::Reader::from_reader(io::stdin()); let mut users = Vec::new(); for user in rdr.deserialize() { users.push(user?); } users.par_iter() .map(|user| -> Result<(), failure::Error> { let conn = pool.get()?; create_user(&conn, &user)?; Ok(()) }) .for_each(drop); } _ => { matches.usage(); } } Ok(()) }
use clap::{ crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg, SubCommand, }; use postgres::{Connection, Error}; use r2d2_postgres::{TlsMode, PostgresConnectionManager}; use rayon::prelude::*; use serde_derive::Deserialize; use std::io; fn create_table(conn: &Connection) -> Result<(), Error> { conn.execute("CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, email VARCHAR NOT NULL )", &[]) .map(drop) } fn create_user(conn: &Connection, user: &User) -> Result<(), Error> { conn.execute("INSERT INTO users (name, email) VALUES ($1, $2)", &[&user.name, &user.email]) .map(drop) }
#[derive(Deserialize, Debug)] struct User { name: String, email: String, } const CMD_CREATE: &str = "create"; const CMD_ADD: &str = "add"; const CMD_LIST: &str = "list"; const CMD_IMPORT: &str = "import"; fn main() -> Result<(), failure::Error> { let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .setting(AppSettings::SubcommandRequired) .arg( Arg::with_name("database") .short("d") .long("db") .value_name("ADDR") .help("Sets an address of db connection") .takes_value(true), ) .subcommand(SubCommand::with_name(CMD_CREATE).about("create users table")) .subcommand(SubCommand::with_name(CMD_ADD).about("add user to the table") .arg(Arg::with_name("NAME") .help("Sets the name of a user") .required(true) .index(1)) .arg(Arg::with_name("EMAIL") .help("Sets the email of a user") .required(true) .index(2))) .subcommand(SubCommand::with_name(CMD_LIST).about("print list of users")) .subcommand(SubCommand::with_name(CMD_IMPORT).about("import users from csv")) .get_matches(); let addr = matches.value_of("database") .unwrap_or("postgres://postgres@localhost:5432"); let manager = PostgresConnectionManager::new(addr, TlsMode::None)?; let pool = r2d2::Pool::new(manager)?; let conn = pool.get()?; match matches.subcommand() { (CMD_CREATE, _) => { create_table(&conn)?; } (CMD_ADD, Some(matches)) => { let name = matches.value_of("NAME").unwrap().to_owned(); let email = matches.value_of("EMAIL").unwrap().to_owned(); let user = User { name, email }; create_user(&conn, &user)?; } (CMD_LIST, _) => { let list = list_users(&conn)?; for user in list { println!("Name: {:20} Email: {:20}", user.name, user.email); } } (CMD_IMPORT, _) => { let mut rdr = csv::Reader::from_reader(io::stdin()); let mut users = Vec::new(); for user in rdr.deserialize() { users.push(user?); } users.par_iter() .map(|user| -> Result<(), failure::Error> { let conn = pool.get()?; create_user(&conn, &user)?; Ok(()) }) .for_each(drop); } _ => { matches.usage(); } } Ok(()) }
fn list_users(conn: &Connection) -> Result<Vec<User>, Error> { let res = conn.query("SELECT name, email FROM users", &[])?.into_iter() .map(|row| { User { name: row.get(0), email: row.get(1), } }) .collect(); Ok(res) }
function_block-full_function
[ { "content": "fn create_user(conn: &Connection, name: &str, email: &str) -> Result<(), Error> {\n\n conn.execute(\"INSERT INTO users (name, email) VALUES ($1, $2)\",\n\n &[&name, &email])\n\n .map(drop)\n\n}\n\n\n", "file_path": "Chapter07/users/src/main.rs", "rank": 0, "sc...
Rust
src/main.rs
Steve-xmh/netease-music-tui
7b2c1f07cd679e1d44d8ea61640e37f97b0ce96e
#[macro_use] extern crate lazy_static; #[macro_use] extern crate failure; extern crate config; extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate log; extern crate log_panics; use crossterm::event::{EnableMouseCapture, KeyCode, KeyEvent, KeyModifiers}; use crossterm::terminal::enable_raw_mode; use crossterm::ExecutableCommand; use dirs; use failure::err_msg; use log::LevelFilter; use std::fs; use std::io; use std::path::Path; use tui::backend::CrosstermBackend; use tui::Terminal; use util::event::{Event, Events}; mod api; mod app; mod handlers; mod model; mod player; mod ui; mod util; mod dbus_mpris; use app::{ActiveBlock, App}; use dbus_mpris::{dbus_mpris_handler, DbusMpris}; const FILE_NAME: &str = "Settings.toml"; const CONFIG_DIR: &str = ".config"; const APP_CONFIG_DIR: &str = "netease-music-tui"; #[cfg(not(target_os = "windows"))] fn get_log_path() -> String { "/var/log/ncmt.log".into() } #[cfg(target_os = "windows")] fn get_log_path() -> String { "./ncmt.log".into() } fn main() -> Result<(), failure::Error> { let config_file_path = match dirs::home_dir() { Some(home) => { let path = Path::new(&home); let home_config_dir = path.join(CONFIG_DIR); let app_config_dir = home_config_dir.join(APP_CONFIG_DIR); if !home_config_dir.exists() { fs::create_dir(&home_config_dir)?; } if !app_config_dir.exists() { fs::create_dir(&app_config_dir)?; } let config_file_path = &app_config_dir.join(FILE_NAME); config_file_path.to_path_buf() } None => return Err(err_msg("No $HOME directory found for config")), }; let mut settings = config::Config::default(); let config_string = match fs::read_to_string(&config_file_path) { Ok(data) => data, Err(_) => return Err(err_msg("Please set your account in config file")), }; settings .merge(config::File::from_str( &config_string, config::FileFormat::Toml, )) .unwrap(); match settings.get_bool("debug") { Ok(debug) => { if debug { log_panics::init(); simple_logging::log_to_file(get_log_path(), LevelFilter::Debug)?; } } Err(e) => error!("{}", e), } info!("start netease cloud music rust client"); let mut app = App::new(); let mut is_first_render = true; let cloud_music = app.cloud_music.to_owned().unwrap(); let profile = match cloud_music.login_status()? { Some(profile) => { app.user_id = profile.userId.unwrap(); profile } None => { let username = settings.get::<String>("username")?; let password = settings.get::<String>("password")?; match cloud_music.login(&username, &password) { Ok(profile) => profile, Err(_) => return Err(err_msg("Account/Password Error")), } } }; let mut stdout = io::stdout(); stdout.execute(EnableMouseCapture)?; enable_raw_mode()?; let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; terminal.hide_cursor()?; let events = Events::new(); let dbus_mpris = DbusMpris::new(); loop { terminal.draw(|mut f| { let current_route = app.get_current_route(); match current_route.active_block { ActiveBlock::Help => { ui::draw_help_menu(&mut f); } ActiveBlock::Msg => { ui::draw_msg(&mut f, &mut app); } _ => { ui::draw_main_layout(&mut f, &mut app); } } })?; match dbus_mpris.next() { Ok(cmd) => { dbus_mpris_handler(cmd, &mut app); } Err(_) => {} } match events.next()? { Event::Input(input) => { match input { KeyEvent { code: KeyCode::Char('q'), modifiers: KeyModifiers::NONE, } => { if app.get_current_route().active_block != ActiveBlock::Search { let pop_result = app.pop_navigation_stack(); if pop_result.is_none() { break; } } } KeyEvent { code: KeyCode::Char('c'), modifiers: KeyModifiers::CONTROL, } => { break; } _ => { handlers::handle_app(input, &mut app); } } } Event::Tick => { app.update_on_tick(); } } if is_first_render { let cloud_music = app.cloud_music.to_owned().unwrap(); let playlists = cloud_music.user_playlists(&profile.userId.unwrap().to_string()); match playlists { Ok(p) => { app.playlists = Some(p); app.selected_playlist_index = Some(0); } Err(e) => { app.handle_error(e); } }; is_first_render = false; } } Ok(()) }
#[macro_use] extern crate lazy_static; #[macro_use] extern crate failure; extern crate config; extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate log; extern crate log_panics; use crossterm::event::{EnableMouseCapture, KeyCode, KeyEvent, KeyModifiers}; use crossterm::terminal::enable_raw_mode; use crossterm::ExecutableCommand; use dirs; use failure::err_msg; use log::LevelFilter; use std::fs; use std::io; use std::path::Path; use tui::backend::CrosstermBackend; use tui::Terminal; use util::event::{Event, Events}; mod api; mod app; mod handlers; mod model; mod player; mod ui; mod util; mod dbus_mpris; use app::{ActiveBlock, App}; use dbus_mpris::{dbus_mpris_handler, DbusMpris}; const FILE_NAME: &str = "Settings.toml"; const CONFIG_DIR: &str = ".config"; const APP_CONFIG_DIR: &str = "netease-music-tui"; #[cfg(not(target_os = "windows"))] fn get_log_path() -> String { "/var/log/ncmt.log".into() } #[cfg(target_os = "windows")] fn get_log_path() -> String { "./ncmt.log".into() } fn main() -> Result<(), failure::Error> { let config_file_path = match dirs::home_dir() { Some(home) => { let path = Path::new(&home); let home_config_dir = path.join(CONFIG_DIR); let app_config_dir = home_config_dir.join(APP_CONFIG_DIR); if !home_config_dir.exists() { fs::create_dir(&home_config_dir)?; } if !app_config_dir.exists() { fs::create_dir(&app_config_dir)?; } let config_file_path = &app_config_dir.join(FILE_NAME); config_file_path.to_path_buf() } None => return Err(err_msg("No $HOME directory found for config")), }; let mut settings = config::Config::default(); let config_string = match fs::read_to_string(&config_file_path) { Ok(data) => data, Err(_) => return Err(err_msg("Please set your account in config file")), }; settings .merge(config::File::from_str( &config_string, config::FileFormat::Toml, )) .unwrap(); match settings.get_bool("debug") { Ok(debug) => { if debug { log_panics::init(); simple_logging::log_to_file(get_log_path(), LevelFilter::Debug)?; } } Err(e) => error!("{}", e), } info!("start netease cloud music rust client"); let mut app = App::new(); let mut is_first_render = true; let cloud_music = app.cloud_music.to_owned().unwrap(); let profile = match cloud_music.login_status()? { Some(profile) => { app.user_id = profile.userId.unwrap(); profile } None => { let username = settings.get::<String>("username")?; let password = settings.get::<String>("password")?; match cloud_music.login(&username, &password) { Ok(profile) => profile, Err(_) => return Err(err_msg("Account/Password Error")), } } }; let mut stdout = io::stdout(); stdout.execute(EnableMouseCapture)?; enable_raw_mode()?; let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; terminal.hide_cursor()?; let events = Events::new(); let dbus_mpris = DbusMpris::new(); loop { terminal.draw(|mut f| { let current_route = app.get_current_route(); match current_route.active_block { ActiveBlock::Help => { ui::draw_help_menu(&mut f); } ActiveBlock::Msg => { ui::draw_msg(&mut f, &mut app); } _ => {
ui::draw_main_layout(&mut f, &mut app); } } })?; match dbus_mpris.next() { Ok(cmd) => { dbus_mpris_handler(cmd, &mut app); } Err(_) => {} } match events.next()? { Event::Input(input) => { match input { KeyEvent { code: KeyCode::Char('q'), modifiers: KeyModifiers::NONE, } => { if app.get_current_route().active_block != ActiveBlock::Search { let pop_result = app.pop_navigation_stack(); if pop_result.is_none() { break; } } } KeyEvent { code: KeyCode::Char('c'), modifiers: KeyModifiers::CONTROL, } => { break; } _ => { handlers::handle_app(input, &mut app); } } } Event::Tick => { app.update_on_tick(); } } if is_first_render { let cloud_music = app.cloud_music.to_owned().unwrap(); let playlists = cloud_music.user_playlists(&profile.userId.unwrap().to_string()); match playlists { Ok(p) => { app.playlists = Some(p); app.selected_playlist_index = Some(0); } Err(e) => { app.handle_error(e); } }; is_first_render = false; } } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn handler(key: KeyEvent, app: &mut App) {\n\n match key {\n\n k if common_events::left_event(k) => common_events::handle_left_event(app),\n\n KeyEvent {\n\n code: KeyCode::Enter,\n\n modifiers: KeyModifiers::NONE,\n\n } => {\n\n let cur...
Rust
src/main.rs
samhamnam/conways_game_of_crabs
1c8afc822ea1c432c9c3ee281380d524ed71199a
use pixels::{Error, Pixels, SurfaceTexture}; use rand::prelude::*; use winit::{ dpi::LogicalSize, event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; fn main() -> Result<(), Error> { println!("Random start: {}", random::<i32>()); let width = 400; let height = 400; let event_loop = EventLoop::new(); let window = { let size = LogicalSize::new(width as f64, height as f64); WindowBuilder::new() .with_title("Crabs") .with_inner_size(size) .with_min_inner_size(size) .with_resizable(false) .build(&event_loop) .unwrap() }; let mut pixels = { let window_size = window.inner_size(); let surface_texture = SurfaceTexture::new(window_size.width, window_size.height, &window); Pixels::new(width, height, surface_texture)? }; let mut world = World::new([54, 139, 187, 255], [190, 25, 49, 255], width, height); event_loop.run(move |event, _, control_flow| { if let Event::RedrawRequested(_) = event { world.draw(pixels.get_frame()); if pixels .render() .map_err(|e| panic!("pixels.render() failed: {}", e)) .is_err() { *control_flow = ControlFlow::Exit; } } if let Event::WindowEvent { event: e, .. } = event { if e == WindowEvent::CloseRequested { *control_flow = ControlFlow::Exit } else if let WindowEvent::Resized(new_size) = e { println!("{:?}", new_size); pixels.resize_surface(new_size.width, new_size.height) } } window.request_redraw(); }); } pub struct World { clear_color: [u8; 4], width: u32, height: u32, crabs: Vec<bool>, crab_buffer: Vec<bool>, crab_color: [u8; 4], } impl World { pub fn new(clear_color: [u8; 4], crab_color: [u8; 4], width: u32, height: u32) -> Self { let w = width as usize; let h = height as usize; let mut crabs = vec![false; w * h]; crabs.iter_mut().for_each(|c| *c = random()); let crab_buffer = vec![false; w * h]; Self { clear_color, crab_color, width, height, crabs, crab_buffer, } } pub fn get_crab(&self, x: usize, y: usize) -> bool { self.crabs[x + (self.height as usize * y)] } pub fn set_crab(&mut self, val: bool, x: usize, y: usize) { self.crabs[x + (self.height as usize * y)] = val; } pub fn get_crabs_siblings(&self, x: usize, y: usize) -> impl Iterator<Item = bool> { if x == 0 || y == 0 || y >= self.height as usize - 1 || x >= self.width as usize - 1 { vec![].into_iter() } else { let c = &self.crabs; #[allow(clippy::identity_op)] vec![ c[(x - 1) + (self.height as usize * (y - 1))], c[(x + 0) + (self.height as usize * (y - 1))], c[(x + 1) + (self.height as usize * (y - 1))], c[(x - 1) + (self.height as usize * (y + 0))], c[(x + 1) + (self.height as usize * (y + 0))], c[(x - 1) + (self.height as usize * (y + 1))], c[(x + 0) + (self.height as usize * (y + 1))], c[(x + 1) + (self.height as usize * (y + 1))], ] .into_iter() } } pub fn should_crab_live(&self, x: usize, y: usize) -> bool { let alive = self.get_crabs_siblings(x, y).filter(|c| *c).count(); if self.get_crab(x, y) { alive == 2 || alive == 3 } else { alive == 3 } } pub fn draw(&mut self, frame: &mut [u8]) { for i in 0..self.crabs.len() { let x = (i % self.width as usize) as usize; let y = (i / self.width as usize) as usize; let should_live = self.should_crab_live(x, y); self.crab_buffer[i] = should_live; let pixel = frame.chunks_exact_mut(4).nth(i).unwrap(); if should_live { pixel.copy_from_slice(&self.crab_color); } else { pixel.copy_from_slice(&self.clear_color); } } self.crabs.copy_from_slice(&self.crab_buffer); } }
use pixels::{Error, Pixels, SurfaceTexture}; use rand::prelude::*; use winit::{ dpi::LogicalSize, event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; fn main() -> Result<(), Error> { println!("Random start: {}", random::<i32>()); let width = 400; let height = 400; let event_loop = EventLoop::new(); let window = { let size = LogicalSize::new(width as f64, height as f64); WindowBuilder::new() .with_title("Crab
pub struct World { clear_color: [u8; 4], width: u32, height: u32, crabs: Vec<bool>, crab_buffer: Vec<bool>, crab_color: [u8; 4], } impl World { pub fn new(clear_color: [u8; 4], crab_color: [u8; 4], width: u32, height: u32) -> Self { let w = width as usize; let h = height as usize; let mut crabs = vec![false; w * h]; crabs.iter_mut().for_each(|c| *c = random()); let crab_buffer = vec![false; w * h]; Self { clear_color, crab_color, width, height, crabs, crab_buffer, } } pub fn get_crab(&self, x: usize, y: usize) -> bool { self.crabs[x + (self.height as usize * y)] } pub fn set_crab(&mut self, val: bool, x: usize, y: usize) { self.crabs[x + (self.height as usize * y)] = val; } pub fn get_crabs_siblings(&self, x: usize, y: usize) -> impl Iterator<Item = bool> { if x == 0 || y == 0 || y >= self.height as usize - 1 || x >= self.width as usize - 1 { vec![].into_iter() } else { let c = &self.crabs; #[allow(clippy::identity_op)] vec![ c[(x - 1) + (self.height as usize * (y - 1))], c[(x + 0) + (self.height as usize * (y - 1))], c[(x + 1) + (self.height as usize * (y - 1))], c[(x - 1) + (self.height as usize * (y + 0))], c[(x + 1) + (self.height as usize * (y + 0))], c[(x - 1) + (self.height as usize * (y + 1))], c[(x + 0) + (self.height as usize * (y + 1))], c[(x + 1) + (self.height as usize * (y + 1))], ] .into_iter() } } pub fn should_crab_live(&self, x: usize, y: usize) -> bool { let alive = self.get_crabs_siblings(x, y).filter(|c| *c).count(); if self.get_crab(x, y) { alive == 2 || alive == 3 } else { alive == 3 } } pub fn draw(&mut self, frame: &mut [u8]) { for i in 0..self.crabs.len() { let x = (i % self.width as usize) as usize; let y = (i / self.width as usize) as usize; let should_live = self.should_crab_live(x, y); self.crab_buffer[i] = should_live; let pixel = frame.chunks_exact_mut(4).nth(i).unwrap(); if should_live { pixel.copy_from_slice(&self.crab_color); } else { pixel.copy_from_slice(&self.clear_color); } } self.crabs.copy_from_slice(&self.crab_buffer); } }
s") .with_inner_size(size) .with_min_inner_size(size) .with_resizable(false) .build(&event_loop) .unwrap() }; let mut pixels = { let window_size = window.inner_size(); let surface_texture = SurfaceTexture::new(window_size.width, window_size.height, &window); Pixels::new(width, height, surface_texture)? }; let mut world = World::new([54, 139, 187, 255], [190, 25, 49, 255], width, height); event_loop.run(move |event, _, control_flow| { if let Event::RedrawRequested(_) = event { world.draw(pixels.get_frame()); if pixels .render() .map_err(|e| panic!("pixels.render() failed: {}", e)) .is_err() { *control_flow = ControlFlow::Exit; } } if let Event::WindowEvent { event: e, .. } = event { if e == WindowEvent::CloseRequested { *control_flow = ControlFlow::Exit } else if let WindowEvent::Resized(new_size) = e { println!("{:?}", new_size); pixels.resize_surface(new_size.width, new_size.height) } } window.request_redraw(); }); }
function_block-function_prefixed
[]
Rust
xngin-compute/src/cmp.rs
jiangzhe/xngin
57f3e2070a3bf52dbfda28750038302e330eca12
use crate::error::{Error, Result}; use crate::BinaryEval; use xngin_datatype::PreciseType; use xngin_expr::PredFuncKind; use xngin_storage::attr::Attr; use xngin_storage::bitmap::Bitmap; use xngin_storage::codec::{Codec, Single}; use xngin_storage::repr::ByteRepr; use xngin_storage::sel::Sel; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum CmpKind { Equal, Greater, GreaterEqual, Less, LessEqual, NotEqual, } impl CmpKind { #[inline] pub fn from_pred(kind: PredFuncKind) -> Option<Self> { let res = match kind { PredFuncKind::Equal => CmpKind::Equal, PredFuncKind::Greater => CmpKind::Greater, PredFuncKind::GreaterEqual => CmpKind::GreaterEqual, PredFuncKind::Less => CmpKind::Less, PredFuncKind::LessEqual => CmpKind::LessEqual, PredFuncKind::NotEqual => CmpKind::NotEqual, _ => return None, }; Some(res) } #[inline] pub fn eval(&self, lhs: &Attr, rhs: &Attr, sel: Option<&Sel>) -> Result<Attr> { match (self, lhs.ty, rhs.ty) { (CmpKind::Equal, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(EqualI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Equal, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(EqualI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Greater, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(GreaterI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Greater, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(GreaterI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::GreaterEqual, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(GreaterEqualI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::GreaterEqual, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(GreaterEqualI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Less, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(LessI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Less, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(LessI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::LessEqual, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(LessEqualI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::LessEqual, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(LessEqualI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::NotEqual, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(NotEqualI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::NotEqual, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(NotEqualI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } _ => Err(Error::UnsupportedEval), } } } pub trait CmpEval { type L: ByteRepr + Copy; type R: ByteRepr + Copy; fn apply_bool(&self, lhs: Self::L, rhs: Self::R) -> bool; } struct Impl<T>(T); impl<T: CmpEval> Impl<T> { #[inline] fn apply_left_chunk(&self, lhs: &[T::L], rhs: T::R) -> u64 { let mut res = 0u64; let mut mask = 1; for l_val in lhs { let flag = self.0.apply_bool(*l_val, rhs); res |= if flag { mask } else { 0 }; mask <<= 1; } res } #[inline] fn apply_right_chunk(&self, lhs: T::L, rhs: &[T::R]) -> u64 { let mut res = 0u64; let mut mask = 1; for r_val in rhs { let flag = self.0.apply_bool(lhs, *r_val); res |= if flag { mask } else { 0 }; mask <<= 1; } res } #[inline] fn apply_chunk(&self, lhs: &[T::L], rhs: &[T::R]) -> u64 { let mut res = 0u64; let mut mask = 1; for (l_val, r_val) in lhs.iter().zip(rhs) { let flag = self.0.apply_bool(*l_val, *r_val); res |= if flag { mask } else { 0 }; mask <<= 1; } res } #[inline] fn single_single(&self, l_val: T::L, r_val: T::R, validity: Sel) -> Result<Attr> { let flag = self.0.apply_bool(l_val, r_val); Ok(Attr::new_single( PreciseType::bool(), Single::new_bool(flag, validity.n_records() as u16), validity, )) } #[inline] fn array_single( &self, l_vals: &[T::L], r_val: T::R, validity: Sel, sel: Option<&Sel>, ) -> Result<Attr> { if let Some(sel) = sel { match sel { Sel::None { .. } => { return Ok(Attr::new_null(PreciseType::bool(), l_vals.len() as u16)); } Sel::Index { count, indexes, .. } => { return handle_sel_index( &indexes[..*count as usize], &validity, l_vals.len(), |idx| self.0.apply_bool(l_vals[idx], r_val), ) } _ => (), } } let mut res = Bitmap::zeroes(l_vals.len()); let (res_u64s, _) = res.u64s_mut(); for (lhs, res) in l_vals.chunks(64).zip(res_u64s) { *res = self.apply_left_chunk(lhs, r_val); } Ok(Attr::new_bitmap(res, validity)) } #[inline] fn single_array( &self, l_val: T::L, r_vals: &[T::R], validity: Sel, sel: Option<&Sel>, ) -> Result<Attr> { if let Some(sel) = sel { match sel { Sel::None { .. } => { return Ok(Attr::new_null(PreciseType::bool(), r_vals.len() as u16)); } Sel::Index { count, indexes, .. } => { return handle_sel_index( &indexes[..*count as usize], &validity, r_vals.len(), |idx| self.0.apply_bool(l_val, r_vals[idx]), ) } _ => (), } } let mut res = Bitmap::zeroes(r_vals.len()); let (res_u64s, _) = res.u64s_mut(); for (rhs, res) in r_vals.chunks(64).zip(res_u64s) { *res = self.apply_right_chunk(l_val, rhs); } Ok(Attr::new_bitmap(res, validity)) } #[inline] fn array_array( &self, l_vals: &[T::L], r_vals: &[T::R], validity: Sel, sel: Option<&Sel>, ) -> Result<Attr> { assert!(l_vals.len() == r_vals.len()); if let Some(sel) = sel { match sel { Sel::None { .. } => { return Ok(Attr::new_null(PreciseType::bool(), l_vals.len() as u16)); } Sel::Index { count, indexes, .. } => { return handle_sel_index( &indexes[..*count as usize], &validity, l_vals.len(), |idx| self.0.apply_bool(l_vals[idx], r_vals[idx]), ) } _ => (), } } let mut res = Bitmap::zeroes(r_vals.len()); let (res_u64s, _) = res.u64s_mut(); for ((lhs, rhs), res) in l_vals.chunks(64).zip(r_vals.chunks(64)).zip(res_u64s) { *res = self.apply_chunk(lhs, rhs); } Ok(Attr::new_bitmap(res, validity)) } } #[inline] fn handle_sel_index<F: Fn(usize) -> bool>( sel: &[u16], validity: &Sel, len: usize, f: F, ) -> Result<Attr> { let mut res = Bitmap::zeroes(len); let mut valids = [0u16; 6]; let mut valid_count = 0; for idx in sel { let i = *idx as usize; if validity.selected(i)? { let flag = f(i); res.set(i, flag)?; valids[valid_count] = *idx; valid_count += 1; } } let res = if valid_count == 0 { Attr::new_null(PreciseType::bool(), len as u16) } else { let validity = Sel::Index { count: valid_count as u8, len: len as u16, indexes: valids, }; Attr::new_bitmap(res, validity) }; Ok(res) } impl<T: CmpEval> BinaryEval for Impl<T> { #[inline] fn binary_eval( &self, res_ty: PreciseType, lhs: &Attr, rhs: &Attr, sel: Option<&Sel>, ) -> Result<Attr> { debug_assert_eq!(PreciseType::bool(), res_ty); let n_records = lhs.n_records(); if n_records != rhs.n_records() { return Err(Error::RowNumberMismatch); } let validity = lhs.validity.intersect(&rhs.validity)?; if validity.is_none() { return Ok(Attr::new_null(res_ty, n_records as u16)); } match (&lhs.codec, &rhs.codec) { (Codec::Single(l), Codec::Single(r)) => { self.single_single(l.view(), r.view(), validity) } (Codec::Array(l), Codec::Single(r)) => { self.array_single(l.cast_slice(), r.view(), validity, sel) } (Codec::Single(l), Codec::Array(r)) => { self.single_array(l.view(), r.cast_slice(), validity, sel) } (Codec::Array(l), Codec::Array(r)) => { self.array_array(l.cast_slice(), r.cast_slice(), validity, sel) } (Codec::Empty, _) | (_, Codec::Empty) => Ok(Attr::empty(res_ty)), (Codec::Bitmap(_), _) | (_, Codec::Bitmap(_)) => Err(Error::UnsupportedEval), } } } macro_rules! impl_cmp_eval_for_iso_num { ($id:ident, $ty:ty, $op:tt) => { pub struct $id; impl CmpEval for $id { type L = $ty; type R = $ty; #[inline] fn apply_bool(&self, lhs: Self::L, rhs: Self::R) -> bool { lhs $op rhs } } } } impl_cmp_eval_for_iso_num!(EqualI32, i32, ==); impl_cmp_eval_for_iso_num!(GreaterI32, i32, >); impl_cmp_eval_for_iso_num!(GreaterEqualI32, i32, >=); impl_cmp_eval_for_iso_num!(LessI32, i32, <); impl_cmp_eval_for_iso_num!(LessEqualI32, i32, <=); impl_cmp_eval_for_iso_num!(NotEqualI32, i32, !=); impl_cmp_eval_for_iso_num!(EqualI64, i64, ==); impl_cmp_eval_for_iso_num!(GreaterI64, i64, >); impl_cmp_eval_for_iso_num!(GreaterEqualI64, i64, >=); impl_cmp_eval_for_iso_num!(LessI64, i64, <); impl_cmp_eval_for_iso_num!(LessEqualI64, i64, <=); impl_cmp_eval_for_iso_num!(NotEqualI64, i64, !=); #[cfg(test)] mod tests { use super::*; #[test] fn test_cmp_eval_eq() { let size = 10i32; let c1 = Attr::from((0..size).into_iter()); let c2 = Attr::from((0..size).into_iter()); let c3 = Attr::new_single( PreciseType::i32(), Single::new(0i32, size as u16), Sel::All(size as u16), ); let c4 = Attr::new_single( PreciseType::i32(), Single::new(0i32, size as u16), Sel::All(size as u16), ); let c5 = Attr::new_null(PreciseType::i32(), size as u16); let eq = CmpKind::Equal; let res = eq.eval(&c1, &c2, None).unwrap(); let res = res.codec.as_bitmap().unwrap(); assert!(res.bools().all(|b| b)); let res = eq.eval(&c3, &c4, None).unwrap(); assert!(res.validity.is_all()); let res = res.codec.as_single().unwrap(); let value = res.view_bool(); assert!(value); let res = eq.eval(&c1, &c3, None).unwrap(); let res = res.codec.as_bitmap().unwrap(); assert!(res.get(0).unwrap()); assert!(res.bools().skip(1).all(|b| !b)); let res = eq.eval(&c4, &c2, None).unwrap(); let res = res.codec.as_bitmap().unwrap(); assert!(res.get(0).unwrap()); assert!(res.bools().skip(1).all(|b| !b)); let res = eq.eval(&c1, &c5, None).unwrap(); assert!(res.validity.is_none()); let res = eq.eval(&c5, &c1, None).unwrap(); assert!(res.validity.is_none()); let res = eq.eval(&c3, &c5, None).unwrap(); assert!(res.validity.is_none()); } #[test] fn test_cmp_eval_gt() { let c1 = Attr::from((0..64i32).into_iter()); let c2 = Attr::from((0..64i32).into_iter().rev()); let c3 = Attr::new_single(PreciseType::i32(), Single::new(5i32, 64), Sel::All(64)); let c4 = Attr::new_single(PreciseType::i32(), Single::new(15i32, 64), Sel::All(64)); let gt = CmpKind::Greater; let res = gt .eval(&c1, &c2, Some(&Sel::new_indexes(64, vec![5, 50]))) .unwrap(); let (valid, _) = res.bool_at(0).unwrap(); assert!(!valid); let (valid, value) = res.bool_at(5).unwrap(); assert!(valid && !value); let (valid, value) = res.bool_at(50).unwrap(); assert!(valid && value); let res = gt.eval(&c1, &c2, Some(&Sel::None(64))).unwrap(); assert_eq!(PreciseType::bool(), res.ty); let res = gt .eval(&c1, &c3, Some(&Sel::new_indexes(64, vec![1, 50]))) .unwrap(); let (valid, value) = res.bool_at(1).unwrap(); assert!(valid && !value); let (valid, value) = res.bool_at(50).unwrap(); assert!(valid && value); let res = gt.eval(&c1, &c3, Some(&Sel::None(64))).unwrap(); assert_eq!(PreciseType::bool(), res.ty); let res = gt .eval(&c4, &c1, Some(&Sel::new_indexes(64, vec![1, 50]))) .unwrap(); let (valid, value) = res.bool_at(1).unwrap(); assert!(valid && value); let (valid, value) = res.bool_at(50).unwrap(); assert!(valid && !value); let res = gt.eval(&c4, &c1, Some(&Sel::None(64))).unwrap(); assert_eq!(PreciseType::bool(), res.ty); } }
use crate::error::{Error, Result}; use crate::BinaryEval; use xngin_datatype::PreciseType; use xngin_expr::PredFuncKind; use xngin_storage::attr::Attr; use xngin_storage::bitmap::Bitmap; use xngin_storage::codec::{Codec, Single}; use xngin_storage::repr::ByteRepr; use xngin_storage::sel::Sel; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum CmpKind { Equal, Greater, GreaterEqual, Less, LessEqual, NotEqual, } impl CmpKind { #[inline] pub fn from_pred(kind: PredFuncKind) -> Option<Self> { let res = match kind { PredFuncKind::Equal => CmpKind::Equal, PredFuncKind::Greater => CmpKind::Greater, PredFuncKind::GreaterEqual => CmpKind::GreaterEqual, PredFuncKind::Less => CmpKind::Less, PredFuncKind::LessEqual => CmpKind::LessEqual, PredFuncKind::NotEqual => CmpKind::NotEqual, _ => return None, }; Some(res) } #[inline] pub fn eval(&self, lhs: &Attr, rhs: &Attr, sel: Option<&Sel>) -> Result<Attr> { match (self, lhs.ty, rhs.ty) { (CmpKind::Equal, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(EqualI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Equal, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(EqualI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Greater, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(GreaterI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Greater, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(GreaterI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::GreaterEqual, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(GreaterEqualI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::GreaterEqual, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(GreaterEqualI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Less, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(LessI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::Less, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(LessI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::LessEqual, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(LessEqualI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::LessEqual, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(LessEqualI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::NotEqual, PreciseType::Int(4, false), PreciseType::Int(4, false)) => { Impl(NotEqualI32).binary_eval(PreciseType::bool(), lhs, rhs, sel) } (CmpKind::NotEqual, PreciseType::Int(8, false), PreciseType::Int(8, false)) => { Impl(NotEqualI64).binary_eval(PreciseType::bool(), lhs, rhs, sel) } _ => Err(Error::UnsupportedEval), } } } pub trait CmpEval { type L: ByteRepr + Copy; type R: ByteRepr + Copy; fn apply_bool(&self, lhs: Self::L, rhs: Self::R) -> bool; } struct Impl<T>(T); impl<T: CmpEval> Impl<T> { #[inline] fn apply_left_chunk(&self, lhs: &[T::L], rhs: T::R) -> u64 { let mut res = 0u64; let mut mask = 1; for l_val in lhs { let flag = self.0.apply_bool(*l_val, rhs); res |= if flag { mask } else { 0 }; mask <<= 1; } res } #[inline] fn apply_right_chunk(&self, lhs: T::L, rhs: &[T::R]) -> u64 { let mut res = 0u64; let mut mask = 1; for r_val in rhs { let flag = self.0.apply_bool(lhs, *r_val); res |= if flag { mask } else { 0 }; mask <<= 1; } res } #[inline] fn apply_chunk(&self, lhs: &[T::L], rhs: &[T::R]) -> u64 { let mut res = 0u64; let mut mask = 1; for (l_val, r_val) in lhs.iter().zip(rhs) { let flag = self.0.apply_bool(*l_val, *r_val); res |= if flag { mask } else { 0 }; mask <<= 1; } res } #[inline] fn single_single(&self, l_val: T::L, r_val: T::R, validity: Sel) -> Result<Attr> { let flag = self.0.apply_bool(l_val, r_val); Ok(Attr::new_single( PreciseType::bool(), Single::new_bool(flag, validity.n_records() as u16), validity, )) } #[inline] fn array_single( &self, l_vals: &[T::L], r_val: T::R, validity: Sel, sel: Option<&Sel>, ) -> Result<Attr> { if let Some(sel) = sel { match sel { Sel::None { .. } => { return Ok(Attr::new_null(PreciseType::bool(), l_vals.len() as u16)); } Sel::Index { count, indexes, .. } => { return handle_sel_index( &indexes[..*count as usize], &validity, l_vals.len(), |idx| self.0.apply_bool(l_vals[idx], r_val), ) } _ => (), } } let mut res = Bitmap::zeroes(l_vals.len()); let (res_u64s, _) = res.u64s_mut(); for (lhs, res) in l_vals.chunks(64).zip(res_u64s) { *res = self.apply_left_chunk(lhs, r_val); } Ok(Attr::new_bitmap(res, validity)) } #[inline] fn single_array( &self, l_val: T::L, r_vals: &[T::R], validity: Sel, sel: Option<&Sel>, ) -> Result<Attr> { if let Some(sel) = sel { match sel { Sel::None { .. } => { return Ok(Attr::new_null(PreciseType::bool(), r_vals.len() as u16)); } Sel::Index { count, indexes, .. } => { return handle_sel_index( &indexes[..*count as usize], &validity, r_vals.len(), |idx| self.0.apply_bool(l_val, r_vals[idx]), ) } _ => (), } } let mut res = Bitmap::zeroes(r_vals.len()); let (res_u64s, _) = res.u64s_mut(); for (rhs, res) in r_vals.chunks(64).zip(res_u64s) { *res = self.apply_right_chunk(l_val, rhs); } Ok(Attr::new_bitmap(res, validity)) } #[inline] fn array_array( &self, l_vals: &[T::L], r_vals: &[T::R], validity: Sel, sel: Option<&Sel>, ) -> Result<Attr> { assert!(l_vals.len() == r_vals.len()); if let Some(sel) = sel { match sel { Sel::None { .. } => { return Ok(Attr::new_null(PreciseType::bool(), l_vals.len() as u16)); } Sel::Index { count, indexes, .. } => { return handle_sel_index( &indexes[..*count as usize], &validity, l_vals.len(), |idx| self.0.apply_bool(l_vals[idx], r_vals[idx]), ) } _ => (), } } let mut res = Bitmap::zeroes(r_vals.len()); let (res_u64s, _) = res.u64s_mut(); for ((lhs, rhs), res) in l_vals.chunks(64).zip(r_vals.chunks(64)).zip(res_u64s) { *res = self.apply_chunk(lhs, rhs); } Ok(Attr::new_bitmap(res, validity)) } } #[inline] fn handle_sel_index<F: Fn(usize) -> bool>( sel: &[u16], validity: &Sel, len: usize, f: F, ) -> Result<Attr> { let mut res = Bitmap::zeroes(len); let mut valids = [0u16; 6]; let mut valid_count = 0; for idx in sel { let i = *idx as usize; if validity.selected(i)? { let flag = f(i); res.set(i, flag)?; valids[valid_count] = *idx; valid_count += 1; } } let res = if valid_count == 0 { Attr::new_null(PreciseType::bool(), len as u16) } else { let validity = Sel::Index { count: valid_count as u8, len: len as u16, indexes: valids, }; Attr::new_bitmap(res, validity) }; Ok(res) } impl<T: CmpEval> BinaryEval for Impl<T> { #[inline] fn binary_eval( &self, res_ty: PreciseType, lhs: &Attr, rhs: &Attr, sel: Option<&Sel>, ) -> Result<Attr> { debug_assert_eq!(PreciseType::bool(), res_ty); let n_records = lhs.n_records(); if n_records != rhs.n_records() { return Err(Error::RowNumberMismatch); } let validity = lhs.validity.intersect(&rhs.validity)?; if validity.is_none() { return Ok(Attr::new_null(res_ty, n_records as u16)); } match (&lhs.codec, &rhs.codec) { (Codec::Single(l), Codec::Single(r)) => { self.single_single(l.view(), r.view(), validity) } (Codec::Array(l), Codec::Single(r)) => { self.array_single(l.cast_slice(), r.view(), validity, sel) } (Codec::Single(l), Codec::Array(r)) => { self.single_array(l.view(), r.cast_slice(), validity, sel) } (Codec::Array(l), Codec::Array(r)) => { self.array_array(l.cast_slice(), r.cast_slice(), validity, sel) } (Codec::Empty, _) | (_, Codec::Empty) => Ok(Attr::empty(res_ty)), (Codec::Bitmap(_), _) | (_, Codec::Bitmap(_)) => Err(Error::UnsupportedEval), } } } macro_rules! impl_cmp_eval_for_iso_num { ($id:ident, $ty:ty, $op:tt) => { pub struct $id; impl CmpEval for $id { type L = $ty; type R = $ty; #[inline] fn apply_bool(&self, lhs: Self::L, rhs: Self::R) -> bool { lhs $op rhs } } } } impl_cmp_eval_for_iso_num!(EqualI32, i32, ==); impl_cmp_eval_for_iso_num!(GreaterI32, i32, >); impl_cmp_eval_for_iso_num!(GreaterEqualI32, i32, >=); impl_cmp_eval_for_iso_num!(LessI32, i32, <); impl_cmp_eval_for_iso_num!(LessEqualI32, i32, <=); impl_cmp_eval_for_iso_num!(NotEqualI32, i32, !=); impl_cmp_eval_for_iso_num!(EqualI64, i64, ==); impl_cmp_eval_for_iso_num!(GreaterI64, i64, >); impl_cmp_eval_for_iso_num!(GreaterEqualI64, i64, >=); impl_cmp_eval_for_iso_num!(LessI64, i64, <); impl_cmp_eval_for_iso_num!(LessEqualI64, i64, <=); impl_cmp_eval_for_iso_num!(NotEqualI64, i64, !=); #[cfg(test)] mod tests { use super::*; #[test] fn test_cmp_eval_eq() { let size = 10i32; let c1 = Attr::from((0..size).into_iter()); let c2 = Attr::from((0..size).into_iter()); let c3 = Attr::new_single( PreciseType::i32(), Single::new(0i32, size as u16), Sel::All(size as u16), ); let c4 = Attr::new_single( PreciseType::i32(), Single::new(0i32, size as u16), Sel::All(size as u16), ); let c5 = Attr::new_null(PreciseType::i32(), size as u16); let eq = CmpKind::Equal; let res = eq.eval(&c1, &c2, None).unwrap(); let res = res.codec.as_bitmap().unwrap(); assert!(res.bools().all(|b| b)); let res = eq.eval(&c3, &c4, None).unwrap(); assert!(res.validity.is_all()); let res = res.codec.as_single().unwrap(); let value = res.view_bool(); assert!(value); let res = eq.eval(&c1, &c3, None).unwrap(); let res = res.codec.as_bitmap().unwrap(); assert!(res.get(0).unwrap()); assert!(res.bools().skip(1).all(|b| !b)); let res = eq.eval(&c4, &c2, None).unwrap(); let res = res.codec.as_bitmap().unwrap(); assert!(res.get(0).unwrap()); assert!(res.bools().skip(1).all(|b| !b)); let res = eq.eval(&c1, &c5, None).unwrap(); assert!(res.validity.is_none()); let res = eq.eval(&c5, &c1, None).unwrap(); assert!(res.validity.is_none()); let res = eq.eval(&c3, &c5, None).unwrap(); assert!(res.validity.is_none()); } #[test] fn test_cmp_eval_gt() { let c1 = Attr::from((0..64i32).into_iter()); let c2 = Attr::from((0..64i32).into_iter().rev()); let c3 = Attr::new_single(PreciseType::i32(), Single::new(5i32, 64), Sel::All(64)); let c4 = Attr::new_single(PreciseType::i32(), Single::new(15i32, 64), Sel::All(64)); let gt = CmpKind::Greater; let res = gt .eval(&c1, &c2, Some(&Sel::new_indexes(64, vec![5, 50]))) .unwrap(); let (valid, _) = res.bool_at(0).unwrap(); assert!(!valid); let (valid, value) = res.bool_at(5).unwrap(); assert!(valid && !value); let (valid, value) = res.bool_at(50).unwrap(); assert!(valid && value); let res = gt.eval(&c1, &c2, Some(&Sel::None(64))).unwrap(); assert_eq!(PreciseType::bool(), res.ty); let res = gt .eval(&c1, &c3, Some(&Sel::new_indexes(64, vec![1, 50]))) .unwrap(); let (valid, value) = res.bool_at(1).unwrap(); assert!(valid && !value);
}
let (valid, value) = res.bool_at(50).unwrap(); assert!(valid && value); let res = gt.eval(&c1, &c3, Some(&Sel::None(64))).unwrap(); assert_eq!(PreciseType::bool(), res.ty); let res = gt .eval(&c4, &c1, Some(&Sel::new_indexes(64, vec![1, 50]))) .unwrap(); let (valid, value) = res.bool_at(1).unwrap(); assert!(valid && value); let (valid, value) = res.bool_at(50).unwrap(); assert!(valid && !value); let res = gt.eval(&c4, &c1, Some(&Sel::None(64))).unwrap(); assert_eq!(PreciseType::bool(), res.ty); }
function_block-function_prefix_line
[ { "content": "pub trait DataSourceID: Clone + Copy + PartialEq + Eq + Hash + PartialOrd + Ord + Sized {\n\n /// resolve data source from expression\n\n fn from_expr(e: &Expr) -> Option<(Self, u32)>;\n\n}\n\n\n\nimpl DataSourceID for QueryID {\n\n #[inline]\n\n fn from_expr(e: &Expr) -> Option<(Self,...
Rust
lib/bobbin-sys/src/system.rs
thomasantony/bobbin-sdk
37375ca40351352a029aceb8b0cf17650a3624f6
use core::ops::{Deref, DerefMut}; use bobbin_mcu::mcu::Mcu; use heap::Heap; use tick::Tick; use pend::Pend; use irq_dispatch::IrqDispatcher; use console::Console; struct SystemToken; static mut SYSTEM_TOKEN: Option<SystemToken> = Some(SystemToken); pub trait SystemProvider { type Mcu: Mcu; type Clk; fn init() -> Self; fn init_mcu() -> Self::Mcu; fn init_clk() -> Self::Clk; fn init_heap() -> Heap; fn init_dispatcher() -> IrqDispatcher<Self::Mcu>; fn init_pend() -> Pend; fn init_tick(&Self::Clk) -> Tick; fn init_console(&Self::Clk, &mut Heap) {} fn init_led(&Self::Clk, &mut Heap) {} fn init_btn(&Self::Clk, &mut Heap) {} } pub struct System<S: SystemProvider> { provider: S, mcu: S::Mcu, clk: S::Clk, heap: Heap, tick: Tick, pend: Pend, dispatcher: IrqDispatcher<S::Mcu>, _private: () } impl<S: SystemProvider> System<S> { pub fn take() -> Self { let provider = S::init(); unsafe { asm!("cpsid i "); } unsafe { while let None = SYSTEM_TOKEN.take() {} } let mcu = S::init_mcu(); let clk = S::init_clk(); let mut heap = S::init_heap(); let dispatcher = S::init_dispatcher(); let tick = S::init_tick(&clk); let pend = S::init_pend(); S::init_console(&clk, &mut heap); S::init_led(&clk, &mut heap); S::init_btn(&clk, &mut heap); System { provider, mcu, clk, heap, tick, pend, dispatcher, _private: (), } } pub fn release(system: Self) { let System { provider, mcu, clk, heap, tick, pend, dispatcher, _private } = system; let _ = provider; let _ = mcu; let _ = clk; Tick::release(tick); Pend::release(pend); Heap::release(heap); IrqDispatcher::release(dispatcher); unsafe { SYSTEM_TOKEN = Some(SystemToken) } } pub fn mcu(&self) -> &S::Mcu { &self.mcu } pub fn mcu_mut(&mut self) -> &mut S::Mcu { &mut self.mcu } pub fn clk(&self) -> &S::Clk { &self.clk } pub fn clk_mut(&mut self) -> &mut S::Clk { &mut self.clk } pub fn heap(&self) -> &Heap { &self.heap } pub fn heap_mut(&mut self) -> &mut Heap { &mut self.heap } pub fn tick(&self) -> &Tick { &self.tick } pub fn tick_mut(&mut self) -> &mut Tick { &mut self.tick } pub fn pend(&self) -> &Pend { &self.pend } pub fn pend_mut(&mut self) -> &mut Pend { &mut self.pend } pub fn dispatcher(&self) -> &IrqDispatcher<S::Mcu> { &self.dispatcher } pub fn dispatcher_mut(&mut self) -> &mut IrqDispatcher<S::Mcu> { &mut self.dispatcher } pub fn console(&self) -> &'static Console<'static> { if let Some(console) = Console::borrow() { console } else { loop {} } } pub fn run<T, F: FnOnce(&Self) -> T>(&mut self, f: F) -> T { unsafe { asm!("cpsie i"); } let ret = f(&*self); unsafe { asm!("cpsid i"); } ret } } impl<S: SystemProvider> Deref for System<S> { type Target = S; fn deref(&self) -> &Self::Target { &self.provider } } impl<S: SystemProvider> DerefMut for System<S> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.provider } }
use core::ops::{Deref, DerefMut}; use bobbin_mcu::mcu::Mcu; use heap::Heap; use tick::Tick; use pend::Pend; use irq_dispatch::IrqDispatcher; use console::Console; struct SystemToken; static mut SYSTEM_TOKEN: Option<SystemToken> = Some(SystemToken); pub trait SystemProvider { type Mcu: Mcu; type Clk; fn init() -> Self; fn init_mcu() -> Self::Mcu; fn init_clk() -> Self::Clk; fn init_heap() -> Heap; fn init_dispatcher() -> IrqDispatcher<Self::Mcu>; fn init_pend() -> Pend; fn init_tick(&Self::Clk) -> Tick; fn init_console(&Self::Clk, &mut Heap) {} fn init_led(&Self::Clk, &mut Heap) {} fn init_btn(&Self::Clk, &mut Heap) {} } pub struct System<S: SystemProvider> { provider: S, mcu: S::Mcu, clk: S::Clk, heap: Heap, tick: Tick, pend: Pend, dispatcher: IrqDispatcher<S::Mcu>, _private: () } impl<S: SystemProvider> System<S> { pub fn take() -> Self { let provider = S::init(); unsafe { asm!("cpsid i "); } unsafe { while let None = SYSTEM_TOKEN.take() {} } let mcu = S::init_mcu(); let clk = S::init_clk(); let mut heap = S::init_heap(); let dispatcher = S::init_dispatcher(); let tick = S::init_tick(&clk); let pend = S::init_pend(); S::init_console(&clk, &mut heap); S::init_led(&clk, &mut heap); S::init_btn(&clk, &mut heap); System { provider, mcu, cl
pub fn release(system: Self) { let System { provider, mcu, clk, heap, tick, pend, dispatcher, _private } = system; let _ = provider; let _ = mcu; let _ = clk; Tick::release(tick); Pend::release(pend); Heap::release(heap); IrqDispatcher::release(dispatcher); unsafe { SYSTEM_TOKEN = Some(SystemToken) } } pub fn mcu(&self) -> &S::Mcu { &self.mcu } pub fn mcu_mut(&mut self) -> &mut S::Mcu { &mut self.mcu } pub fn clk(&self) -> &S::Clk { &self.clk } pub fn clk_mut(&mut self) -> &mut S::Clk { &mut self.clk } pub fn heap(&self) -> &Heap { &self.heap } pub fn heap_mut(&mut self) -> &mut Heap { &mut self.heap } pub fn tick(&self) -> &Tick { &self.tick } pub fn tick_mut(&mut self) -> &mut Tick { &mut self.tick } pub fn pend(&self) -> &Pend { &self.pend } pub fn pend_mut(&mut self) -> &mut Pend { &mut self.pend } pub fn dispatcher(&self) -> &IrqDispatcher<S::Mcu> { &self.dispatcher } pub fn dispatcher_mut(&mut self) -> &mut IrqDispatcher<S::Mcu> { &mut self.dispatcher } pub fn console(&self) -> &'static Console<'static> { if let Some(console) = Console::borrow() { console } else { loop {} } } pub fn run<T, F: FnOnce(&Self) -> T>(&mut self, f: F) -> T { unsafe { asm!("cpsie i"); } let ret = f(&*self); unsafe { asm!("cpsid i"); } ret } } impl<S: SystemProvider> Deref for System<S> { type Target = S; fn deref(&self) -> &Self::Target { &self.provider } } impl<S: SystemProvider> DerefMut for System<S> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.provider } }
k, heap, tick, pend, dispatcher, _private: (), } }
function_block-function_prefixed
[ { "content": "pub fn run_with_sys<S: SystemProvider>(mut sys: System<S>) -> ! {\n\n let ticker = Ticker::<S::Mcu>::new();\n\n let pender = Pender::new();\n\n\n\n let _guard_tick = match sys.tick_mut().register(&ticker) {\n\n Ok(guard) => guard,\n\n Err(_) => {\n\n println!(\"Er...
Rust
src/mesh.rs
littleTitan/3d-engine
81009f8949edd809815270f77eb5ed482da17243
use crate::{triangle::Triangle, vec3d::Vec3d}; use byteorder::{LittleEndian, ReadBytesExt}; use std::{ fs::{self, File}, io::prelude::*, }; #[derive(Clone)] pub struct Mesh { pub tris: Vec<Triangle>, pub is_over: bool, pub is_held: bool, pub pos: Vec3d, } impl Mesh { pub fn new(pos: Vec3d) -> Mesh { Mesh { tris: Vec::new(), is_over: false, is_held: false, pos: pos, } } #[allow(dead_code)] pub fn form_cube(&mut self) { self.tris = vec![ Triangle::new( Vec3d::new(-0.5, -0.5, -0.5), Vec3d::new(-0.5, 0.5, -0.5), Vec3d::new(0.5, 0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, -0.5, -0.5), Vec3d::new(0.5, 0.5, -0.5), Vec3d::new(0.5, -0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, -0.5), Vec3d::new(0.5, 0.5, -0.5), Vec3d::new(0.5, 0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, -0.5), Vec3d::new(0.5, 0.5, 0.5), Vec3d::new(0.5, -0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, 0.5), Vec3d::new(0.5, 0.5, 0.5), Vec3d::new(-0.5, 0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, 0.5), Vec3d::new(-0.5, 0.5, 0.5), Vec3d::new(-0.5, -0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, -0.5, 0.5), Vec3d::new(-0.5, 0.5, 0.5), Vec3d::new(-0.5, 0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, -0.5, 0.5), Vec3d::new(-0.5, 0.5, -0.5), Vec3d::new(-0.5, -0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, 0.5, -0.5), Vec3d::new(-0.5, 0.5, 0.5), Vec3d::new(0.5, 0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, 0.5, -0.5), Vec3d::new(0.5, 0.5, 0.5), Vec3d::new(0.5, 0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, 0.5), Vec3d::new(-0.5, -0.5, 0.5), Vec3d::new(-0.5, -0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, 0.5), Vec3d::new(-0.5, -0.5, -0.5), Vec3d::new(0.5, -0.5, -0.5), ) + self.pos, ]; } #[allow(dead_code)] pub fn x_axis_rotation(&mut self, r: f32, origin_y: f32, origin_z: f32) { for i in 0..self.tris.len() { self.tris[i].x_axis_rotation(r, origin_y, origin_z); } } #[allow(dead_code)] pub fn y_axis_rotation(&mut self, r: f32, origin_x: f32, origin_z: f32) { for i in 0..self.tris.len() { self.tris[i].y_axis_rotation(r, origin_x, origin_z); } } #[allow(dead_code)] pub fn z_axis_rotation(&mut self, r: f32, origin_x: f32, origin_y: f32) { for i in 0..self.tris.len() { self.tris[i].z_axis_rotation(r, origin_x, origin_y); } } #[allow(dead_code)] pub fn increment_x(&mut self, inc_x: f32) { self.pos.x += inc_x; for i in 0..self.tris.len() { self.tris[i].increment_x(inc_x); } } #[allow(dead_code)] pub fn increment_y(&mut self, inc_y: f32) { self.pos.y += inc_y; for i in 0..self.tris.len() { self.tris[i].increment_y(inc_y); } } #[allow(dead_code)] pub fn increment_z(&mut self, inc_z: f32) { self.pos.z += inc_z; for i in 0..self.tris.len() { self.tris[i].increment_z(inc_z); } } #[allow(dead_code)] pub fn from_file(&mut self, filename: &str) { println!("In file {}", filename); let file_type = filename.split('.').last().unwrap(); if file_type == "obj" { self.from_obj(filename); } else if file_type == "stl" { match self.from_stl_ascii(filename) { Ok(_) => (), Err(_e) => self.from_stl_bin(filename), } } } pub fn from_obj(&mut self, filename: &str) { let contents = fs::read_to_string(filename).expect("Something went wrong reading the file"); let mut points: Vec<Vec3d> = Vec::new(); for line in contents.lines() { if line.chars().next().unwrap() == 'v' { let mut e = line.split_whitespace(); e.next(); points.push(Vec3d { x: e.next().unwrap().parse::<f32>().unwrap(), y: e.next().unwrap().parse::<f32>().unwrap(), z: e.next().unwrap().parse::<f32>().unwrap(), }); } else if line.chars().next().unwrap() == 'f' { let mut e = line.split_whitespace(); e.next(); self.tris.push(Triangle::new( points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], )); } } } pub fn from_stl_bin(&mut self, filename: &str) { let mut file = File::open(filename).expect("file not found"); let mut header_buf = [0; 80]; let header = file .read(&mut header_buf[..]) .expect("Something went wrong reading the file"); let _contents = String::from_utf8_lossy(&header_buf[..header]); let mut n_tris_buf = [0; 4]; let n_tris_raw = file .read(&mut n_tris_buf[..]) .expect("Something went wrong reading the file"); let mut n_tris_dat = &n_tris_buf[..n_tris_raw]; let n_tris = *&n_tris_dat.read_u32::<LittleEndian>().unwrap() as i32; println!("{:?}", n_tris); let mut tri_buf = [0; 50]; for _i in 0..n_tris { let tri_raw = file .read(&mut tri_buf[..]) .expect("Something went wrong reading the file"); let mut data = &tri_buf[..tri_raw]; self.tris.push(Triangle::new_with_normal( Vec3d { x: *&data.read_f32::<LittleEndian>().unwrap(), y: *&data.read_f32::<LittleEndian>().unwrap(), z: *&data.read_f32::<LittleEndian>().unwrap(), }, Vec3d { x: *&data.read_f32::<LittleEndian>().unwrap(), y: *&data.read_f32::<LittleEndian>().unwrap(), z: *&data.read_f32::<LittleEndian>().unwrap(), }, Vec3d { x: *&data.read_f32::<LittleEndian>().unwrap(), y: *&data.read_f32::<LittleEndian>().unwrap(), z: *&data.read_f32::<LittleEndian>().unwrap(), }, Vec3d { x: *&data.read_f32::<LittleEndian>().unwrap(), y: *&data.read_f32::<LittleEndian>().unwrap(), z: *&data.read_f32::<LittleEndian>().unwrap(), }, )); &data.read_u16::<LittleEndian>().unwrap(); } } pub fn from_stl_ascii(&mut self, filename: &str) -> Result<(), std::io::Error> { let contents = fs::read_to_string(filename)?; let mut points: Vec<Vec3d> = Vec::new(); let mut normal: Vec3d = Vec3d::new(0.0, 0.0, 0.0); for line in contents.lines() { let mut e = line.split_whitespace(); let s = e.next().unwrap(); if s == "facet" { if e.next().unwrap() == "normal" { normal = Vec3d::new( e.next().unwrap().parse::<f32>().unwrap(), e.next().unwrap().parse::<f32>().unwrap(), e.next().unwrap().parse::<f32>().unwrap(), ); } } else if s == "vertex" { points.push(Vec3d::new( e.next().unwrap().parse::<f32>().unwrap(), e.next().unwrap().parse::<f32>().unwrap(), e.next().unwrap().parse::<f32>().unwrap(), )); } else if s == "endfacet" { self.tris.push(Triangle::new_with_normal( normal, points[0], points[1], points[2], )); normal = Vec3d::new(0.0, 0.0, 0.0); points = Vec::new(); } } Ok(()) } }
use crate::{triangle::Triangle, vec3d::Vec3d}; use byteorder::{LittleEndian, ReadBytesExt}; use std::{ fs::{self, File}, io::prelude::*, }; #[derive(Clone)] pub struct Mesh { pub tris: Vec<Triangle>, pub is_over: bool, pub is_held: bool, pub pos: Vec3d, } impl Mesh { pub fn new(pos: Vec3d) -> Mesh { Mesh { tris: Vec::new(), is_over: false, is_held: false, pos: pos, } } #[allow(dead_code)] pub fn form_cube(&mut self) { self.tris = vec![ Triangle::new( Vec3d::new(-0.5, -0.5, -0.5), Vec3d::new(-0.5, 0.5, -0.5), Vec3d::new(0.5, 0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, -0.5, -0.5), Vec3d::new(0.5, 0.5, -0.5), Vec3d::new(0.5, -0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, -0.5), Vec3d::new(0.5, 0.5, -0.5), Vec3d::new(0.5, 0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, -0.5), Vec3d::new(0.5, 0.5, 0.5), Vec3d::new(0.5, -0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, 0.5), Vec3d::new(0.5, 0.5, 0.5), Vec3d::new(-0.5, 0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, 0.5), Vec3d::new(-0.5, 0.5, 0.5), Vec3d::new(-0.5, -0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, -0.5, 0.5), Vec3d::new(-0.5, 0.5, 0.5), Vec3d::new(-0.5, 0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, -0.5, 0.5), Vec3d::new(-0.5, 0.5, -0.5), Vec3d::new(-0.5, -0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, 0.5, -0.5), Vec3d::new(-0.5, 0.5, 0.5), Vec3d::new(0.5, 0.5, 0.5), ) + self.pos, Triangle::new( Vec3d::new(-0.5, 0.5, -0.5), Vec3d::new(0.5, 0.5, 0.5), Vec3d::new(0.5, 0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, 0.5), Vec3d::new(-0.5, -0.5, 0.5), Vec3d::new(-0.5, -0.5, -0.5), ) + self.pos, Triangle::new( Vec3d::new(0.5, -0.5, 0.5), Vec3d::new(-0.5, -0.5, -0.5), Vec3d::new(0.5, -0.5, -0.5), ) + self.pos, ]; } #[allow(dead_code)] pub fn x_axis_rotation(&mut self, r: f32, origin_y: f32, origin_z: f32) { for i in 0..self.tris.len() { self.tris[i].x_axis_rotation(r, origin_y, origin_z); } } #[allow(dead_code)] pub fn y_axis_rotation(&mut self, r: f32, origin_x: f32, origin_z: f32) { for i in 0..self.tris.len() { self.tris[i].y_axis_rotation(r, origin_x, origin_z); } } #[allow(dead_code)] pub fn z_axis_rotation(&mut self, r: f32, origin_x: f32, origin_y: f32) { for i in 0..self.tris.len() { self.tris[i].z_axis_rotation(r, origin_x, origin_y); } } #[allow(dead_code)] pub fn increment_x(&mut self, inc_x: f32) { self.pos.x += inc_x; for i in 0..self.tris.len() { self.tris[i].increment_x(inc_x); } } #[allow(dead_code)] pub fn increment_y(&mut self, inc_y: f32) { self.pos.y += inc_y; for i in 0..self.tris.len() { self.tris[i].increment_y(inc_y); } } #[allow(dead_code)] pub fn increment_z(&mut self, inc_z: f32) { self.pos.z += inc_z; for i in 0..self.tris.len() { self.tris[i].increment_z(inc_z); } } #[allow(dead_code)] pub fn from_file(&mut self, filename: &str) { println!("In file {}", filename); let file_type = filename.split('.').last().unwrap(); if file_type == "obj" { self.from_obj(filename); } else if file_type == "stl" { match self.from_stl_ascii(filename) { Ok(_) => (), Err(_e) => self.from_stl_bin(filename), } } } pub fn from_obj(&mut self, filename: &str) { let contents = fs::read_to_string(filename).expect("Something went wrong reading the file"); let mut points: Vec<Vec3d> = Vec::new(); for line in contents.lines() { if line.chars().next().unwrap() == 'v' { let mut e = line.split_whitespace(); e.next(); points.push(Vec3d { x: e.next().unwrap().parse::<f32>().unwrap(), y: e.next().unwrap().parse::<f32>().unwrap(), z: e.next().unwrap().parse::<f32>().unwrap(), }); } else if line.chars().next().unwrap() == 'f' { let mut e = line.split_whitespace();
.expect("Something went wrong reading the file"); let _contents = String::from_utf8_lossy(&header_buf[..header]); let mut n_tris_buf = [0; 4]; let n_tris_raw = file .read(&mut n_tris_buf[..]) .expect("Something went wrong reading the file"); let mut n_tris_dat = &n_tris_buf[..n_tris_raw]; let n_tris = *&n_tris_dat.read_u32::<LittleEndian>().unwrap() as i32; println!("{:?}", n_tris); let mut tri_buf = [0; 50]; for _i in 0..n_tris { let tri_raw = file .read(&mut tri_buf[..]) .expect("Something went wrong reading the file"); let mut data = &tri_buf[..tri_raw]; self.tris.push(Triangle::new_with_normal( Vec3d { x: *&data.read_f32::<LittleEndian>().unwrap(), y: *&data.read_f32::<LittleEndian>().unwrap(), z: *&data.read_f32::<LittleEndian>().unwrap(), }, Vec3d { x: *&data.read_f32::<LittleEndian>().unwrap(), y: *&data.read_f32::<LittleEndian>().unwrap(), z: *&data.read_f32::<LittleEndian>().unwrap(), }, Vec3d { x: *&data.read_f32::<LittleEndian>().unwrap(), y: *&data.read_f32::<LittleEndian>().unwrap(), z: *&data.read_f32::<LittleEndian>().unwrap(), }, Vec3d { x: *&data.read_f32::<LittleEndian>().unwrap(), y: *&data.read_f32::<LittleEndian>().unwrap(), z: *&data.read_f32::<LittleEndian>().unwrap(), }, )); &data.read_u16::<LittleEndian>().unwrap(); } } pub fn from_stl_ascii(&mut self, filename: &str) -> Result<(), std::io::Error> { let contents = fs::read_to_string(filename)?; let mut points: Vec<Vec3d> = Vec::new(); let mut normal: Vec3d = Vec3d::new(0.0, 0.0, 0.0); for line in contents.lines() { let mut e = line.split_whitespace(); let s = e.next().unwrap(); if s == "facet" { if e.next().unwrap() == "normal" { normal = Vec3d::new( e.next().unwrap().parse::<f32>().unwrap(), e.next().unwrap().parse::<f32>().unwrap(), e.next().unwrap().parse::<f32>().unwrap(), ); } } else if s == "vertex" { points.push(Vec3d::new( e.next().unwrap().parse::<f32>().unwrap(), e.next().unwrap().parse::<f32>().unwrap(), e.next().unwrap().parse::<f32>().unwrap(), )); } else if s == "endfacet" { self.tris.push(Triangle::new_with_normal( normal, points[0], points[1], points[2], )); normal = Vec3d::new(0.0, 0.0, 0.0); points = Vec::new(); } } Ok(()) } }
e.next(); self.tris.push(Triangle::new( points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], )); } } } pub fn from_stl_bin(&mut self, filename: &str) { let mut file = File::open(filename).expect("file not found"); let mut header_buf = [0; 80]; let header = file .read(&mut header_buf[..])
random
[ { "content": "use ggez::{self, graphics::Vertex, nalgebra as na, nalgebra::geometry::Point2};\n\n\n\nuse std::ops::{Add, AddAssign, Mul, Sub};\n\n\n\n/// A Vec3d is a point in 3D space\n\n#[derive(Copy, Clone)]\n\npub struct Vec3d {\n\n pub x: f32,\n\n pub y: f32,\n\n pub z: f32,\n\n}\n\n\n\nimpl Vec3d...
Rust
api/src/services/item.rs
sanpii/oxfeed
a8d79bdd115b903bdb05ec475ef4fbc9c1b01108
use actix_web::web::{Data, Json, Path}; use oxfeed_common::item::Model; use std::collections::HashMap; pub(crate) fn scope() -> actix_web::Scope { actix_web::web::scope("/items") .service(content) .service(favorites) .service(patch) .service(unread) .service(read_all) .service(all) } #[actix_web::get("")] async fn all( elephantry: Data<elephantry::Pool>, pagination: actix_web::web::Query<oxfeed_common::Pagination>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { fetch( &elephantry, &identity, &elephantry::Where::new(), &pagination, ) } #[actix_web::get("/favorites")] async fn favorites( elephantry: Data<elephantry::Pool>, pagination: actix_web::web::Query<oxfeed_common::Pagination>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { fetch( &elephantry, &identity, &elephantry::Where::from("favorite", Vec::new()), &pagination.into_inner(), ) } #[actix_web::get("/unread")] async fn unread( elephantry: Data<elephantry::Pool>, pagination: actix_web::web::Query<oxfeed_common::Pagination>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { fetch( &elephantry, &identity, &elephantry::Where::from("not read", Vec::new()), &pagination.into_inner(), ) } pub(crate) fn fetch( elephantry: &elephantry::Pool, identity: &crate::Identity, filter: &elephantry::Where, pagination: &oxfeed_common::Pagination, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let model = elephantry.model::<Model>(); let items = model.all(&token, filter, pagination)?; let response = actix_web::HttpResponse::Ok().json(items); Ok(response) } #[actix_web::get("/{item_id}/content")] async fn content( elephantry: Data<elephantry::Pool>, path: Path<uuid::Uuid>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let item_id = Some(path.into_inner()); let sql = include_str!("../../sql/item_content.sql"); let content = elephantry .query::<Option<String>>(sql, &[&item_id, &token])? .next(); let response = match content { Some(content) => actix_web::HttpResponse::Ok().body(&content.unwrap_or_default()), None => actix_web::HttpResponse::NotFound().finish(), }; Ok(response) } #[actix_web::patch("/{item_id}")] async fn patch( elephantry: Data<elephantry::Pool>, path: Path<uuid::Uuid>, json: Json<serde_json::Value>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let item_id = path.into_inner(); match elephantry.model::<Model>().one(&token, &item_id)? { Some(_) => (), None => return Ok(actix_web::HttpResponse::NotFound().finish()), } let mut data = HashMap::new(); for (k, v) in json.as_object().unwrap() { let v = match v { serde_json::Value::Bool(v) => v as &dyn elephantry::ToSql, serde_json::Value::String(v) => v as &dyn elephantry::ToSql, _ => todo!(), }; data.insert(k.clone(), v); } let mut response = if !data.is_empty() { let item = elephantry.update_by_pk::<Model>(&elephantry::pk!(item_id), &data)?; match item { Some(_) => actix_web::HttpResponse::NoContent(), None => actix_web::HttpResponse::NotFound(), } } else { actix_web::HttpResponse::NoContent() }; Ok(response.finish()) } #[actix_web::post("/read")] async fn read_all( elephantry: Data<elephantry::Pool>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let sql = include_str!("../../sql/read_all.sql"); elephantry.query::<()>(sql, &[&token])?; let response = actix_web::HttpResponse::NoContent().finish(); Ok(response) }
use actix_web::web::{Data, Json, Path}; use oxfeed_common::item::Model; use std::collections::HashMap; pub(crate) fn scope() -> actix_web::Scope { actix_web::web::scope("/items") .service(content) .service(favorites) .service(patch) .service(unread) .service(read_all) .service(all) } #[actix_web::get("")] async fn all( elephantry: Data<elephantry::Pool>, pagination: actix_web::web::Query<oxfeed_common::Pagination>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { fetch( &elephantry, &identity, &elephantry::Where::new(), &pagination, ) } #[actix_web::get("/favorites")] async fn favorites( elephantry: Data<elephantry::Pool>, pagination: actix_web::web::Query<oxfeed_common::Pagination>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { fetch( &elephantry, &identity, &elephantry::Where::from("favorite", Vec::new()), &pagination.into_inner(), ) } #[actix_web::get("/unread")]
pub(crate) fn fetch( elephantry: &elephantry::Pool, identity: &crate::Identity, filter: &elephantry::Where, pagination: &oxfeed_common::Pagination, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let model = elephantry.model::<Model>(); let items = model.all(&token, filter, pagination)?; let response = actix_web::HttpResponse::Ok().json(items); Ok(response) } #[actix_web::get("/{item_id}/content")] async fn content( elephantry: Data<elephantry::Pool>, path: Path<uuid::Uuid>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let item_id = Some(path.into_inner()); let sql = include_str!("../../sql/item_content.sql"); let content = elephantry .query::<Option<String>>(sql, &[&item_id, &token])? .next(); let response = match content { Some(content) => actix_web::HttpResponse::Ok().body(&content.unwrap_or_default()), None => actix_web::HttpResponse::NotFound().finish(), }; Ok(response) } #[actix_web::patch("/{item_id}")] async fn patch( elephantry: Data<elephantry::Pool>, path: Path<uuid::Uuid>, json: Json<serde_json::Value>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let item_id = path.into_inner(); match elephantry.model::<Model>().one(&token, &item_id)? { Some(_) => (), None => return Ok(actix_web::HttpResponse::NotFound().finish()), } let mut data = HashMap::new(); for (k, v) in json.as_object().unwrap() { let v = match v { serde_json::Value::Bool(v) => v as &dyn elephantry::ToSql, serde_json::Value::String(v) => v as &dyn elephantry::ToSql, _ => todo!(), }; data.insert(k.clone(), v); } let mut response = if !data.is_empty() { let item = elephantry.update_by_pk::<Model>(&elephantry::pk!(item_id), &data)?; match item { Some(_) => actix_web::HttpResponse::NoContent(), None => actix_web::HttpResponse::NotFound(), } } else { actix_web::HttpResponse::NoContent() }; Ok(response.finish()) } #[actix_web::post("/read")] async fn read_all( elephantry: Data<elephantry::Pool>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let sql = include_str!("../../sql/read_all.sql"); elephantry.query::<()>(sql, &[&token])?; let response = actix_web::HttpResponse::NoContent().finish(); Ok(response) }
async fn unread( elephantry: Data<elephantry::Pool>, pagination: actix_web::web::Query<oxfeed_common::Pagination>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { fetch( &elephantry, &identity, &elephantry::Where::from("not read", Vec::new()), &pagination.into_inner(), ) }
function_block-full_function
[ { "content": "fn path(url: &str) -> std::path::PathBuf {\n\n let digest = ring::digest::digest(&ring::digest::SHA256, url.as_bytes());\n\n\n\n let mut path = digest\n\n .as_ref()\n\n .chunks(4)\n\n .map(|x| {\n\n x.iter()\n\n .fold(String::new(), |acc, b| for...
Rust
src/types/metadata.rs
Techcable/steven
2e99712cc8b467a236a8be57e6e43c888ba602e9
use std::collections::HashMap; use std::marker::PhantomData; use std::io; use std::fmt; use protocol; use protocol::Serializable; use format; use item; use shared::Position; pub struct MetadataKey<T: MetaValue> { index: i32, ty: PhantomData<T>, } impl <T: MetaValue> MetadataKey<T> { #[allow(dead_code)] const fn new(index: i32) -> MetadataKey<T> { MetadataKey { index: index, ty: PhantomData, } } } pub struct Metadata { map: HashMap<i32, Value>, } impl Metadata { pub fn new() -> Metadata { Metadata { map: HashMap::new() } } pub fn get<T: MetaValue>(&self, key: &MetadataKey<T>) -> Option<&T> { self.map.get(&key.index).map(T::unwrap) } pub fn put<T: MetaValue>(&mut self, key: &MetadataKey<T>, val: T) { self.map.insert(key.index, val.wrap()); } fn put_raw<T: MetaValue>(&mut self, index: i32, val: T) { self.map.insert(index, val.wrap()); } } impl Serializable for Metadata { fn read_from<R: io::Read>(buf: &mut R) -> Result<Self, protocol::Error> { let mut m = Metadata::new(); loop { let index = try!(u8::read_from(buf)) as i32; if index == 0xFF { break; } let ty = try!(u8::read_from(buf)); match ty { 0 => m.put_raw(index, try!(i8::read_from(buf))), 1 => m.put_raw(index, try!(protocol::VarInt::read_from(buf)).0), 2 => m.put_raw(index, try!(f32::read_from(buf))), 3 => m.put_raw(index, try!(String::read_from(buf))), 4 => m.put_raw(index, try!(format::Component::read_from(buf))), 5 => m.put_raw(index, try!(Option::<item::Stack>::read_from(buf))), 6 => m.put_raw(index, try!(bool::read_from(buf))), 7 => m.put_raw(index, [try!(f32::read_from(buf)), try!(f32::read_from(buf)), try!(f32::read_from(buf))]), 8 => m.put_raw(index, try!(Position::read_from(buf))), 9 => { if try!(bool::read_from(buf)) { m.put_raw(index, try!(Option::<Position>::read_from(buf))); } else { m.put_raw::<Option<Position>>(index, None); } } 10 => m.put_raw(index, try!(protocol::VarInt::read_from(buf))), 11 => { if try!(bool::read_from(buf)) { m.put_raw(index, try!(Option::<protocol::UUID>::read_from(buf))); } else { m.put_raw::<Option<protocol::UUID>>(index, None); } } 12 => m.put_raw(index, try!(protocol::VarInt::read_from(buf)).0 as u16), _ => return Err(protocol::Error::Err("unknown metadata type".to_owned())), } } Ok(m) } fn write_to<W: io::Write>(&self, buf: &mut W) -> Result<(), protocol::Error> { for (k, v) in &self.map { try!((*k as u8).write_to(buf)); match *v { Value::Byte(ref val) => { try!(u8::write_to(&0, buf)); try!(val.write_to(buf)); } Value::Int(ref val) => { try!(u8::write_to(&1, buf)); try!(protocol::VarInt(*val).write_to(buf)); } Value::Float(ref val) => { try!(u8::write_to(&2, buf)); try!(val.write_to(buf)); } Value::String(ref val) => { try!(u8::write_to(&3, buf)); try!(val.write_to(buf)); } Value::FormatComponent(ref val) => { try!(u8::write_to(&4, buf)); try!(val.write_to(buf)); } Value::OptionalItemStack(ref val) => { try!(u8::write_to(&5, buf)); try!(val.write_to(buf)); } Value::Bool(ref val) => { try!(u8::write_to(&6, buf)); try!(val.write_to(buf)); } Value::Vector(ref val) => { try!(u8::write_to(&7, buf)); try!(val[0].write_to(buf)); try!(val[1].write_to(buf)); try!(val[2].write_to(buf)); } Value::Position(ref val) => { try!(u8::write_to(&8, buf)); try!(val.write_to(buf)); } Value::OptionalPosition(ref val) => { try!(u8::write_to(&9, buf)); try!(val.is_some().write_to(buf)); try!(val.write_to(buf)); } Value::Direction(ref val) => { try!(u8::write_to(&10, buf)); try!(val.write_to(buf)); } Value::OptionalUUID(ref val) => { try!(u8::write_to(&11, buf)); try!(val.is_some().write_to(buf)); try!(val.write_to(buf)); } Value::Block(ref val) => { try!(u8::write_to(&11, buf)); try!(protocol::VarInt(*val as i32).write_to(buf)); } } } try!(u8::write_to(&0xFF, buf)); Ok(()) } } impl fmt::Debug for Metadata { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "Metadata[ ")); for (k, v) in &self.map { try!(write!(f, "{:?}={:?}, ", k, v)); } write!(f, "]") } } impl Default for Metadata { fn default() -> Metadata { Metadata::new() } } #[derive(Debug)] pub enum Value { Byte(i8), Int(i32), Float(f32), String(String), FormatComponent(format::Component), OptionalItemStack(Option<item::Stack>), Bool(bool), Vector([f32; 3]), Position(Position), OptionalPosition(Option<Position>), Direction(protocol::VarInt), OptionalUUID(Option<protocol::UUID>), Block(u16), } pub trait MetaValue { fn unwrap(&Value) -> &Self; fn wrap(self) -> Value; } impl MetaValue for i8 { fn unwrap(value: &Value) -> &Self { match *value { Value::Byte(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Byte(self) } } impl MetaValue for i32 { fn unwrap(value: &Value) -> &Self { match *value { Value::Int(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Int(self) } } impl MetaValue for f32 { fn unwrap(value: &Value) -> &Self { match *value { Value::Float(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Float(self) } } impl MetaValue for String { fn unwrap(value: &Value) -> &Self { match *value { Value::String(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::String(self) } } impl MetaValue for format::Component { fn unwrap(value: &Value) -> &Self { match *value { Value::FormatComponent(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::FormatComponent(self) } } impl MetaValue for Option<item::Stack> { fn unwrap(value: &Value) -> &Self { match *value { Value::OptionalItemStack(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::OptionalItemStack(self) } } impl MetaValue for bool { fn unwrap(value: &Value) -> &Self { match *value { Value::Bool(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Bool(self) } } impl MetaValue for [f32; 3] { fn unwrap(value: &Value) -> &Self { match *value { Value::Vector(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Vector(self) } } impl MetaValue for Position { fn unwrap(value: &Value) -> &Self { match *value { Value::Position(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Position(self) } } impl MetaValue for Option<Position> { fn unwrap(value: &Value) -> &Self { match *value { Value::OptionalPosition(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::OptionalPosition(self) } } impl MetaValue for protocol::VarInt { fn unwrap(value: &Value) -> &Self { match *value { Value::Direction(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Direction(self) } } impl MetaValue for Option<protocol::UUID> { fn unwrap(value: &Value) -> &Self { match *value { Value::OptionalUUID(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::OptionalUUID(self) } } impl MetaValue for u16 { fn unwrap(value: &Value) -> &Self { match *value { Value::Block(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Block(self) } } #[cfg(test)] mod test { use super::*; use std::marker::PhantomData; const TEST: MetadataKey<String> = MetadataKey { index: 0, ty: PhantomData, }; #[test] fn basic() { let mut m = Metadata::new(); m.put(&TEST, "Hello world".to_owned()); match m.get(&TEST) { Some(val) => { assert!(val == "Hello world"); } None => panic!("failed"), } } }
use std::collections::HashMap; use std::marker::PhantomData; use std::io; use std::fmt; use protocol; use protocol::Serializable; use format; use item; use shared::Position; pub struct MetadataKey<T: MetaValue> { index: i32, ty: PhantomData<T>, } impl <T: MetaValue> MetadataKey<T> { #[allow(dead_code)] const fn new(index: i32) -> MetadataKey<T> { MetadataKey { index: index, ty: PhantomData, } } } pub struct Metadata { map: HashMap<i32, Value>, } impl Metadata { pub fn new() -> Metadata { Metadata { map: HashMap::new() } } pub fn get<T: MetaValue>(&self, key: &MetadataKey<T>) -> Option<&T> { self.map.get(&key.index).map(T::unwrap) } pub fn put<T: MetaValue>(&mut self, key: &MetadataKey<T>, val: T) { self.map.insert(key.index, val.wrap()); } fn put_raw<T: MetaValue>(&mut self, index: i32, val: T) { self.map.insert(index, val.wrap()); } } impl Serializable for Metadata { fn read_from<R: io::Read>(buf: &mut R) -> Result<Self, protocol::Error> { let mut m = Metadata::new(); loop { let index = try!(u8::read_from(buf)) as i32; if index == 0xFF { break; } let ty = try!(u8::read_from(buf)); match ty { 0 => m.put_raw(index, try!(i8::read_from(buf))), 1 => m.put_raw(index, try!(protocol::VarInt::read_from(buf)).0), 2 => m.put_raw(index, try!(f32::read_from(buf))), 3 => m.put_raw(index, try!(String::read_from(buf))), 4 => m.put_raw(index, try!(format::Component::read_from(buf))), 5 => m.put_raw(index, try!(Option::<item::Stack>::read_from(buf))), 6 => m.put_raw(index, try!(bool::read_from(buf))), 7 => m.put_raw(index, [try!(f32::read_from(buf)), try!(f32::read_from(buf)), try!(f32::read_from(buf))]), 8 => m.put_raw(index, try!(Position::read_from(buf))), 9 => { if try!(bool::read_from(buf)) { m.put_raw(index, try!(Option::<Position>::read_from(buf))); } else { m.put_raw::<Option<Position>>(index, None); } } 10 => m.put_raw(index, try!(protocol::VarInt::read_from(buf))), 11 => { if try!(bool::read_from(buf)) { m.put_raw(index, try!(Option::<protocol::UUID>::read_from(buf))); } else { m.put_raw::<Option<protocol::UUID>>(index, None); } } 12 => m.put_raw(index, try!(protocol::VarInt::read_from(buf)).0 as u16), _ => return Err(protocol::Error::Err("unknown metadata type".to_owned())), } } Ok(m) } fn write_to<W: io::Write>(&self, buf: &mut W) -> Result<(), protocol::Error> { for (k, v) in &self.map { try!((*k as u8).write_to(buf)); match *v { Value::Byte(ref val) => { try!(u8::write_to(&0, buf)); try!(val.write_to(buf)); } Value::Int(ref val) => { try!(u8::write_to(&1, buf)); try!(protocol::VarInt(*val).write_to(buf)); } Value::Float(ref val) => { try!(u8::write_to(&2, buf)); try!(val.write_to(buf)); } Value::String(ref val) => { try!(u8::write_to(&3, buf)); try!(val.write_to(buf)); } Value::FormatComponent(ref val) => { try!(u8::write_to(&4, buf)); try!(val.write_to(buf)); } Value::OptionalItemStack(ref val) => { try!(u8::write_to(&5, buf)); try!(val.write_to(buf)); } Value::Bool(ref val) => { try!(u8::write_to(&6, buf)); try!(val.write_to(buf)); } Value::Vector(ref val) => { try!(u8::write_to(&7, buf)); try!(val[0].write_to(buf)); try!(val[1].write_to(buf)); try!(val[2].write_to(buf)); } Value::Position(ref val) => { try!(u8::write_to(&8, buf)); try!(val.write_to(buf)); } Value::OptionalPosition(ref val) => { try!(u8::write_to(&9, buf)); try!(val.is_some().write_to(buf)); try!(val.write_to(buf)); } Value::Direction(ref val) => { try!(u8::write_to(&10, buf)); try!(val.write_to(buf)); } Value::OptionalUUID(ref val) => { try!(u8::write_to(&11, buf)); try!(val.is_some().write_to(buf)); try!(val.write_to(buf)); } Value::Block(ref val) => { try!(u8::write_to(&11, buf)); try!(protocol::VarInt(*val as i32).write_to(buf)); } } } try!(u8::write_to(&0xFF, buf)); Ok(()) } } impl fmt::Debug for Metadata { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "Metadata[ ")); for (k, v) in &self.map { try!(write!(f, "{:?}={:?}, ", k, v)); } write!(f, "]") } } impl Default for Metadata { fn default() -> Metadata { Metadata::new() } } #[derive(Debug)] pub enum Value { Byte(i8), Int(i32), Float(f32), String(String), FormatComponent(format::Component), OptionalItemStack(Option<item::Stack>), Bool(bool), Vector([f32; 3]), Position(Position), OptionalPosition(Option<Position>), Direction(protocol::VarInt), OptionalUUID(Option<protocol::UUID>), Block(u16), } pub trait MetaValue { fn unwrap(&Value) -> &Self; fn wrap(self) -> Value; } impl MetaValue for i8 { fn unwrap(value: &Value) -> &Self { match *value { Value::Byte(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Byte(self) } } impl MetaValue for i32 { fn unwrap(value: &Value) -> &Self { match *value { Value::Int(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Int(self) } } impl MetaValue for f32 { fn unwrap(value: &Value) -> &Self { match *value { Value::Float(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Float(self) } } impl MetaValue for String { fn unwrap(value: &Value) -> &Self { match *value { Value::String(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::String(self) } } impl MetaValue for format::Component { fn unwrap(value: &Value) -> &Self { match *value { Value::FormatComponent(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::FormatComponent(self) } } impl MetaValue for Option<item::Stack> { fn unwrap(value: &Value) -> &Self { match *value { Value::OptionalItemStack(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::OptionalItemStack(self) } } impl MetaValue for bool { fn unwrap(value: &Value) -> &Self { match *value { Value::Bool(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Bool(self) } } impl MetaValue for [f32; 3] { fn unwrap(value: &Value) -> &Self { match *value { Value::Vector(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Vector(self) } } impl MetaValue for Position { fn unwrap(value: &Value) -> &Self { match *value { Value::Position(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Position(self) } } impl MetaValue for Option<Position> { fn unwrap(value: &Value) -> &Self { match *value { Value::OptionalPosition(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::OptionalPosition(self) } } impl MetaValue for protocol::VarInt { fn unwrap(value: &Value) -> &Self { match *value { Value::Direction(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Direction(self) } } impl MetaValue for Option<protocol::UUID> { fn unwrap(value: &Value) -> &Sel
fn wrap(self) -> Value { Value::OptionalUUID(self) } } impl MetaValue for u16 { fn unwrap(value: &Value) -> &Self { match *value { Value::Block(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Block(self) } } #[cfg(test)] mod test { use super::*; use std::marker::PhantomData; const TEST: MetadataKey<String> = MetadataKey { index: 0, ty: PhantomData, }; #[test] fn basic() { let mut m = Metadata::new(); m.put(&TEST, "Hello world".to_owned()); match m.get(&TEST) { Some(val) => { assert!(val == "Hello world"); } None => panic!("failed"), } } }
f { match *value { Value::OptionalUUID(ref val) => val, _ => panic!("incorrect key"), } }
function_block-function_prefixed
[ { "content": "pub fn read_string<R: io::Read>(buf: &mut R) -> Result<String, protocol::Error> {\n\n let len: i16 = try!(buf.read_i16::<BigEndian>());\n\n let mut ret = String::new();\n\n try!(buf.take(len as u64).read_to_string(&mut ret));\n\n Result::Ok(ret)\n\n}\n", "file_path": "src/nbt/mod.r...
Rust
src/tests.rs
ecstatic-morse/hrtb-logic
579b811bbdaf240e6439238d34dcd37454369a33
use insta::assert_display_snapshot; use crate::{short::*, Formula, Var}; macro_rules! vars { ($($x:ident),*) => { $( const $x: Var = var(stringify!($x).as_bytes()[0] as char); )* } } macro_rules! props { ($($x:ident),*) => { $( const $x: Formula = prop(stringify!($x)); )* } } vars!(A, B, C, D, E, X, Y, Z); props!(P, Q, R, S, T, U, V); #[test] fn nnf() { let nnf = Formula::negation_normal_form; assert_eq!(nnf(!!Q), Q); assert_eq!(nnf(!and(P, Q)), or(!P, !Q)); assert_eq!(nnf(!or(P, Q)), and(!P, !Q)); assert_eq!(nnf(!forall(A, P)), exists(A, !P)); assert_display_snapshot!(nnf(!forall(A, or(P, and(Q, R)))), @"∃'a.(¬P ∧ (¬Q ∨ ¬R))"); } #[test] fn dnf() { let dnf = Formula::disjunctive_normal_form; assert_display_snapshot!(dnf(and(or(P, Q), or(R, S))), @"(P ∧ R) ∨ (P ∧ S) ∨ (Q ∧ R) ∨ (Q ∧ S)"); assert_display_snapshot!(dnf(and(or(and(P, Q), R), S)), @"(P ∧ Q ∧ S) ∨ (R ∧ S)"); assert_display_snapshot!(dnf(and_([or(P, Q), or(R, S), or_([T, U, V])]))); } #[test] fn simp() { let simp = |mut f: Formula| { f.simplify(); f }; let top = || Formula::from(true); let bot = || Formula::from(false); assert_display_snapshot!(simp(and(top(), top())), @"True"); assert_display_snapshot!(simp(and(top(), bot())), @"False"); assert_display_snapshot!(simp(or(bot(), bot())), @"False"); assert_display_snapshot!(simp(or(top(), bot())), @"True"); } #[test] fn qe_atomless() { let _ = Y; let dnf = Formula::disjunctive_normal_form; let qe = |mut f: Formula| { f.eliminate_all_quantifiers(); f.simplify(); f.make_negation_normal_form(); f }; assert_display_snapshot!(qe(forall(B, subeq(B, A))), @"False"); assert_display_snapshot!(qe(forall(A, forall(B, subeq(B, A)))), @"False"); assert_display_snapshot!(qe(exists(B, and(subeq(A, B), subeq(B, C)))), @"'a ⊆ 'c"); assert_display_snapshot!(qe(forall(B, subeq(A, B))), @"'a ⊆ 'static"); assert_display_snapshot!( qe(exists(A, and_([subeq(B, A), subeq(C, A), subeq(A, D), subeq(A, E)]))), @"('b ⊆ 'd) ∧ ('b ⊆ 'e) ∧ ('c ⊆ 'd) ∧ ('c ⊆ 'e)" ); assert_display_snapshot!( qe(forall(A, implies(subeq(A, B), subeq(A, C)))), @"'b ⊆ 'c" ); assert_display_snapshot!( qe(forall(A, implies(and(subeq(A, B), subeq(A, C)), subeq(A, D)))), @"('b ⊆ 'd) ∨ ('c ⊆ 'd)" ); assert_display_snapshot!( qe(forall(A, implies(or(subeq(A, B), subeq(A, C)), subeq(A, D)))), @"('b ⊆ 'd) ∧ ('c ⊆ 'd)" ); assert_display_snapshot!( dnf(qe(forall(A, iff(or(subeq(A, B), subeq(A, C)), subeq(A, D))))), @"(('d ⊆ 'b) ∧ ('b ⊆ 'd) ∧ ('c ⊆ 'd)) ∨ (('d ⊆ 'c) ∧ ('b ⊆ 'd) ∧ ('c ⊆ 'd))" ); assert_display_snapshot!( qe(exists(Z, forall(X, iff(subeq(X, Z), and(subeq(X, A), subeq(X, B)))))), @"('a ⊆ 'b) ∨ ('b ⊆ 'a)" ); assert_display_snapshot!( qe(forall(A, forall(C, forall(B, implies(and(subeq(A, B), subeq(B, C)), subeq(A, C)))))), @"True" ); assert_display_snapshot!( qe(forall(A, forall(C, implies(subne(A, C), exists(B, and(subne(A, B), subne(B, C))))))), @"True" ); assert_display_snapshot!( qe(forall(A, forall(B, or(subeq(A, B), !subeq(A, B))))), @"True" ); assert_display_snapshot!( qe(forall(A, forall(B, or(subeq(A, B), subeq(B, A))))), @"False" ); assert_display_snapshot!( qe(forall(A, forall(B, or(!subeq(A, B), !subeq(B, A))))), @"False" ); assert_display_snapshot!( qe(exists(Z, and(!subeq(A, Z), !subeq(Z, B)))), @"¬('a ⊆ 'static)" ); } #[test] fn is_dnf() { let is_dnf = |f: Formula| f.is_disjunctive_normal_form(); assert!(!is_dnf(and(or(P, Q), or(R, S)))); assert!(is_dnf(or(and(P, Q), and(R, S)))); } #[test] fn has_nested_connective() { let has_nested = |f: Formula| f.has_nested_connective(); assert!(!has_nested(and(or(P, Q), or(R, S)))); assert!(has_nested(or(and(P, Q), or(R, S)))); } mod prop { use super::*; use proptest::prelude::*; const PROPS: &'static str = "PQRSTUVWYZ"; impl Arbitrary for Formula { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with((): Self::Parameters) -> Self::Strategy { let mut props: Vec<_> = (0..PROPS.len()) .map(|i| PROPS.get(i..=i).unwrap()) .map(prop) .collect(); props.push(true.into()); props.push(false.into()); let leaf = proptest::sample::select(props).no_shrink(); leaf.prop_recursive(6, 64, 10, |inner| { prop_oneof![ inner.clone().prop_map(|form| not(form)), proptest::collection::vec(inner.clone(), 2..6).prop_map(Formula::Or), proptest::collection::vec(inner.clone(), 2..6).prop_map(Formula::And), ] }) .boxed() } } proptest! { #[test] fn nnf(form in any::<Formula>()) { let nnf = form.negation_normal_form(); prop_assert!(nnf.is_negation_normal_form()); } #[test] fn dnf(form in any::<Formula>()) { let dnf = form.disjunctive_normal_form(); prop_assert!(dnf.is_disjunctive_normal_form()); } #[test] fn trivial(mut form in any::<Formula>()) { form.simplify_all_trivial_connectives(); prop_assert!(!form.has_trivial_connectives()); } } }
use insta::assert_display_snapshot; use crate::{short::*, Formula, Var}; macro_rules! vars { ($($x:ident),*) => { $( const $x: Var = var(stringify!($x).as_bytes()[0] as char); )* } } macro_rules! props { ($($x:ident),*) => { $( const $x: Formula = prop(stringify!($x)); )* } } vars!(A, B, C, D, E, X, Y, Z); props!(P, Q, R, S, T, U, V); #[test] fn nnf() { let nnf = Formula::negation_normal_form; assert_eq!(nnf(!!Q), Q); assert_eq!(nnf(!and(P, Q)), or(!P, !Q)); assert_eq!(nnf(!or(P, Q)), and(!P, !Q)); assert_eq!(nnf(!forall(A, P)), exists(A, !P)); assert_display_snapshot!(nnf(!forall(A, or(P, and(Q, R)))), @"∃'a.(¬P ∧ (¬Q ∨ ¬R))"); } #[test] fn dnf() { let dnf = Formula::disjunctive_normal_form; assert_display_snapshot!(dnf(and(or(P, Q), or(R, S))), @"(P ∧ R) ∨ (P ∧ S) ∨ (Q ∧ R) ∨ (Q ∧ S)"); assert_display_snapshot!(dnf(and(or(and(P, Q), R), S)), @"(P ∧ Q ∧ S) ∨ (R ∧ S)"); assert_display_snapshot!(dnf(and_([or(P, Q), or(R, S), or_([T, U, V])]))); } #[test] fn simp() { let simp = |mut f: Formula| { f.simplify(); f }; let top = || Formula::from(true); let bot = || Formula::fro
#[test] fn qe_atomless() { let _ = Y; let dnf = Formula::disjunctive_normal_form; let qe = |mut f: Formula| { f.eliminate_all_quantifiers(); f.simplify(); f.make_negation_normal_form(); f }; assert_display_snapshot!(qe(forall(B, subeq(B, A))), @"False"); assert_display_snapshot!(qe(forall(A, forall(B, subeq(B, A)))), @"False"); assert_display_snapshot!(qe(exists(B, and(subeq(A, B), subeq(B, C)))), @"'a ⊆ 'c"); assert_display_snapshot!(qe(forall(B, subeq(A, B))), @"'a ⊆ 'static"); assert_display_snapshot!( qe(exists(A, and_([subeq(B, A), subeq(C, A), subeq(A, D), subeq(A, E)]))), @"('b ⊆ 'd) ∧ ('b ⊆ 'e) ∧ ('c ⊆ 'd) ∧ ('c ⊆ 'e)" ); assert_display_snapshot!( qe(forall(A, implies(subeq(A, B), subeq(A, C)))), @"'b ⊆ 'c" ); assert_display_snapshot!( qe(forall(A, implies(and(subeq(A, B), subeq(A, C)), subeq(A, D)))), @"('b ⊆ 'd) ∨ ('c ⊆ 'd)" ); assert_display_snapshot!( qe(forall(A, implies(or(subeq(A, B), subeq(A, C)), subeq(A, D)))), @"('b ⊆ 'd) ∧ ('c ⊆ 'd)" ); assert_display_snapshot!( dnf(qe(forall(A, iff(or(subeq(A, B), subeq(A, C)), subeq(A, D))))), @"(('d ⊆ 'b) ∧ ('b ⊆ 'd) ∧ ('c ⊆ 'd)) ∨ (('d ⊆ 'c) ∧ ('b ⊆ 'd) ∧ ('c ⊆ 'd))" ); assert_display_snapshot!( qe(exists(Z, forall(X, iff(subeq(X, Z), and(subeq(X, A), subeq(X, B)))))), @"('a ⊆ 'b) ∨ ('b ⊆ 'a)" ); assert_display_snapshot!( qe(forall(A, forall(C, forall(B, implies(and(subeq(A, B), subeq(B, C)), subeq(A, C)))))), @"True" ); assert_display_snapshot!( qe(forall(A, forall(C, implies(subne(A, C), exists(B, and(subne(A, B), subne(B, C))))))), @"True" ); assert_display_snapshot!( qe(forall(A, forall(B, or(subeq(A, B), !subeq(A, B))))), @"True" ); assert_display_snapshot!( qe(forall(A, forall(B, or(subeq(A, B), subeq(B, A))))), @"False" ); assert_display_snapshot!( qe(forall(A, forall(B, or(!subeq(A, B), !subeq(B, A))))), @"False" ); assert_display_snapshot!( qe(exists(Z, and(!subeq(A, Z), !subeq(Z, B)))), @"¬('a ⊆ 'static)" ); } #[test] fn is_dnf() { let is_dnf = |f: Formula| f.is_disjunctive_normal_form(); assert!(!is_dnf(and(or(P, Q), or(R, S)))); assert!(is_dnf(or(and(P, Q), and(R, S)))); } #[test] fn has_nested_connective() { let has_nested = |f: Formula| f.has_nested_connective(); assert!(!has_nested(and(or(P, Q), or(R, S)))); assert!(has_nested(or(and(P, Q), or(R, S)))); } mod prop { use super::*; use proptest::prelude::*; const PROPS: &'static str = "PQRSTUVWYZ"; impl Arbitrary for Formula { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with((): Self::Parameters) -> Self::Strategy { let mut props: Vec<_> = (0..PROPS.len()) .map(|i| PROPS.get(i..=i).unwrap()) .map(prop) .collect(); props.push(true.into()); props.push(false.into()); let leaf = proptest::sample::select(props).no_shrink(); leaf.prop_recursive(6, 64, 10, |inner| { prop_oneof![ inner.clone().prop_map(|form| not(form)), proptest::collection::vec(inner.clone(), 2..6).prop_map(Formula::Or), proptest::collection::vec(inner.clone(), 2..6).prop_map(Formula::And), ] }) .boxed() } } proptest! { #[test] fn nnf(form in any::<Formula>()) { let nnf = form.negation_normal_form(); prop_assert!(nnf.is_negation_normal_form()); } #[test] fn dnf(form in any::<Formula>()) { let dnf = form.disjunctive_normal_form(); prop_assert!(dnf.is_disjunctive_normal_form()); } #[test] fn trivial(mut form in any::<Formula>()) { form.simplify_all_trivial_connectives(); prop_assert!(!form.has_trivial_connectives()); } } }
m(false); assert_display_snapshot!(simp(and(top(), top())), @"True"); assert_display_snapshot!(simp(and(top(), bot())), @"False"); assert_display_snapshot!(simp(or(bot(), bot())), @"False"); assert_display_snapshot!(simp(or(top(), bot())), @"True"); }
function_block-function_prefixed
[ { "content": "pub fn exists(var: Var, form: Formula) -> Formula {\n\n Formula::Bind(QuantifierKind::Exists, var, P::new(form))\n\n}\n\n\n\npub const fn subeq(sub: Var, sup: Var) -> Formula {\n\n Formula::SubsetEq { sub, sup }\n\n}\n\n\n", "file_path": "src/short.rs", "rank": 0, "score": 94200....
Rust
src/util.rs
lovesh/pixel-signature
93102638c2e4e35f4c136fddbcb18c8abc923ebd
use crate::amcl_wrapper::group_elem::GroupElement; use crate::errors::PixelError; use amcl_wrapper::field_elem::FieldElement; use crate::{VerkeyGroup, SignatureGroup}; pub struct GeneratorSet(pub VerkeyGroup, pub Vec<SignatureGroup>); impl GeneratorSet { pub fn new(T: u128, prefix: &str) -> Result<Self, PixelError> { Ok(GeneratorSet( VerkeyGroup::from_msg_hash(prefix.as_bytes()), Self::create_generators(T, prefix)?, )) } pub fn create_generators(T: u128, prefix: &str) -> Result<Vec<SignatureGroup>, PixelError> { let l = calculate_l(T)? as usize; let mut params = Vec::with_capacity(l + 2); for i in 0..(l + 2) { let s: String = prefix.to_string() + &i.to_string(); params.push(SignatureGroup::from_msg_hash(s.as_bytes())); } Ok(params) } } pub fn calculate_l(T: u128) -> Result<u8, PixelError> { if (T < 3) || (T == u128::max_value()) { return Err(PixelError::InvalidMaxTimePeriod { T }); } if !(T + 1).is_power_of_two() { return Err(PixelError::NonPowerOfTwo { T }); } let mut l = 0; let mut t = T; while t != 0 { t = t >> 1; l += 1; } Ok(l) } /* // Note: This is different from paper as of 30/6/19. The formula in paper is incorrect. If node is left child of parent then this node's number is 1 more than parent's node number If node is right child of parent then this node's number is 1 + parent's node number + half of the number of children of the parent. A more verbose form of the code would ne if node is left_of(parent) { node_num(node) = 1 + node_num(parent) } else { node_num(node) = 1 + node_num(parent) + (2^ (l - depth(node)) - 2) / 2 node_num(node) = 1 + node_num(parent) + (2^ (l - depth(node) - 1)) } */ pub fn path_to_node_num(path: &[u8], l: u8) -> Result<u128, PixelError> { if (path.len() as u8) >= l { return Err(PixelError::InvalidPath { path: path.to_vec(), l, }); } let mut t = 1u128; for i in 1..(path.len() + 1) { t += 1 + (((1 << (l - i as u8)) as u128 - 1) * (path[i - 1] - 1) as u128) as u128; } Ok(t) } pub fn from_node_num_to_path(t: u128, l: u8) -> Result<Vec<u8>, PixelError> { if t > ((1 << l) - 1) as u128 { return Err(PixelError::InvalidNodeNum { t, l }); } if t == 1 { return Ok(vec![]); } else { let two_l_1 = (1 << (l - 1)) as u128; if t <= two_l_1 { let mut path = vec![1]; path.append(&mut from_node_num_to_path(t - 1, l - 1)?); return Ok(path); } else { let mut path = vec![2]; path.append(&mut from_node_num_to_path(t - two_l_1, l - 1)?); return Ok(path); } } } pub fn node_successor_paths(t: u128, l: u8) -> Result<Vec<Vec<u8>>, PixelError> { if t > ((1 << l) - 1) as u128 { return Err(PixelError::InvalidNodeNum { t, l }); } if t == 1 { return Ok(vec![]); } else { let mut curr_path = vec![]; let mut successors = vec![]; let path = from_node_num_to_path(t, l)?; for p in path { if p == 1 { let mut s = curr_path.clone(); s.push(2); successors.push(s); } curr_path.push(p) } successors.reverse(); return Ok(successors); } } pub fn calculate_path_factor_using_t_l( t: u128, l: u8, gens: &GeneratorSet, ) -> Result<SignatureGroup, PixelError> { let path = from_node_num_to_path(t, l)?; calculate_path_factor(path, gens) } pub fn calculate_path_factor(path: Vec<u8>, gens: &GeneratorSet) -> Result<SignatureGroup, PixelError> { if gens.1.len() < (path.len() + 2) { return Err(PixelError::NotEnoughGenerators { n: path.len() + 2 }); } let mut sigma_1_1 = gens.1[1].clone(); for (i, p) in path.iter().enumerate() { if *p == 1 { sigma_1_1 += &gens.1[2 + i] } else { sigma_1_1 += &gens.1[2 + i].double() } } Ok(sigma_1_1) } #[cfg(test)] mod tests { use super::*; use std::collections::HashSet; use std::iter::FromIterator; #[test] fn test_calculate_l() { assert!(calculate_l(u128::max_value()).is_err()); let valid_Ts: HashSet<u128> = HashSet::from_iter(vec![3, 7, 15, 31, 63].iter().cloned()); assert_eq!(calculate_l(3).unwrap(), 2); assert_eq!(calculate_l(7).unwrap(), 3); assert_eq!(calculate_l(15).unwrap(), 4); assert_eq!(calculate_l(31).unwrap(), 5); for i in 1..65 { if !valid_Ts.contains(&i) { assert!(calculate_l(i).is_err()); } } } #[test] fn test_path_to_node_num() { assert!(path_to_node_num(&[1, 2, 1], 3).is_err()); assert!(path_to_node_num(&[1, 2, 1, 1], 3).is_err()); assert!(path_to_node_num(&[1, 1, 2, 1], 4).is_err()); assert!(path_to_node_num(&[2, 1, 2, 1, 1], 4).is_err()); assert_eq!(path_to_node_num(&[], 3).unwrap(), 1); assert_eq!(path_to_node_num(&[1], 3).unwrap(), 2); assert_eq!(path_to_node_num(&[2], 3).unwrap(), 5); assert_eq!(path_to_node_num(&[2, 1], 3).unwrap(), 6); assert_eq!(path_to_node_num(&[2, 2], 3).unwrap(), 7); assert_eq!(path_to_node_num(&[1, 1], 3).unwrap(), 3); assert_eq!(path_to_node_num(&[1, 1, 1], 4).unwrap(), 4); assert_eq!(path_to_node_num(&[1, 1, 2], 4).unwrap(), 5); assert_eq!(path_to_node_num(&[1, 2], 4).unwrap(), 6); assert_eq!(path_to_node_num(&[1, 2, 1], 4).unwrap(), 7); assert_eq!(path_to_node_num(&[1, 2, 2], 4).unwrap(), 8); assert_eq!(path_to_node_num(&[2], 4).unwrap(), 9); } #[test] fn test_from_node_num_to_path() { assert!(from_node_num_to_path(8, 3).is_err()); assert!(from_node_num_to_path(9, 3).is_err()); assert!(from_node_num_to_path(10, 3).is_err()); assert!(from_node_num_to_path(16, 4).is_err()); assert!(from_node_num_to_path(17, 4).is_err()); assert!(from_node_num_to_path(20, 4).is_err()); assert_eq!(from_node_num_to_path(1, 3).unwrap(), Vec::<u8>::new()); assert_eq!(from_node_num_to_path(2, 3).unwrap(), vec![1]); assert_eq!(from_node_num_to_path(3, 3).unwrap(), vec![1, 1]); assert_eq!(from_node_num_to_path(4, 3).unwrap(), vec![1, 2]); assert_eq!(from_node_num_to_path(5, 3).unwrap(), vec![2]); assert_eq!(from_node_num_to_path(6, 3).unwrap(), vec![2, 1]); assert_eq!(from_node_num_to_path(7, 3).unwrap(), vec![2, 2]); assert_eq!(from_node_num_to_path(15, 4).unwrap(), vec![2, 2, 2]); assert_eq!(from_node_num_to_path(14, 4).unwrap(), vec![2, 2, 1]); assert_eq!(from_node_num_to_path(13, 4).unwrap(), vec![2, 2]); assert_eq!(from_node_num_to_path(10, 4).unwrap(), vec![2, 1]); assert_eq!(from_node_num_to_path(11, 4).unwrap(), vec![2, 1, 1]); assert_eq!(from_node_num_to_path(12, 4).unwrap(), vec![2, 1, 2]); assert_eq!(from_node_num_to_path(8, 4).unwrap(), vec![1, 2, 2]); } #[test] fn test_node_successors_7() { let T = 7; let l = calculate_l(T).unwrap(); let successors = node_successor_paths(1, l).unwrap(); assert!(successors.is_empty()); let successors = node_successor_paths(2, l).unwrap(); assert_eq!(successors, vec![vec![2]]); let successors = node_successor_paths(3, l).unwrap(); assert_eq!(successors, vec![vec![1, 2], vec![2]]); let successors = node_successor_paths(4, l).unwrap(); assert_eq!(successors, vec![vec![2]]); let successors = node_successor_paths(5, l).unwrap(); assert!(successors.is_empty()); let successors = node_successor_paths(6, l).unwrap(); assert_eq!(successors, vec![vec![2, 2]]); let successors = node_successor_paths(7, l).unwrap(); assert!(successors.is_empty()); } #[test] fn test_node_successors_15() { let T = 15; let l = calculate_l(T).unwrap(); let successors = node_successor_paths(1, l).unwrap(); assert!(successors.is_empty()); let successors = node_successor_paths(2, l).unwrap(); assert_eq!(successors, vec![vec![2]]); let successors = node_successor_paths(3, l).unwrap(); assert_eq!(successors, vec![vec![1, 2], vec![2]]); let successors = node_successor_paths(4, l).unwrap(); assert_eq!(successors, vec![vec![1, 1, 2], vec![1, 2], vec![2]]); let successors = node_successor_paths(5, l).unwrap(); assert_eq!(successors, vec![vec![1, 2], vec![2]]); let successors = node_successor_paths(6, l).unwrap(); assert_eq!(successors, vec![vec![2]]); let successors = node_successor_paths(7, l).unwrap(); assert_eq!(successors, vec![vec![1, 2, 2], vec![2]]); let successors = node_successor_paths(9, l).unwrap(); assert!(successors.is_empty()); let successors = node_successor_paths(10, l).unwrap(); assert_eq!(successors, vec![vec![2, 2]]); let successors = node_successor_paths(11, l).unwrap(); assert_eq!(successors, vec![vec![2, 1, 2], vec![2, 2]]); let successors = node_successor_paths(12, l).unwrap(); assert_eq!(successors, vec![vec![2, 2]]); let successors = node_successor_paths(15, l).unwrap(); assert!(successors.is_empty()); } }
use crate::amcl_wrapper::group_elem::GroupElement; use crate::errors::PixelError; use amcl_wrapper::field_elem::FieldElement; use crate::{VerkeyGroup, SignatureGroup}; pub struct GeneratorSet(pub VerkeyGroup, pub Vec<SignatureGroup>); impl GeneratorSet { pub fn new(T: u128, prefix: &str) -> Result<Self, PixelError> { Ok(GeneratorSet( VerkeyGroup::from_msg_hash(prefix.as_bytes()), Self::create_generators(T, prefix)?, )) } pub fn create_generators(T: u128, prefix: &str) -> Result<Vec<SignatureGroup>, PixelError> { let l = calculate_l(T)? as usize; let mut params = Vec::with_capacity(l + 2); for i in 0..(l + 2) { let s: String = prefix.to_string() + &i.to_string(); params.push(SignatureGroup::from_msg_hash(s.as_bytes())); } Ok(params) } } pub fn calculate_l(T: u128) -> Result<u8, PixelError> { if (T < 3) || (T == u128::max_value()) { return Err(PixelError::InvalidMaxTimePeriod { T }); } if !(T + 1).is_power_of_two() { return Err(PixelError::NonPowerOfTwo { T }); } let mut l = 0; let mut t = T; while t != 0 { t = t >> 1; l += 1; } Ok(l) } /* // Note: This is different from paper as of 30/6/19. The formula in paper is incorrect. If node is left child of parent then this node's number is 1 more than parent's node number If node is right child of parent then this node's number is 1 + parent's node number + half of the number of children of the parent. A more verbose form of the code would ne if node is left_of(parent) { node_num(node) = 1 + node_num(parent) } else { node_num(node) = 1 + node_num(parent) + (2^ (l - depth(node)) - 2) / 2 node_num(node) = 1 + node_num(parent) + (2^ (l - depth(node) - 1)) } */ pub fn path_to_node_num(path: &[u8], l: u8) -> Result<u128, PixelError> { if (path.len() as u8) >= l { return Err(PixelError::InvalidPath { path: path.to_vec(), l, }); } let mut t = 1u128; for i in 1..(path.len() + 1) { t += 1 + (((1 << (l - i as u8)) as u128 - 1) * (path[i - 1] - 1) as u128) as u128; } Ok(t) } pub fn from_node_num_to_path(t: u128, l: u8) -> Result<Vec<u8>, PixelError> { if t > ((1 << l) - 1) as u128 { return Err(PixelError::InvalidNodeNum { t, l }); } if t == 1 { return Ok(vec![]); } else { let two_l_1 = (1 << (l - 1)) as u128; if t <= two_l_1 { let mut path = vec![1]; path.append(&mut from_node_num_to_path(t - 1, l - 1)?); return Ok(path); } else { let mut path = vec![2]; path.append(&mut from_node_num_to_path(t - two_l_1, l - 1)?); return Ok(path); } } } pub fn node_successor_paths(t: u128, l: u8) -> Result<Vec<Vec<u8>>, PixelError> { if t > ((1 << l) - 1) as u128 { return Err(PixelError::InvalidNodeNum { t, l }); } if t == 1 { return Ok(vec![]); } else { let mut curr_path = vec![]; let mut successors = vec![]; let path = from_node_num_to_path(t, l)?; for p in path { if p == 1 { let mut s = curr_path.clone(); s.push(2); successors.push(s); } curr_path.push(p) } successors.reverse(); return Ok(successors); } } pub fn calculate_path_factor_using_t_l( t: u128, l: u8, gens: &GeneratorSet, ) -> Result<SignatureGroup, PixelError> { let path = from_node_num_to_path(t, l)?; calculate_path_factor(path, gens) }
#[cfg(test)] mod tests { use super::*; use std::collections::HashSet; use std::iter::FromIterator; #[test] fn test_calculate_l() { assert!(calculate_l(u128::max_value()).is_err()); let valid_Ts: HashSet<u128> = HashSet::from_iter(vec![3, 7, 15, 31, 63].iter().cloned()); assert_eq!(calculate_l(3).unwrap(), 2); assert_eq!(calculate_l(7).unwrap(), 3); assert_eq!(calculate_l(15).unwrap(), 4); assert_eq!(calculate_l(31).unwrap(), 5); for i in 1..65 { if !valid_Ts.contains(&i) { assert!(calculate_l(i).is_err()); } } } #[test] fn test_path_to_node_num() { assert!(path_to_node_num(&[1, 2, 1], 3).is_err()); assert!(path_to_node_num(&[1, 2, 1, 1], 3).is_err()); assert!(path_to_node_num(&[1, 1, 2, 1], 4).is_err()); assert!(path_to_node_num(&[2, 1, 2, 1, 1], 4).is_err()); assert_eq!(path_to_node_num(&[], 3).unwrap(), 1); assert_eq!(path_to_node_num(&[1], 3).unwrap(), 2); assert_eq!(path_to_node_num(&[2], 3).unwrap(), 5); assert_eq!(path_to_node_num(&[2, 1], 3).unwrap(), 6); assert_eq!(path_to_node_num(&[2, 2], 3).unwrap(), 7); assert_eq!(path_to_node_num(&[1, 1], 3).unwrap(), 3); assert_eq!(path_to_node_num(&[1, 1, 1], 4).unwrap(), 4); assert_eq!(path_to_node_num(&[1, 1, 2], 4).unwrap(), 5); assert_eq!(path_to_node_num(&[1, 2], 4).unwrap(), 6); assert_eq!(path_to_node_num(&[1, 2, 1], 4).unwrap(), 7); assert_eq!(path_to_node_num(&[1, 2, 2], 4).unwrap(), 8); assert_eq!(path_to_node_num(&[2], 4).unwrap(), 9); } #[test] fn test_from_node_num_to_path() { assert!(from_node_num_to_path(8, 3).is_err()); assert!(from_node_num_to_path(9, 3).is_err()); assert!(from_node_num_to_path(10, 3).is_err()); assert!(from_node_num_to_path(16, 4).is_err()); assert!(from_node_num_to_path(17, 4).is_err()); assert!(from_node_num_to_path(20, 4).is_err()); assert_eq!(from_node_num_to_path(1, 3).unwrap(), Vec::<u8>::new()); assert_eq!(from_node_num_to_path(2, 3).unwrap(), vec![1]); assert_eq!(from_node_num_to_path(3, 3).unwrap(), vec![1, 1]); assert_eq!(from_node_num_to_path(4, 3).unwrap(), vec![1, 2]); assert_eq!(from_node_num_to_path(5, 3).unwrap(), vec![2]); assert_eq!(from_node_num_to_path(6, 3).unwrap(), vec![2, 1]); assert_eq!(from_node_num_to_path(7, 3).unwrap(), vec![2, 2]); assert_eq!(from_node_num_to_path(15, 4).unwrap(), vec![2, 2, 2]); assert_eq!(from_node_num_to_path(14, 4).unwrap(), vec![2, 2, 1]); assert_eq!(from_node_num_to_path(13, 4).unwrap(), vec![2, 2]); assert_eq!(from_node_num_to_path(10, 4).unwrap(), vec![2, 1]); assert_eq!(from_node_num_to_path(11, 4).unwrap(), vec![2, 1, 1]); assert_eq!(from_node_num_to_path(12, 4).unwrap(), vec![2, 1, 2]); assert_eq!(from_node_num_to_path(8, 4).unwrap(), vec![1, 2, 2]); } #[test] fn test_node_successors_7() { let T = 7; let l = calculate_l(T).unwrap(); let successors = node_successor_paths(1, l).unwrap(); assert!(successors.is_empty()); let successors = node_successor_paths(2, l).unwrap(); assert_eq!(successors, vec![vec![2]]); let successors = node_successor_paths(3, l).unwrap(); assert_eq!(successors, vec![vec![1, 2], vec![2]]); let successors = node_successor_paths(4, l).unwrap(); assert_eq!(successors, vec![vec![2]]); let successors = node_successor_paths(5, l).unwrap(); assert!(successors.is_empty()); let successors = node_successor_paths(6, l).unwrap(); assert_eq!(successors, vec![vec![2, 2]]); let successors = node_successor_paths(7, l).unwrap(); assert!(successors.is_empty()); } #[test] fn test_node_successors_15() { let T = 15; let l = calculate_l(T).unwrap(); let successors = node_successor_paths(1, l).unwrap(); assert!(successors.is_empty()); let successors = node_successor_paths(2, l).unwrap(); assert_eq!(successors, vec![vec![2]]); let successors = node_successor_paths(3, l).unwrap(); assert_eq!(successors, vec![vec![1, 2], vec![2]]); let successors = node_successor_paths(4, l).unwrap(); assert_eq!(successors, vec![vec![1, 1, 2], vec![1, 2], vec![2]]); let successors = node_successor_paths(5, l).unwrap(); assert_eq!(successors, vec![vec![1, 2], vec![2]]); let successors = node_successor_paths(6, l).unwrap(); assert_eq!(successors, vec![vec![2]]); let successors = node_successor_paths(7, l).unwrap(); assert_eq!(successors, vec![vec![1, 2, 2], vec![2]]); let successors = node_successor_paths(9, l).unwrap(); assert!(successors.is_empty()); let successors = node_successor_paths(10, l).unwrap(); assert_eq!(successors, vec![vec![2, 2]]); let successors = node_successor_paths(11, l).unwrap(); assert_eq!(successors, vec![vec![2, 1, 2], vec![2, 2]]); let successors = node_successor_paths(12, l).unwrap(); assert_eq!(successors, vec![vec![2, 2]]); let successors = node_successor_paths(15, l).unwrap(); assert!(successors.is_empty()); } }
pub fn calculate_path_factor(path: Vec<u8>, gens: &GeneratorSet) -> Result<SignatureGroup, PixelError> { if gens.1.len() < (path.len() + 2) { return Err(PixelError::NotEnoughGenerators { n: path.len() + 2 }); } let mut sigma_1_1 = gens.1[1].clone(); for (i, p) in path.iter().enumerate() { if *p == 1 { sigma_1_1 += &gens.1[2 + i] } else { sigma_1_1 += &gens.1[2 + i].double() } } Ok(sigma_1_1) }
function_block-full_function
[ { "content": "#[cfg(feature = \"VerkeyG1\")]\n\npub fn ate_multi_pairing(elems: Vec<(&SignatureGroup, &VerkeyGroup)>) -> GT {\n\n GT::ate_multi_pairing(\n\n elems\n\n .into_iter()\n\n .map(|(s, v)| (v, s))\n\n .collect::<Vec<(&VerkeyGroup, &SignatureGroup)>>(),\n\n ...
Rust
src/distance_.rs
huonw/hamming
4b528d75cfa2e102b6edc6c60b629cd986215437
fn naive(x: &[u8], y: &[u8]) -> u64 { assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |a, (b, c)| a + (*b ^ *c).count_ones() as u64) } #[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone)] pub struct DistanceError { _x: () } pub fn distance_fast(x: &[u8], y: &[u8]) -> Result<u64, DistanceError> { assert_eq!(x.len(), y.len()); const M1: u64 = 0x5555555555555555; const M2: u64 = 0x3333333333333333; const M4: u64 = 0x0F0F0F0F0F0F0F0F; const M8: u64 = 0x00FF00FF00FF00FF; type T30 = [u64; 30]; let (head1, thirty1, tail1) = unsafe { ::util::align_to::<_, T30>(x) }; let (head2, thirty2, tail2) = unsafe { ::util::align_to::<_, T30>(y) }; if head1.len() != head2.len() { return Err(DistanceError { _x: () }); } debug_assert_eq!(thirty1.len(), thirty2.len()); let mut count = naive(head1, head2) + naive(tail1, tail2); for (array1, array2) in thirty1.iter().zip(thirty2) { let mut acc = 0; for j_ in 0..10 { let j = j_ * 3; let mut count1 = array1[j] ^ array2[j]; let mut count2 = array1[j + 1] ^ array2[j + 1]; let mut half1 = array1[j + 2] ^ array2[j + 2]; let mut half2 = half1; half1 &= M1; half2 = (half2 >> 1) & M1; count1 -= (count1 >> 1) & M1; count2 -= (count2 >> 1) & M1; count1 += half1; count2 += half2; count1 = (count1 & M2) + ((count1 >> 2) & M2); count1 += (count2 & M2) + ((count2 >> 2) & M2); acc += (count1 & M4) + ((count1 >> 4) & M4); } acc = (acc & M8) + ((acc >> 8) & M8); acc = acc + (acc >> 16); acc = acc + (acc >> 32); count += acc & 0xFFFF; } Ok(count) } pub fn distance(x: &[u8], y: &[u8]) -> u64 { distance_fast(x, y) .ok() .unwrap_or_else(|| naive(x, y)) } #[cfg(test)] mod tests { use quickcheck as qc; use rand; #[test] fn naive_smoke() { let tests: &[(&[u8], &[u8], u64)] = &[ (&[], &[], 0), (&[0], &[0], 0), (&[0], &[0xFF], 8), (&[0b10101010], &[0b01010101], 8), (&[0b11111010], &[0b11110101], 4), (&[0; 10], &[0; 10], 0), (&[0xFF; 10], &[0x0F; 10], 4 * 10), (&[0x3B; 10000], &[0x3B; 10000], 0), (&[0x77; 10000], &[0x3B; 10000], 3 * 10000), ]; for &(x, y, expected) in tests { assert_eq!(super::naive(x, y), expected); } } #[test] fn distance_fast_qc() { fn prop(v: Vec<u8>, w: Vec<u8>, misalign: u8) -> qc::TestResult { let l = ::std::cmp::min(v.len(), w.len()); if l < misalign as usize { return qc::TestResult::discard() } let x = &v[misalign as usize..l]; let y = &w[misalign as usize..l]; qc::TestResult::from_bool(super::distance_fast(x, y).unwrap() == super::naive(x, y)) } qc::QuickCheck::new() .gen(qc::StdGen::new(rand::thread_rng(), 10_000)) .quickcheck(prop as fn(Vec<u8>,Vec<u8>,u8) -> qc::TestResult) } #[test] fn distance_fast_smoke_huge() { let v = vec![0b1001_1101; 10234567]; let w = vec![0b1111_1111; v.len()]; assert_eq!(super::distance_fast(&v, &v).unwrap(), 0); assert_eq!(super::distance_fast(&v, &w).unwrap(), 3 * w.len() as u64); } #[test] fn distance_smoke() { let v = vec![0; 10000]; let w = vec![0xFF; v.len()]; for len_ in 0..99 { let len = len_ * 10; for i in 0..8 { for j in 0..8 { assert_eq!(super::distance(&v[i..i+len], &w[j..j+len]), len as u64 * 8) } } } } }
fn naive(x: &[u8], y: &[u8]) -> u64 { assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |a, (b, c)| a + (*b ^ *c).count_ones() as u64) } #[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone)] pub struct DistanceError { _x: () } pub fn distance_fast(x: &[u8], y: &[u8]) -> Result<u64, DistanceError> { assert_eq!(x.len(), y.len()); const M1: u64 = 0x5555555555555555; const M2: u64 = 0x3333333333333333; const M4: u64 = 0x0F0F0F0F0F0F0F0F; const M8: u64 = 0x00FF00FF00FF00FF; type T30 = [u64; 30]; let (head1, thirty1, tail1) = unsafe { ::util::align_to::<_, T30>(x) }; let (head2, thirty2, tail2) = unsafe { ::util::align_to::<_, T30>(y) }; if head1.len() != head2.len() { return Err(DistanceError { _x: () }); } debug_assert_eq!(thirty1.len(), thirty2.len()); let mut count = naive(head1, head2) + naive(tail1, tail2); for (array1, array2) in thirty1.iter().zip(thirty2) { let mut acc = 0; for j_ in 0..10 { let j = j_ * 3; let mut count1 = array1[j] ^ array2[j]; let mut count2 = array1[j + 1] ^ array2[j + 1]; let mut half1 = array1[j + 2] ^ array2[j + 2]; let mut half2 = half1; half1 &= M1; half2 = (half2 >> 1) & M1; count1 -= (count1 >> 1) & M1; count2 -= (count2 >> 1) & M1; count1 += half1; count2 += half2; count1 = (count1 & M2) + ((count1 >> 2) & M2); count1 += (count2 & M2) + ((count2 >> 2) & M2); acc += (count1 & M4) + ((count1 >> 4) & M4); } acc = (acc & M8) + ((acc >> 8) & M8); acc = acc + (acc >> 16); acc = acc + (acc >> 32); count += acc & 0xFFFF; } Ok(count) } pub fn distance(x: &[u8], y: &[u8]) -> u64 { distance_fast(x, y) .ok() .unwrap_or_else(|| naive(x, y)) } #[cfg(test)] mod tests { use quickcheck as qc; use rand; #[test] fn naive_smoke() { let tests: &[(&[u8], &[u8], u64)] = &[ (&[], &[], 0), (&[0], &[0], 0), (&[0], &[0xFF], 8), (&[0b10101010], &[0b01010101], 8), (&[0b11111010], &[0b11110101], 4), (&[0; 10], &[0; 10], 0), (&[0xFF; 10], &[0x0F; 10], 4 * 10), (&[0x3B; 10000], &[0x3B; 10000], 0), (&[0x77; 10000], &[0x3B; 10000], 3 * 10000), ]; for &(x, y, expected) in tests { assert_eq!(super::naive(x, y), expected); } } #[test] fn distance_fast_qc() { fn prop(v: Vec<u8>, w: Vec<u8>, misalign: u8) -> qc::TestResult {
qc::QuickCheck::new() .gen(qc::StdGen::new(rand::thread_rng(), 10_000)) .quickcheck(prop as fn(Vec<u8>,Vec<u8>,u8) -> qc::TestResult) } #[test] fn distance_fast_smoke_huge() { let v = vec![0b1001_1101; 10234567]; let w = vec![0b1111_1111; v.len()]; assert_eq!(super::distance_fast(&v, &v).unwrap(), 0); assert_eq!(super::distance_fast(&v, &w).unwrap(), 3 * w.len() as u64); } #[test] fn distance_smoke() { let v = vec![0; 10000]; let w = vec![0xFF; v.len()]; for len_ in 0..99 { let len = len_ * 10; for i in 0..8 { for j in 0..8 { assert_eq!(super::distance(&v[i..i+len], &w[j..j+len]), len as u64 * 8) } } } } }
let l = ::std::cmp::min(v.len(), w.len()); if l < misalign as usize { return qc::TestResult::discard() } let x = &v[misalign as usize..l]; let y = &w[misalign as usize..l]; qc::TestResult::from_bool(super::distance_fast(x, y).unwrap() == super::naive(x, y)) }
function_block-function_prefix_line
[ { "content": "/// Computes the [Hamming\n\n/// weight](https://en.wikipedia.org/wiki/Hamming_weight) of `x`, that\n\n/// is, the population count, or number of 1.\n\n///\n\n/// This is a highly optimised version of the following naive version:\n\n///\n\n/// ```rust\n\n/// fn naive(x: &[u8]) -> u64 {\n\n/// ...
Rust
indy-credx/src/error.rs
animo/indy-shared-rs
063f7de369da0c3032225283773edf816a3eac21
use std::error::Error as StdError; use std::fmt::{self, Display, Formatter}; use std::result::Result as StdResult; use crate::ursa::errors::{UrsaCryptoError, UrsaCryptoErrorKind}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ErrorKind { Input, IOError, InvalidState, Unexpected, CredentialRevoked, InvalidUserRevocId, ProofRejected, RevocationRegistryFull, } impl ErrorKind { pub fn as_str(&self) -> &'static str { match self { Self::Input => "Input error", Self::IOError => "IO error", Self::InvalidState => "Invalid state", Self::Unexpected => "Unexpected error", Self::CredentialRevoked => "Credential revoked", Self::InvalidUserRevocId => "Invalid revocation accumulator index", Self::ProofRejected => "Proof rejected", Self::RevocationRegistryFull => "Revocation registry full", } } } impl Display for ErrorKind { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } #[derive(Debug)] pub struct Error { kind: ErrorKind, pub cause: Option<Box<dyn StdError + Send + Sync + 'static>>, pub message: Option<String>, } impl Error { pub fn from_msg<T: Into<String>>(kind: ErrorKind, msg: T) -> Self { Self { kind, cause: None, message: Some(msg.into()), } } pub fn from_opt_msg<T: Into<String>>(kind: ErrorKind, msg: Option<T>) -> Self { Self { kind, cause: None, message: msg.map(Into::into), } } pub fn kind(&self) -> ErrorKind { self.kind } pub fn with_cause<T: Into<Box<dyn StdError + Send + Sync>>>(mut self, err: T) -> Self { self.cause = Some(err.into()); self } } impl fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match (self.kind, &self.message) { (ErrorKind::Input, None) => write!(f, "{}", self.kind), (ErrorKind::Input, Some(msg)) => f.write_str(msg), (kind, None) => write!(f, "{}", kind), (kind, Some(msg)) => write!(f, "{}: {}", kind, msg), }?; if let Some(ref source) = self.cause { write!(f, " [{}]", source)?; } Ok(()) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { self.cause .as_ref() .map(|err| unsafe { std::mem::transmute(&**err) }) } } impl PartialEq for Error { fn eq(&self, other: &Self) -> bool { self.kind == other.kind && self.message == other.message } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Self { Self { kind, cause: None, message: None, } } } impl From<indy_utils::ValidationError> for Error { fn from(err: indy_utils::ValidationError) -> Self { Error::from_opt_msg(ErrorKind::Input, err.context) } } impl From<std::io::Error> for Error { fn from(err: std::io::Error) -> Self { Error::from(ErrorKind::IOError).with_cause(err) } } impl From<serde_json::Error> for Error { fn from(err: serde_json::Error) -> Self { Error::from(ErrorKind::Input).with_cause(err) } } impl From<UrsaCryptoError> for Error { fn from(err: UrsaCryptoError) -> Self { let message = err.to_string(); let kind = match err.kind() { UrsaCryptoErrorKind::InvalidState => ErrorKind::InvalidState, UrsaCryptoErrorKind::InvalidStructure => ErrorKind::Input, UrsaCryptoErrorKind::IOError => ErrorKind::IOError, UrsaCryptoErrorKind::InvalidRevocationAccumulatorIndex => ErrorKind::InvalidUserRevocId, UrsaCryptoErrorKind::RevocationAccumulatorIsFull => ErrorKind::RevocationRegistryFull, UrsaCryptoErrorKind::ProofRejected => ErrorKind::ProofRejected, UrsaCryptoErrorKind::CredentialRevoked => ErrorKind::CredentialRevoked, UrsaCryptoErrorKind::InvalidParam(_) => ErrorKind::Input, }; Error::from_msg(kind, message) } } impl<M> From<(ErrorKind, M)> for Error where M: fmt::Display + Send + Sync + 'static, { fn from((kind, msg): (ErrorKind, M)) -> Error { Error::from_msg(kind, msg.to_string()) } } macro_rules! err_msg { () => { $crate::error::Error::from($crate::error::ErrorKind::Input) }; ($kind:ident) => { $crate::error::Error::from($crate::error::ErrorKind::$kind) }; ($kind:ident, $($args:tt)+) => { $crate::error::Error::from_msg($crate::error::ErrorKind::$kind, format!($($args)+)) }; ($($args:tt)+) => { $crate::error::Error::from_msg($crate::error::ErrorKind::Input, format!($($args)+)) }; } macro_rules! err_map { ($($params:tt)*) => { |err| err_msg!($($params)*).with_cause(err) }; } pub trait ResultExt<T, E> { fn map_err_string(self) -> StdResult<T, String>; fn map_input_err<F, M>(self, mapfn: F) -> Result<T> where F: FnOnce() -> M, M: fmt::Display + Send + Sync + 'static; fn with_err_msg<M>(self, kind: ErrorKind, msg: M) -> Result<T> where M: fmt::Display + Send + Sync + 'static; fn with_input_err<M>(self, msg: M) -> Result<T> where M: fmt::Display + Send + Sync + 'static; } impl<T, E> ResultExt<T, E> for StdResult<T, E> where E: std::error::Error + Send + Sync + 'static, { fn map_err_string(self) -> StdResult<T, String> { self.map_err(|err| err.to_string()) } fn map_input_err<F, M>(self, mapfn: F) -> Result<T> where F: FnOnce() -> M, M: fmt::Display + Send + Sync + 'static, { self.map_err(|err| Error::from_msg(ErrorKind::Input, mapfn().to_string()).with_cause(err)) } fn with_err_msg<M>(self, kind: ErrorKind, msg: M) -> Result<T> where M: fmt::Display + Send + Sync + 'static, { self.map_err(|err| Error::from_msg(kind, msg.to_string()).with_cause(err)) } #[inline] fn with_input_err<M>(self, msg: M) -> Result<T> where M: fmt::Display + Send + Sync + 'static, { self.map_err(|err| Error::from_msg(ErrorKind::Input, msg.to_string()).with_cause(err)) } }
use std::error::Error as StdError; use std::fmt::{self, Display, Formatter}; use std::result::Result as StdResult; use crate::ursa::errors::{UrsaCryptoError, UrsaCryptoErrorKind}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ErrorKind { Input, IOError, InvalidState, Unexpected, CredentialRevoked, InvalidUserRevocId, ProofRejected, RevocationRegistryFull, } impl ErrorKind { pub fn as_str(&self) -> &'static str {
} } impl Display for ErrorKind { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } #[derive(Debug)] pub struct Error { kind: ErrorKind, pub cause: Option<Box<dyn StdError + Send + Sync + 'static>>, pub message: Option<String>, } impl Error { pub fn from_msg<T: Into<String>>(kind: ErrorKind, msg: T) -> Self { Self { kind, cause: None, message: Some(msg.into()), } } pub fn from_opt_msg<T: Into<String>>(kind: ErrorKind, msg: Option<T>) -> Self { Self { kind, cause: None, message: msg.map(Into::into), } } pub fn kind(&self) -> ErrorKind { self.kind } pub fn with_cause<T: Into<Box<dyn StdError + Send + Sync>>>(mut self, err: T) -> Self { self.cause = Some(err.into()); self } } impl fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match (self.kind, &self.message) { (ErrorKind::Input, None) => write!(f, "{}", self.kind), (ErrorKind::Input, Some(msg)) => f.write_str(msg), (kind, None) => write!(f, "{}", kind), (kind, Some(msg)) => write!(f, "{}: {}", kind, msg), }?; if let Some(ref source) = self.cause { write!(f, " [{}]", source)?; } Ok(()) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { self.cause .as_ref() .map(|err| unsafe { std::mem::transmute(&**err) }) } } impl PartialEq for Error { fn eq(&self, other: &Self) -> bool { self.kind == other.kind && self.message == other.message } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Self { Self { kind, cause: None, message: None, } } } impl From<indy_utils::ValidationError> for Error { fn from(err: indy_utils::ValidationError) -> Self { Error::from_opt_msg(ErrorKind::Input, err.context) } } impl From<std::io::Error> for Error { fn from(err: std::io::Error) -> Self { Error::from(ErrorKind::IOError).with_cause(err) } } impl From<serde_json::Error> for Error { fn from(err: serde_json::Error) -> Self { Error::from(ErrorKind::Input).with_cause(err) } } impl From<UrsaCryptoError> for Error { fn from(err: UrsaCryptoError) -> Self { let message = err.to_string(); let kind = match err.kind() { UrsaCryptoErrorKind::InvalidState => ErrorKind::InvalidState, UrsaCryptoErrorKind::InvalidStructure => ErrorKind::Input, UrsaCryptoErrorKind::IOError => ErrorKind::IOError, UrsaCryptoErrorKind::InvalidRevocationAccumulatorIndex => ErrorKind::InvalidUserRevocId, UrsaCryptoErrorKind::RevocationAccumulatorIsFull => ErrorKind::RevocationRegistryFull, UrsaCryptoErrorKind::ProofRejected => ErrorKind::ProofRejected, UrsaCryptoErrorKind::CredentialRevoked => ErrorKind::CredentialRevoked, UrsaCryptoErrorKind::InvalidParam(_) => ErrorKind::Input, }; Error::from_msg(kind, message) } } impl<M> From<(ErrorKind, M)> for Error where M: fmt::Display + Send + Sync + 'static, { fn from((kind, msg): (ErrorKind, M)) -> Error { Error::from_msg(kind, msg.to_string()) } } macro_rules! err_msg { () => { $crate::error::Error::from($crate::error::ErrorKind::Input) }; ($kind:ident) => { $crate::error::Error::from($crate::error::ErrorKind::$kind) }; ($kind:ident, $($args:tt)+) => { $crate::error::Error::from_msg($crate::error::ErrorKind::$kind, format!($($args)+)) }; ($($args:tt)+) => { $crate::error::Error::from_msg($crate::error::ErrorKind::Input, format!($($args)+)) }; } macro_rules! err_map { ($($params:tt)*) => { |err| err_msg!($($params)*).with_cause(err) }; } pub trait ResultExt<T, E> { fn map_err_string(self) -> StdResult<T, String>; fn map_input_err<F, M>(self, mapfn: F) -> Result<T> where F: FnOnce() -> M, M: fmt::Display + Send + Sync + 'static; fn with_err_msg<M>(self, kind: ErrorKind, msg: M) -> Result<T> where M: fmt::Display + Send + Sync + 'static; fn with_input_err<M>(self, msg: M) -> Result<T> where M: fmt::Display + Send + Sync + 'static; } impl<T, E> ResultExt<T, E> for StdResult<T, E> where E: std::error::Error + Send + Sync + 'static, { fn map_err_string(self) -> StdResult<T, String> { self.map_err(|err| err.to_string()) } fn map_input_err<F, M>(self, mapfn: F) -> Result<T> where F: FnOnce() -> M, M: fmt::Display + Send + Sync + 'static, { self.map_err(|err| Error::from_msg(ErrorKind::Input, mapfn().to_string()).with_cause(err)) } fn with_err_msg<M>(self, kind: ErrorKind, msg: M) -> Result<T> where M: fmt::Display + Send + Sync + 'static, { self.map_err(|err| Error::from_msg(kind, msg.to_string()).with_cause(err)) } #[inline] fn with_input_err<M>(self, msg: M) -> Result<T> where M: fmt::Display + Send + Sync + 'static, { self.map_err(|err| Error::from_msg(ErrorKind::Input, msg.to_string()).with_cause(err)) } }
match self { Self::Input => "Input error", Self::IOError => "IO error", Self::InvalidState => "Invalid state", Self::Unexpected => "Unexpected error", Self::CredentialRevoked => "Credential revoked", Self::InvalidUserRevocId => "Invalid revocation accumulator index", Self::ProofRejected => "Proof rejected", Self::RevocationRegistryFull => "Revocation registry full", }
if_condition
[ { "content": "pub fn set_last_error(error: Option<Error>) -> ErrorCode {\n\n trace!(\"credx_set_last_error\");\n\n let code = match error.as_ref() {\n\n Some(err) => err.kind().into(),\n\n None => ErrorCode::Success,\n\n };\n\n *LAST_ERROR.write().unwrap() = error;\n\n code\n\n}\n",...
Rust
rewryte-generator/src/sqlite.rs
Txuritan/rewryte
3ddcd0d8b374cbb8c895fe0282c828490641c5f6
use { crate::Error, rewryte_parser::models::{Column, ColumnDefault, Enum, ForeignKey, Item, Schema, Table, Types}, std::io, }; pub fn write_schema(schema: &Schema, writer: &mut impl io::Write) -> Result<(), Error> { for (i, item) in schema.items.iter().enumerate() { write_item(item, writer)?; writeln!(writer)?; if i != schema.items.len() - 1 { writeln!(writer)?; } } Ok(()) } pub fn write_item(item: &Item, writer: &mut impl io::Write) -> Result<(), Error> { match &item { Item::Enum(decl) => write_enum(decl, writer)?, Item::Table(decl) => write_table(decl, writer)?, } Ok(()) } pub fn write_enum(_decl: &Enum, _writer: &mut impl io::Write) -> Result<(), Error> { Ok(()) } pub fn write_table(decl: &Table, writer: &mut impl io::Write) -> Result<(), Error> { write!(writer, "CREATE TABLE")?; if decl.not_exists { write!(writer, " IF NOT EXISTS")?; } write!(writer, " {} (", decl.name)?; writeln!(writer)?; for column in &decl.columns { write_column(column, writer)?; write!(writer, ",")?; writeln!(writer)?; } write!(writer, " PRIMARY KEY (")?; for (i, primary) in decl.primary_keys.iter().enumerate() { write!(writer, "{}", primary)?; if i != decl.primary_keys.len() - 1 { write!(writer, ", ")?; } } write!(writer, ")")?; if !decl.foreign_keys.is_empty() { write!(writer, ",")?; writeln!(writer)?; for (i, foreign_key) in decl.foreign_keys.iter().enumerate() { write_foreign_key(foreign_key, writer)?; if i != decl.foreign_keys.len() - 1 { write!(writer, ",")?; writeln!(writer)?; } } if decl.unique_keys.is_empty() { writeln!(writer)?; } } else if decl.unique_keys.is_empty() { writeln!(writer)?; } if !decl.unique_keys.is_empty() { write!(writer, ",")?; writeln!(writer)?; write!(writer, " UNIQUE (")?; for (i, unique) in decl.unique_keys.iter().enumerate() { write!(writer, "{}", unique)?; if i != decl.unique_keys.len() - 1 { write!(writer, ", ")?; } } write!(writer, ")")?; writeln!(writer)?; } write!(writer, ");")?; Ok(()) } pub fn write_column(column: &Column, writer: &mut impl io::Write) -> Result<(), Error> { write!(writer, " {} ", column.name,)?; write_types(&column.typ, writer)?; if !column.null { write!(writer, " NOT NULL")?; } write_column_default(&column.default, writer)?; Ok(()) } pub fn write_types(types: &Types, writer: &mut impl io::Write) -> Result<(), Error> { write!( writer, "{}", match types { Types::Char | Types::Text => "TEXT", Types::Varchar => "VARCHAR", Types::Number | Types::SmallInt | Types::MediumInt | Types::Int | Types::Serial => { "INTEGER" } Types::BigInt => "BIGINT", Types::Float | Types::Real | Types::Numeric => "REAL", Types::Decimal => "DECIMAL", Types::DateTime => "DATETIME", Types::Boolean => "BOOLEAN", Types::Raw(raw) => raw, } )?; Ok(()) } pub fn write_column_default( column_default: &ColumnDefault, writer: &mut impl io::Write, ) -> Result<(), Error> { if column_default != &ColumnDefault::None { write!(writer, " DEFAULT")?; match column_default { ColumnDefault::Now => { write!(writer, " (DATETIME('now', 'utc'))")?; } ColumnDefault::Null => { write!(writer, " NULL")?; } ColumnDefault::Raw(raw) => { write!(writer, " {}", raw)?; } ColumnDefault::None => unreachable!(), } } Ok(()) } pub fn write_foreign_key( foreign_key: &ForeignKey, writer: &mut impl io::Write, ) -> Result<(), Error> { write!( writer, " FOREIGN KEY ({}) REFERENCES {}({}) ON UPDATE {} ON DELETE {}", foreign_key.local, foreign_key.table, foreign_key.foreign, foreign_key.update, foreign_key.delete, )?; Ok(()) } #[cfg(test)] mod tests { use {crate::sqlite::write_table, rewryte_parser::models::*}; #[test] fn simple() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, PRIMARY KEY (Id) );", utf8_buff.as_str() ); } #[test] fn multiple_primary_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Key", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Value", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Key", "Value"], foreign_keys: vec![], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Key TEXT NOT NULL, Value TEXT NOT NULL, PRIMARY KEY (Key, Value) );", utf8_buff.as_str() ); } #[test] fn foreign_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Other", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![ForeignKey { local: "Other", table: "Other", foreign: "Id", delete: Action::default(), update: Action::default(), }], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, Other TEXT NOT NULL, PRIMARY KEY (Id), FOREIGN KEY (Other) REFERENCES Other(Id) ON UPDATE NO ACTION ON DELETE NO ACTION );", utf8_buff.as_str() ); } #[test] fn unique_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Key", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Value", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![], unique_keys: vec!["Key"], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Key TEXT NOT NULL, Value TEXT NOT NULL, PRIMARY KEY (Id), UNIQUE (Key) );", utf8_buff.as_str() ); } #[test] fn unique_keys_foreign_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Other", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![ForeignKey { local: "Other", table: "Other", foreign: "Id", delete: Action::default(), update: Action::default(), }], unique_keys: vec!["Name"], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, Other TEXT NOT NULL, PRIMARY KEY (Id), FOREIGN KEY (Other) REFERENCES Other(Id) ON UPDATE NO ACTION ON DELETE NO ACTION, UNIQUE (Name) );", utf8_buff.as_str() ); } }
use { crate::Error, rewryte_parser::models::{Column, ColumnDefault, Enum, ForeignKey, Item, Schema, Table, Types}, std::io, }; pub fn write_schema(schema: &Schema, writer: &mut impl io::Write) -> Result<(), Error> { for (i, item) in schema.items.iter().enumerate() { write_item(item, writer)?; writeln!(writer)?; if i != schema.items.len() - 1 { writeln!(writer)?; } } Ok(()) }
pub fn write_enum(_decl: &Enum, _writer: &mut impl io::Write) -> Result<(), Error> { Ok(()) } pub fn write_table(decl: &Table, writer: &mut impl io::Write) -> Result<(), Error> { write!(writer, "CREATE TABLE")?; if decl.not_exists { write!(writer, " IF NOT EXISTS")?; } write!(writer, " {} (", decl.name)?; writeln!(writer)?; for column in &decl.columns { write_column(column, writer)?; write!(writer, ",")?; writeln!(writer)?; } write!(writer, " PRIMARY KEY (")?; for (i, primary) in decl.primary_keys.iter().enumerate() { write!(writer, "{}", primary)?; if i != decl.primary_keys.len() - 1 { write!(writer, ", ")?; } } write!(writer, ")")?; if !decl.foreign_keys.is_empty() { write!(writer, ",")?; writeln!(writer)?; for (i, foreign_key) in decl.foreign_keys.iter().enumerate() { write_foreign_key(foreign_key, writer)?; if i != decl.foreign_keys.len() - 1 { write!(writer, ",")?; writeln!(writer)?; } } if decl.unique_keys.is_empty() { writeln!(writer)?; } } else if decl.unique_keys.is_empty() { writeln!(writer)?; } if !decl.unique_keys.is_empty() { write!(writer, ",")?; writeln!(writer)?; write!(writer, " UNIQUE (")?; for (i, unique) in decl.unique_keys.iter().enumerate() { write!(writer, "{}", unique)?; if i != decl.unique_keys.len() - 1 { write!(writer, ", ")?; } } write!(writer, ")")?; writeln!(writer)?; } write!(writer, ");")?; Ok(()) } pub fn write_column(column: &Column, writer: &mut impl io::Write) -> Result<(), Error> { write!(writer, " {} ", column.name,)?; write_types(&column.typ, writer)?; if !column.null { write!(writer, " NOT NULL")?; } write_column_default(&column.default, writer)?; Ok(()) } pub fn write_types(types: &Types, writer: &mut impl io::Write) -> Result<(), Error> { write!( writer, "{}", match types { Types::Char | Types::Text => "TEXT", Types::Varchar => "VARCHAR", Types::Number | Types::SmallInt | Types::MediumInt | Types::Int | Types::Serial => { "INTEGER" } Types::BigInt => "BIGINT", Types::Float | Types::Real | Types::Numeric => "REAL", Types::Decimal => "DECIMAL", Types::DateTime => "DATETIME", Types::Boolean => "BOOLEAN", Types::Raw(raw) => raw, } )?; Ok(()) } pub fn write_column_default( column_default: &ColumnDefault, writer: &mut impl io::Write, ) -> Result<(), Error> { if column_default != &ColumnDefault::None { write!(writer, " DEFAULT")?; match column_default { ColumnDefault::Now => { write!(writer, " (DATETIME('now', 'utc'))")?; } ColumnDefault::Null => { write!(writer, " NULL")?; } ColumnDefault::Raw(raw) => { write!(writer, " {}", raw)?; } ColumnDefault::None => unreachable!(), } } Ok(()) } pub fn write_foreign_key( foreign_key: &ForeignKey, writer: &mut impl io::Write, ) -> Result<(), Error> { write!( writer, " FOREIGN KEY ({}) REFERENCES {}({}) ON UPDATE {} ON DELETE {}", foreign_key.local, foreign_key.table, foreign_key.foreign, foreign_key.update, foreign_key.delete, )?; Ok(()) } #[cfg(test)] mod tests { use {crate::sqlite::write_table, rewryte_parser::models::*}; #[test] fn simple() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, PRIMARY KEY (Id) );", utf8_buff.as_str() ); } #[test] fn multiple_primary_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Key", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Value", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Key", "Value"], foreign_keys: vec![], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Key TEXT NOT NULL, Value TEXT NOT NULL, PRIMARY KEY (Key, Value) );", utf8_buff.as_str() ); } #[test] fn foreign_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Other", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![ForeignKey { local: "Other", table: "Other", foreign: "Id", delete: Action::default(), update: Action::default(), }], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, Other TEXT NOT NULL, PRIMARY KEY (Id), FOREIGN KEY (Other) REFERENCES Other(Id) ON UPDATE NO ACTION ON DELETE NO ACTION );", utf8_buff.as_str() ); } #[test] fn unique_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Key", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Value", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![], unique_keys: vec!["Key"], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Key TEXT NOT NULL, Value TEXT NOT NULL, PRIMARY KEY (Id), UNIQUE (Key) );", utf8_buff.as_str() ); } #[test] fn unique_keys_foreign_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Other", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![ForeignKey { local: "Other", table: "Other", foreign: "Id", delete: Action::default(), update: Action::default(), }], unique_keys: vec!["Name"], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, Other TEXT NOT NULL, PRIMARY KEY (Id), FOREIGN KEY (Other) REFERENCES Other(Id) ON UPDATE NO ACTION ON DELETE NO ACTION, UNIQUE (Name) );", utf8_buff.as_str() ); } }
pub fn write_item(item: &Item, writer: &mut impl io::Write) -> Result<(), Error> { match &item { Item::Enum(decl) => write_enum(decl, writer)?, Item::Table(decl) => write_table(decl, writer)?, } Ok(()) }
function_block-full_function
[ { "content": "pub fn write_item(item: &Item, writer: &mut impl io::Write) -> Result<(), Error> {\n\n match &item {\n\n Item::Enum(decl) => write_enum(decl, writer)?,\n\n Item::Table(decl) => write_table(decl, writer)?,\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "rewryte-generator/...
Rust
src/serde/ser/from_seq/header.rs
snaar/chopper
62a0305233f16b5001b433c8ef83844f12794173
use serde::ser::{Impossible, SerializeSeq, SerializeStruct, SerializeTuple, SerializeTupleStruct}; use serde::{Serialize, Serializer}; use crate::chopper::types::{FieldType, Header}; use crate::serde::ser::error::SerError; use crate::serde::ser::field_type::to_field_type; pub fn to_header<T>(value: &T, timestamp_field_index: usize) -> Result<Header, SerError> where T: Serialize + ?Sized, { value.serialize(HeaderSerializer::new(timestamp_field_index)) } pub struct HeaderSerializer { timestamp_field_index: usize, field_types: Vec<FieldType>, } impl HeaderSerializer { pub fn new(timestamp_field_index: usize) -> HeaderSerializer { HeaderSerializer { timestamp_field_index, field_types: Vec::new(), } } fn into_header(self) -> Result<Header, SerError> { if self.field_types.is_empty() { return Err(SerError::NoTimestampField); } let mut field_types = self.field_types; let field_names = Header::generate_default_field_names(field_types.len() - 1); let idx = self.timestamp_field_index; if field_types[idx] != FieldType::Long { return Err(SerError::InvalidTimestampFieldType); } field_types.remove(idx); Ok(Header::new(field_names, field_types)) } } impl Serializer for HeaderSerializer { type Ok = Header; type Error = SerError; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>; type SerializeMap = Impossible<Self::Ok, Self::Error>; type SerializeStruct = Self; type SerializeStructVariant = Impossible<Self::Ok, Self::Error>; fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Serialize, { value.serialize(self) } fn serialize_newtype_struct<T: ?Sized>( self, _name: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: Serialize, { value.serialize(self) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { Ok(self) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> { Ok(self) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error> { Ok(self) } fn serialize_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct, Self::Error> { Ok(self) } return_error! { <type_not_supported> bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none unit unit_struct unit_variant newtype_variant tuple_variant map struct_variant } } impl SerializeSeq for HeaderSerializer { type Ok = Header; type Error = SerError; fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize, { self.field_types.push(to_field_type(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { self.into_header() } } impl SerializeTuple for HeaderSerializer { type Ok = Header; type Error = SerError; fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize, { self.field_types.push(to_field_type(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { self.into_header() } } impl SerializeTupleStruct for HeaderSerializer { type Ok = Header; type Error = SerError; fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize, { self.field_types.push(to_field_type(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { self.into_header() } } impl SerializeStruct for HeaderSerializer { type Ok = Header; type Error = SerError; fn serialize_field<T: ?Sized>( &mut self, _key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize, { self.field_types.push(to_field_type(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { self.into_header() } } #[cfg(test)] mod tests { use crate::chopper::types::{FieldType, Header}; use crate::serde::ser::from_seq::header::to_header; #[test] fn test() { let row = ( false, 5u8, vec![b'a'], 'a', 6.6f64, 7.7f32, 8i32, 123u64, 9i64, 10i16, "a".to_string(), ); let header = to_header(&row, 7).unwrap(); assert_eq!(header.field_names().len(), 10); assert_eq!(header.field_types().len(), 10); assert_eq!( header.field_names(), &Header::generate_default_field_names(10) ); assert_eq!( header.field_types(), &vec![ FieldType::Boolean, FieldType::Byte, FieldType::ByteBuf, FieldType::Char, FieldType::Double, FieldType::Float, FieldType::Int, FieldType::Long, FieldType::Short, FieldType::String, ] ); } }
use serde::ser::{Impossible, SerializeSeq, SerializeStruct, SerializeTuple, SerializeTupleStruct}; use serde::{Serialize, Serializer}; use crate::chopper::types::{FieldType, Header}; use crate::serde::ser::error::SerError; use crate::serde::ser::field_type::to_field_type; pub fn to_header<T>(value: &T, timestamp_field_
_index)) } pub struct HeaderSerializer { timestamp_field_index: usize, field_types: Vec<FieldType>, } impl HeaderSerializer { pub fn new(timestamp_field_index: usize) -> HeaderSerializer { HeaderSerializer { timestamp_field_index, field_types: Vec::new(), } } fn into_header(self) -> Result<Header, SerError> { if self.field_types.is_empty() { return Err(SerError::NoTimestampField); } let mut field_types = self.field_types; let field_names = Header::generate_default_field_names(field_types.len() - 1); let idx = self.timestamp_field_index; if field_types[idx] != FieldType::Long { return Err(SerError::InvalidTimestampFieldType); } field_types.remove(idx); Ok(Header::new(field_names, field_types)) } } impl Serializer for HeaderSerializer { type Ok = Header; type Error = SerError; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>; type SerializeMap = Impossible<Self::Ok, Self::Error>; type SerializeStruct = Self; type SerializeStructVariant = Impossible<Self::Ok, Self::Error>; fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Serialize, { value.serialize(self) } fn serialize_newtype_struct<T: ?Sized>( self, _name: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: Serialize, { value.serialize(self) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { Ok(self) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> { Ok(self) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error> { Ok(self) } fn serialize_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct, Self::Error> { Ok(self) } return_error! { <type_not_supported> bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none unit unit_struct unit_variant newtype_variant tuple_variant map struct_variant } } impl SerializeSeq for HeaderSerializer { type Ok = Header; type Error = SerError; fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize, { self.field_types.push(to_field_type(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { self.into_header() } } impl SerializeTuple for HeaderSerializer { type Ok = Header; type Error = SerError; fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize, { self.field_types.push(to_field_type(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { self.into_header() } } impl SerializeTupleStruct for HeaderSerializer { type Ok = Header; type Error = SerError; fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize, { self.field_types.push(to_field_type(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { self.into_header() } } impl SerializeStruct for HeaderSerializer { type Ok = Header; type Error = SerError; fn serialize_field<T: ?Sized>( &mut self, _key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize, { self.field_types.push(to_field_type(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { self.into_header() } } #[cfg(test)] mod tests { use crate::chopper::types::{FieldType, Header}; use crate::serde::ser::from_seq::header::to_header; #[test] fn test() { let row = ( false, 5u8, vec![b'a'], 'a', 6.6f64, 7.7f32, 8i32, 123u64, 9i64, 10i16, "a".to_string(), ); let header = to_header(&row, 7).unwrap(); assert_eq!(header.field_names().len(), 10); assert_eq!(header.field_types().len(), 10); assert_eq!( header.field_names(), &Header::generate_default_field_names(10) ); assert_eq!( header.field_types(), &vec![ FieldType::Boolean, FieldType::Byte, FieldType::ByteBuf, FieldType::Char, FieldType::Double, FieldType::Float, FieldType::Int, FieldType::Long, FieldType::Short, FieldType::String, ] ); } }
index: usize) -> Result<Header, SerError> where T: Serialize + ?Sized, { value.serialize(HeaderSerializer::new(timestamp_field
function_block-random_span
[]
Rust
tests/functional.rs
pwalski/tchannel_rs
17169ae7d689f255c26be985589867a60045d724
#[cfg(test)] #[macro_use] extern crate log; #[macro_use] extern crate serial_test; use std::sync::Arc; use bytes::Bytes; use test_case::test_case; use tchannel_rs::handler::{HandlerResult, RequestHandler}; use tchannel_rs::messages::MessageChannel; use tchannel_rs::messages::RawMessage; use tchannel_rs::Config; use tchannel_rs::{SubChannel, TChannel, TResult}; #[test_case("service", "endpoint", "header", "body"; "Basic")] #[test_case("service", "endpoint", "header", ""; "Empty body")] #[test_case("service", "endpoint", "", "body"; "Empty header")] #[test_case("service", "endpoint", "", ""; "Empty header and body")] #[test_case("service", "a", "b", "c"; "One byte frame args")] #[test_case("service", "", "", ""; "Zero byte frame args")] #[serial] #[tokio::test] async fn single_frame_msg( service: &str, endpoint: &str, header: &str, body: &str, ) -> Result<(), anyhow::Error> { echo_test(service, endpoint, header, body).await } #[test_case("service", "from_v(&['a' as u8; u16::MAX as usize * 10])", "header", "body"; "Long endpoint/arg1")] #[test_case("service", "endpoint", from_v(&[b'b'; u16::MAX as usize * 10]), "body"; "Long header/arg2")] #[test_case("service", "endpoint", "header", "from_v(&['c' as u8; u16::MAX as usize * 10])"; "Long body/arg3")] #[test_case("service", "from_v(&['a' as u8; u16::MAX as usize * 10])", "from_v(&['b' as u8; u16::MAX as usize * 10])", "from_v(&['c' as u8; u16::MAX as usize * 10])"; "Long all args")] #[serial] #[tokio::test] async fn multi_frame_msg( service: &str, endpoint: &str, header: &str, body: &str, ) -> Result<(), anyhow::Error> { echo_test(service, endpoint, header, body).await } async fn echo_test( service: &str, endpoint: &str, header: &str, body: &str, ) -> Result<(), anyhow::Error> { let _ = env_logger::builder().is_test(true).try_init(); let server = start_echo_server(service, endpoint) .await .expect("Failed to start server"); let req = RawMessage::new( endpoint.to_string(), header.to_string(), Bytes::from(body.to_string()), ); let res = make_request(service, req.clone()) .await .expect("Failed to make request"); server.shutdown_server().expect("Failed to shutdown server"); assert_eq!( req.endpoint(), res.endpoint(), "Endpoint fields should match" ); assert_eq!(req.header(), res.header(), "Header fields should match"); assert_eq!(req.body(), res.body(), "Body fields should match"); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[serial] async fn parallel_messages() -> Result<(), anyhow::Error> { let service = "service"; let endpoint = "endpoint"; let server = start_echo_server(service, endpoint).await?; let client = TChannel::new(Config::default())?; let subchannel = client.subchannel(&service).await?; let small_msgs = (0..50) .map(|i| { RawMessage::new( endpoint.to_string(), format!("header-{}", i), Bytes::from(format!("body-{}", i)), ) }) .collect::<Vec<RawMessage>>(); let large_msgs = (0..5_u8) .map(|i| { RawMessage::new( endpoint.to_string(), from_v(&[i as u8; u16::MAX as usize * 20]).to_string(), Bytes::from(from_v(&[i + 5_u8; u16::MAX as usize * 10]).to_string()), ) }) .collect::<Vec<RawMessage>>(); let (small, large) = tokio::join!( tokio::spawn(send_msgs(subchannel.clone(), small_msgs)), tokio::spawn(send_msgs(subchannel.clone(), large_msgs)) ); assert!(small.is_ok()); assert!(large.is_ok()); server.shutdown_server()?; Ok(()) } async fn send_msgs( subchannel: Arc<SubChannel>, msgs: Vec<RawMessage>, ) -> Result<(), anyhow::Error> { for req in msgs { debug!("Sending {} bytes.", req.header().len() + req.body().len()); let res = subchannel.send(req.clone(), &LOCAL_SERVER).await?; assert_eq!(req.endpoint(), res.endpoint(), "Endpoints should match"); assert_eq!(req.header(), res.header(), "Header fields should match"); assert_eq!(req.body(), res.body(), "Body fields should match"); debug!("Sent"); } Ok(()) } async fn start_echo_server<STR: AsRef<str>>(service: STR, endpoint: STR) -> TResult<TChannel> { let server = TChannel::new(Config::default())?; let subchannel = server.subchannel(&service).await?; subchannel.register(&endpoint, EchoHandler {}).await?; server.start_server()?; Ok(server) } async fn make_request<STR: AsRef<str>>(service: STR, req: RawMessage) -> HandlerResult<RawMessage> { debug!("Outgoing arg2/header len {}", &req.header().len()); let client = TChannel::new(Config::default())?; let subchannel = client.subchannel(service).await?; subchannel.send(req, LOCAL_SERVER).await } #[derive(Debug)] struct EchoHandler {} impl RequestHandler for EchoHandler { type REQ = RawMessage; type RES = RawMessage; fn handle(&mut self, request: Self::REQ) -> HandlerResult<Self::RES> { debug!("Incoming arg2/header len {}", request.header().len()); Ok(request) } } const LOCAL_SERVER: &str = "127.0.0.1:8888"; fn from_v(v: &[u8]) -> &str { std::str::from_utf8(v).unwrap() }
#[cfg(test)] #[macro_use] extern crate log; #[macro_use] extern crate serial_test; use std::sync::Arc; use bytes::Bytes; use test_case::test_case; use tchannel_rs::handler::{HandlerResult, RequestHandler}; use tchannel_rs::messages::MessageChannel; use tchannel_rs::messages::RawMessage; use tchannel_rs::Config; use tchannel_rs::{SubChannel, TChannel, TResult}; #[test_case("service", "endpoint", "header", "body"; "Basic")] #[test_case("service", "endpoint", "header", ""; "Empty body")] #[test_case("service", "endpoint", "", "body"; "Empty header")] #[test_case("service", "endpoint", "", ""; "Empty header and body")] #[test_case("service", "a", "b", "c"; "One byte frame args")] #[test_case("service", "", "", ""; "Zero byte frame args")] #[serial] #[tokio::test] async fn single_frame_msg( service: &str, endpoint: &str, header: &str, body: &str, ) -> Result<(), anyhow::Error> { echo_test(service, endpoint, header, body).await } #[test_case("service", "from_v(&['a' as u8; u16::MAX as usize * 10])", "header", "body"; "Long endpoint/arg1")] #[test_case("service", "endpoint", from_v(&[b'b'; u16::MAX as usize * 10]), "body"; "Long header/arg2")] #[test_case("service", "endpoint", "header", "from_v(&['c' as u8; u16::MAX as usize * 10])"; "Long body/arg3")] #[test_case("service", "from_v(&['a' as u8; u16::MAX as usize * 10])", "from_v(&['b' as u8; u16::MAX as usize * 10])", "from_v(&['c' as u8; u16::MAX as usize * 10])"; "Long all args")] #[serial] #[tokio::test] async fn multi_frame_msg( service: &str, endpoint: &str, header: &str, body: &str, ) -> Result<(), anyhow::Error> { echo_test(service, endpoint, header, body).await } async fn echo_test( service: &str, endpoint: &str, header: &str, body: &str, ) -> Result<(), anyhow::Error> { let _ = env_logger::builder().is_test(true).try_init(); let server = start_echo_server(service, endpoint) .await .expect("Failed to start server"); let req = RawMessage::new( endpoint.to_string(), header.to_string(), Bytes::from(body.to_string()), ); let res = make_request(service, req.clone()) .await .expect("Failed to make request"); server.shutdown_server().expect("Failed to shutdown server"); assert_eq!( req.endpoint(), res.endpoint(), "Endpoint fields should match" ); assert_eq!(req.header(), res.header(), "Header fields should match"); assert_eq!(req.body(), res.body(), "Body fields should match"); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[serial] async fn parallel_messages() -> Result<(), anyhow::Error> { let service = "service"; let endpoint = "endpoint"; let server = start_echo_server(service, endpoint).await?; let client = TChannel::new(Config::default())?; let subchannel = client.subchannel(&service).await?; let small_msgs = (0..50) .map(|i| { RawMessage::new( endpoint.to_string(), format!("header-{}", i), Bytes::from(format!("body-{}", i)), ) }) .collect::<Vec<RawMessage>>(); let large_msgs = (0..5_u8) .map(|i| { RawMessage::new( endpoint.to_string(), from_v(&[i as u8; u16::MAX as usize * 20]).to_string(), Bytes::from(from_v(&[i + 5_u8; u16::MAX as usize * 10]).to_string()), ) }) .collect::<Vec<RawMessage>>(); let (small, large) = tokio::join!( tokio::spawn(send_msgs(subchannel.clone(), small_msgs)), tokio::spawn(send_msgs(subchannel.clone(), large_msgs)) ); assert!(small.is_ok()); assert!(large.is_ok()); server.shutdown_server()?; Ok(()) } async fn send_msgs( subchannel: Arc<SubChannel>, msgs: Vec<RawMessage>, ) -> Result<(), anyhow::Error> { for req in msgs { debug!("Sending {} bytes.", req.header().len() + req.body().len()); let res = subchannel.send(req.clone(), &LOCAL_SERVER).await?; assert_eq!(req.endpoint(), res.endpoint(), "Endpoints should match"); assert_eq!(req.header(), res.header(), "Header fields should match"); assert_eq!(req.body(), res.body(), "Body fields should match"); debug!("Sent"); } Ok(()) }
async fn make_request<STR: AsRef<str>>(service: STR, req: RawMessage) -> HandlerResult<RawMessage> { debug!("Outgoing arg2/header len {}", &req.header().len()); let client = TChannel::new(Config::default())?; let subchannel = client.subchannel(service).await?; subchannel.send(req, LOCAL_SERVER).await } #[derive(Debug)] struct EchoHandler {} impl RequestHandler for EchoHandler { type REQ = RawMessage; type RES = RawMessage; fn handle(&mut self, request: Self::REQ) -> HandlerResult<Self::RES> { debug!("Incoming arg2/header len {}", request.header().len()); Ok(request) } } const LOCAL_SERVER: &str = "127.0.0.1:8888"; fn from_v(v: &[u8]) -> &str { std::str::from_utf8(v).unwrap() }
async fn start_echo_server<STR: AsRef<str>>(service: STR, endpoint: STR) -> TResult<TChannel> { let server = TChannel::new(Config::default())?; let subchannel = server.subchannel(&service).await?; subchannel.register(&endpoint, EchoHandler {}).await?; server.start_server()?; Ok(server) }
function_block-full_function
[ { "content": "fn encode_small_string<STR: AsRef<str>>(value: STR, dst: &mut BytesMut) -> CodecResult<()> {\n\n encode_string_field(value, dst, &BytesMut::put_u8)\n\n}\n\n\n", "file_path": "src/frames/payloads.rs", "rank": 0, "score": 163112.80213647935 }, { "content": "fn encode_string_fi...
Rust
src/shell/history/entry.rs
doy/nbsh
4151ab7aab939a12721a0f4207c87b5c09ace339
use crate::shell::prelude::*; pub struct Entry { cmdline: String, env: Env, pty: super::pty::Pty, fullscreen: Option<bool>, start_instant: std::time::Instant, start_time: time::OffsetDateTime, state: State, } impl Entry { pub fn new( cmdline: String, env: Env, size: (u16, u16), event_w: crate::shell::event::Writer, ) -> Result<Self> { let start_instant = std::time::Instant::now(); let start_time = time::OffsetDateTime::now_utc(); let (pty, pts) = super::pty::Pty::new(size, event_w.clone()).unwrap(); let (child, fh) = Self::spawn_command(&cmdline, &env, &pts)?; tokio::spawn(Self::task(child, fh, env.idx(), event_w)); Ok(Self { cmdline, env, pty, fullscreen: None, start_instant, start_time, state: State::Running((0, 0)), }) } pub fn render( &self, out: &mut impl textmode::Textmode, entry_count: usize, vt: &mut super::pty::Vt, focused: bool, scrolling: bool, offset: time::UtcOffset, ) { let idx = self.env.idx(); let size = out.screen().size(); let time = self.state.exit_info().map_or_else( || { format!( "[{}]", crate::format::time(self.start_time.to_offset(offset)) ) }, |info| { format!( "({}) [{}]", crate::format::duration( info.instant - self.start_instant ), crate::format::time(self.start_time.to_offset(offset)), ) }, ); if vt.bell(focused) { out.write(b"\x07"); } Self::set_bgcolor(out, idx, focused); out.set_fgcolor(textmode::color::YELLOW); let entry_count_width = format!("{}", entry_count + 1).len(); let idx_str = format!("{}", idx + 1); out.write_str(&" ".repeat(entry_count_width - idx_str.len())); out.write_str(&idx_str); out.write_str(" "); out.reset_attributes(); Self::set_bgcolor(out, idx, focused); if let Some(info) = self.state.exit_info() { if info.status.signal().is_some() { out.set_fgcolor(textmode::color::MAGENTA); } else if info.status.success() { out.set_fgcolor(textmode::color::DARKGREY); } else { out.set_fgcolor(textmode::color::RED); } out.write_str(&crate::format::exit_status(info.status)); } else { out.write_str(" "); } out.reset_attributes(); if vt.is_bell() { out.set_bgcolor(textmode::Color::Rgb(64, 16, 16)); } else { Self::set_bgcolor(out, idx, focused); } out.write_str("$ "); Self::set_bgcolor(out, idx, focused); let start = usize::from(out.screen().cursor_position().1); let end = usize::from(size.1) - time.len() - 2; let max_len = end - start; let cmd = if self.cmd().len() > max_len { &self.cmd()[..(max_len - 4)] } else { self.cmd() }; if let State::Running(span) = self.state { let span = (span.0.min(cmd.len()), span.1.min(cmd.len())); if !cmd[..span.0].is_empty() { out.write_str(&cmd[..span.0]); } if !cmd[span.0..span.1].is_empty() { out.set_bgcolor(textmode::Color::Rgb(16, 64, 16)); out.write_str(&cmd[span.0..span.1]); Self::set_bgcolor(out, idx, focused); } if !cmd[span.1..].is_empty() { out.write_str(&cmd[span.1..]); } } else { out.write_str(cmd); } if self.cmd().len() > max_len { if let State::Running(span) = self.state { if span.0 < cmd.len() && span.1 > cmd.len() { out.set_bgcolor(textmode::Color::Rgb(16, 64, 16)); } } out.write_str(" "); if let State::Running(span) = self.state { if span.1 > cmd.len() { out.set_bgcolor(textmode::Color::Rgb(16, 64, 16)); } } out.set_fgcolor(textmode::color::BLUE); out.write_str("..."); } out.reset_attributes(); Self::set_bgcolor(out, idx, focused); let cur_pos = out.screen().cursor_position(); out.write_str(&" ".repeat( usize::from(size.1) - time.len() - 1 - usize::from(cur_pos.1), )); out.write_str(&time); out.write_str(" "); out.reset_attributes(); if vt.binary() { let msg = "This appears to be binary data. Fullscreen this entry to view anyway."; let len: u16 = msg.len().try_into().unwrap(); out.move_to( out.screen().cursor_position().0 + 1, (size.1 - len) / 2, ); out.set_fgcolor(textmode::color::RED); out.write_str(msg); out.hide_cursor(true); } else { let last_row = vt.output_lines(focused && !scrolling, self.state.running()); let mut max_lines = self.max_lines(entry_count); if last_row > max_lines { out.write(b"\r\n"); out.set_fgcolor(textmode::color::BLUE); out.write_str("..."); out.reset_attributes(); max_lines -= 1; } let mut out_row = out.screen().cursor_position().0 + 1; let screen = vt.screen(); let pos = screen.cursor_position(); let mut wrapped = false; let mut cursor_found = None; for (idx, row) in screen .rows_formatted(0, size.1) .enumerate() .take(last_row) .skip(last_row.saturating_sub(max_lines)) { let idx: u16 = idx.try_into().unwrap(); out.reset_attributes(); if !wrapped { out.move_to(out_row, 0); } out.write(&row); wrapped = screen.row_wrapped(idx); if pos.0 == idx { cursor_found = Some(out_row); } out_row += 1; } if focused && !scrolling { if let Some(row) = cursor_found { out.hide_cursor(screen.hide_cursor()); out.move_to(row, pos.1); } else { out.hide_cursor(true); } } } out.reset_attributes(); } pub fn render_fullscreen(&self, out: &mut impl textmode::Textmode) { self.pty.with_vt_mut(|vt| { out.write(&vt.screen().state_formatted()); if vt.bell(true) { out.write(b"\x07"); } out.reset_attributes(); }); } pub fn input(&self, bytes: Vec<u8>) { self.pty.input(bytes); } pub fn resize(&self, size: (u16, u16)) { self.pty.resize(size); } pub fn cmd(&self) -> &str { &self.cmdline } pub fn start_time(&self) -> time::OffsetDateTime { self.start_time } pub fn toggle_fullscreen(&mut self) { if let Some(fullscreen) = self.fullscreen { self.fullscreen = Some(!fullscreen); } else { self.fullscreen = Some(!self.pty.fullscreen()); } } pub fn set_fullscreen(&mut self, fullscreen: bool) { self.fullscreen = Some(fullscreen); } pub fn running(&self) -> bool { self.state.running() } pub fn exited(&mut self, exit_info: ExitInfo) { self.state = State::Exited(exit_info); } pub fn lines(&self, entry_count: usize, focused: bool) -> usize { let running = self.running(); 1 + std::cmp::min( self.pty.with_vt(|vt| vt.output_lines(focused, running)), self.max_lines(entry_count), ) } pub fn should_fullscreen(&self) -> bool { self.fullscreen.unwrap_or_else(|| self.pty.fullscreen()) } pub fn lock_vt(&self) -> std::sync::MutexGuard<super::pty::Vt> { self.pty.lock_vt() } pub fn set_span(&mut self, new_span: (usize, usize)) { if let State::Running(ref mut span) = self.state { *span = new_span; } } fn max_lines(&self, entry_count: usize) -> usize { if self.env.idx() == entry_count - 1 { 15 } else { 5 } } fn set_bgcolor( out: &mut impl textmode::Textmode, idx: usize, focus: bool, ) { if focus { out.set_bgcolor(textmode::Color::Rgb(0x56, 0x1b, 0x8b)); } else if idx % 2 == 0 { out.set_bgcolor(textmode::Color::Rgb(0x24, 0x21, 0x00)); } else { out.set_bgcolor(textmode::Color::Rgb(0x20, 0x20, 0x20)); } } fn spawn_command( cmdline: &str, env: &Env, pts: &pty_process::Pts, ) -> Result<(tokio::process::Child, std::fs::File)> { let mut cmd = pty_process::Command::new(crate::info::current_exe()?); cmd.args(&["-c", cmdline, "--status-fd", "3"]); env.apply(&mut cmd); let (from_r, from_w) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?; let fh = unsafe { std::fs::File::from_raw_fd(from_r) }; unsafe { cmd.pre_exec(move || { nix::unistd::dup2(from_w, 3)?; Ok(()) }); } let child = cmd.spawn(pts)?; nix::unistd::close(from_w)?; Ok((child, fh)) } async fn task( mut child: tokio::process::Child, fh: std::fs::File, idx: usize, event_w: crate::shell::event::Writer, ) { enum Res { Read(crate::runner::Event), Exit(std::io::Result<std::process::ExitStatus>), } let (read_w, read_r) = tokio::sync::mpsc::unbounded_channel(); tokio::task::spawn_blocking(move || loop { let event = bincode::deserialize_from(&fh); match event { Ok(event) => { read_w.send(event).unwrap(); } Err(e) => { match &*e { bincode::ErrorKind::Io(io_e) => { assert!( io_e.kind() == std::io::ErrorKind::UnexpectedEof ); } e => { panic!("{}", e); } } break; } } }); let mut stream: futures_util::stream::SelectAll<_> = [ tokio_stream::wrappers::UnboundedReceiverStream::new(read_r) .map(Res::Read) .boxed(), futures_util::stream::once(child.wait()) .map(Res::Exit) .boxed(), ] .into_iter() .collect(); let mut exit_status = None; let mut new_env = None; while let Some(res) = stream.next().await { match res { Res::Read(event) => match event { crate::runner::Event::RunPipeline(new_span) => { event_w.send(Event::ChildRunPipeline(idx, new_span)); } crate::runner::Event::Suspend => { event_w.send(Event::ChildSuspend(idx)); } crate::runner::Event::Exit(env) => { new_env = Some(env); } }, Res::Exit(status) => { exit_status = Some(status.unwrap()); } } } event_w.send(Event::ChildExit( idx, ExitInfo::new(exit_status.unwrap()), new_env, )); } } enum State { Running((usize, usize)), Exited(ExitInfo), } impl State { fn exit_info(&self) -> Option<&ExitInfo> { match self { Self::Running(_) => None, Self::Exited(exit_info) => Some(exit_info), } } fn running(&self) -> bool { self.exit_info().is_none() } } #[derive(Debug)] pub struct ExitInfo { status: std::process::ExitStatus, instant: std::time::Instant, } impl ExitInfo { fn new(status: std::process::ExitStatus) -> Self { Self { status, instant: std::time::Instant::now(), } } }
use crate::shell::prelude::*; pub struct Entry { cmdline: String, env: Env, pty: super::pty::Pty, fullscreen: Option<bool>, start_instant: std::time::Instant, start_time: time::OffsetDateTime, state: State, } impl Entry { pub fn new( cmdline: String, env: Env, size: (u16, u16), event_w: crate::shell::event::Writer, ) -> Result<Self> { let start_instant = std::time::Instant::now(); let start_time = time::OffsetDateTime::now_utc(); let (pty, pts) = super::pty::Pty::new(size, event_w.clone()).unwrap(); let (child, fh) = Self::spawn_command(&cmdline, &env, &pts)?; tokio::spawn(Self::task(child, fh, env.idx(), event_w)); Ok(Self { cmdline, env, pty, fullscreen: None, start_instant, start_time, state: State::Running((0, 0)), }) } pub fn render( &self, out: &mut impl textmode::Textmode, entry_count: usize, vt: &mut super::pty::Vt, focused: bool, scrolling: bool, offset: time::UtcOffset, ) { let idx = self.env.idx(); let size = out.screen().size(); let time = self.state.exit_info().map_or_else( || { format!( "[{}]", crate::format::time(self.start_time.to_offset(offset)) ) }, |info| { format!( "({}) [{}]", crate::format::duration( info.instant - self.start_instant ), crate::format::time(self.start_time.to_offset(offset)), ) }, ); if vt.bell(focused) { out.write(b"\x07"); } Self::set_bgcolor(out, idx, focused); out.set_fgcolor(textmode::color::YELLOW); let entry_count_width = format!("{}", entry_count + 1).len(); let idx_str = format!("{}", idx + 1); out.write_str(&" ".repeat(entry_count_width - idx_str.len())); out.write_str(&idx_str); out.write_str(" "); out.reset_attributes(); Self::set_bgcolor(out, idx, focused); if let Some(info) = self.state.exit_info() { if info.status.signal().is_some() { out.set_fgcolor(textmode::color::MAGENTA); } else if info.status.success() { out.set_fgcolor(textmode::color::DARKGREY); } else { out.set_fgcolor(textmode::color::RED); } out.write_str(&crate::format::exit_status(info.status)); } else { out.write_str(" "); } out.reset_attributes(); if vt.is_bell() { out.set_bgcolor(textmode::Color::Rgb(64, 16, 16)); } else { Self::set_bgcolor(out, idx, focused); } out.write_str("$ "); Self::set_bgcolor(out, idx, focused); let start = usize::from(out.screen().cursor_position().1); let end = usize::from(size.1) - time.len() - 2; let max_len = end - start; let cmd = if self.cmd().len() > max_len { &self.cmd()[..(max_len - 4)] } else { self.cmd() }; if let State::Running(span) = self.state { let span = (span.0.min(cmd.len()), span.1.min(cmd.len())); if !cmd[..span.0].is_empty() { out.write_str(&cmd[..span.0]); } if !cmd[span.0..span.1].is_empty() { out.set_bgcolor(textmode::Color::Rgb(16, 64, 16)); out.write_str(&cmd[span.0..span.1]); Self::set_bgcolor(out, idx, focused); } if !cmd[span.1..].is_empty() { out.write_str(&cmd[span.1..]); } } else { out.write_str(cmd); } if self.cmd().len() > max_len { if let State::Running(span) = self.state { if span.0 < cmd.len() && span.1 > cmd.len() { out.set_bgcolor(textmode::Color::Rgb(16, 64, 16)); } } out.write_str(" "); if let State::Running(span) = self.state { if span.1 > cmd.len() { out.set_bgcolor(textmode::Color::Rgb(16, 64, 16)); } } out.set_fgcolor(textmode::color::BLUE); out.write_str("..."); } out.reset_attributes(); Self::set_bgcolor(out, idx, focused); let cur_pos = out.screen().cursor_position(); out.write_str(&" ".repeat( usize::from(size.1) - time.len() - 1 - usize::from(cur_pos.1), )); out.write_str(&time); out.write_str(" "); out.reset_attributes(); if vt.binary() { let msg = "This appears to be binary data. Fullscreen this entry to view anyway."; let len: u16 = msg.len().try_into().unwrap(); out.move_to( out.screen().cursor_position().0 + 1, (size.1 - len) / 2, ); out.set_fgcolor(textmode::color::RED); out.write_str(msg); out.hide_cursor(true); } else { let last_row = vt.output_lines(focused && !scrolling, self.state.running()); let mut max_lines = self.max_lines(entry_count); if last_row > max_lines { out.write(b"\r\n"); out.set_fgcolor(textmode::color::BLUE); out.write_str("..."); out.reset_attributes(); max_lines -= 1; } let mut out_row = out.screen().cursor_position().0 + 1; let screen = vt.screen(); let pos = screen.cursor_position(); let mut wrapped = false; let mut cursor_found = None; for (idx, row) in screen .rows_formatted(0, size.1) .enumerate() .take(last_row) .skip(last_row.saturating_sub(max_lines)) { let idx: u16 = idx.try_into().unwrap(); out.reset_attributes(); if !wrapped { out.move_to(out_row, 0); } out.write(&row); wrapped = screen.row_wrapped(idx); if pos.0 == idx { cursor_found = Some(out_row); } out_row += 1; } if focused && !scrolling { if let Some(row) = cursor_found { out.hide_cursor(screen.hide_cursor()); out.move_to(row, pos.1); } else { out.hide_cursor(true); } } } out.reset_attributes(); } pub fn render_fullscreen(&self, out: &mut impl textmode::Textmode) { self.pty.with_vt_mut(|vt| { out.write(&vt.screen().state_formatted()); if vt.bell(true) { out.write(b"\x07"); } out.reset_attributes(); }); } pub fn input(&self, bytes: Vec<u8>) { self.pty.input(bytes); } pub fn resize(&self, size: (u16, u16)) { self.pty.resize(size); } pub fn cmd(&self) -> &str { &self.cmdline } pub fn start_time(&self) -> time::OffsetDateTime { self.start_time } pub fn toggle_fullscreen(&mut self) { if let Some(fullscreen) = self.fullscreen { self.fullscreen = Some(!fullscreen); } else { self.fullscreen = Some(!self.pty.fullscreen()); } } pub fn set_fullscreen(&mut self, fullscreen: bool) { self.fullscreen = Some(fullscreen); } pub fn running(&self) -> bool { self.state.running() } pub fn exited(&mut self, exit_info: ExitInfo) { self.state = State::Exited(exit_info); }
pub fn should_fullscreen(&self) -> bool { self.fullscreen.unwrap_or_else(|| self.pty.fullscreen()) } pub fn lock_vt(&self) -> std::sync::MutexGuard<super::pty::Vt> { self.pty.lock_vt() } pub fn set_span(&mut self, new_span: (usize, usize)) { if let State::Running(ref mut span) = self.state { *span = new_span; } } fn max_lines(&self, entry_count: usize) -> usize { if self.env.idx() == entry_count - 1 { 15 } else { 5 } } fn set_bgcolor( out: &mut impl textmode::Textmode, idx: usize, focus: bool, ) { if focus { out.set_bgcolor(textmode::Color::Rgb(0x56, 0x1b, 0x8b)); } else if idx % 2 == 0 { out.set_bgcolor(textmode::Color::Rgb(0x24, 0x21, 0x00)); } else { out.set_bgcolor(textmode::Color::Rgb(0x20, 0x20, 0x20)); } } fn spawn_command( cmdline: &str, env: &Env, pts: &pty_process::Pts, ) -> Result<(tokio::process::Child, std::fs::File)> { let mut cmd = pty_process::Command::new(crate::info::current_exe()?); cmd.args(&["-c", cmdline, "--status-fd", "3"]); env.apply(&mut cmd); let (from_r, from_w) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?; let fh = unsafe { std::fs::File::from_raw_fd(from_r) }; unsafe { cmd.pre_exec(move || { nix::unistd::dup2(from_w, 3)?; Ok(()) }); } let child = cmd.spawn(pts)?; nix::unistd::close(from_w)?; Ok((child, fh)) } async fn task( mut child: tokio::process::Child, fh: std::fs::File, idx: usize, event_w: crate::shell::event::Writer, ) { enum Res { Read(crate::runner::Event), Exit(std::io::Result<std::process::ExitStatus>), } let (read_w, read_r) = tokio::sync::mpsc::unbounded_channel(); tokio::task::spawn_blocking(move || loop { let event = bincode::deserialize_from(&fh); match event { Ok(event) => { read_w.send(event).unwrap(); } Err(e) => { match &*e { bincode::ErrorKind::Io(io_e) => { assert!( io_e.kind() == std::io::ErrorKind::UnexpectedEof ); } e => { panic!("{}", e); } } break; } } }); let mut stream: futures_util::stream::SelectAll<_> = [ tokio_stream::wrappers::UnboundedReceiverStream::new(read_r) .map(Res::Read) .boxed(), futures_util::stream::once(child.wait()) .map(Res::Exit) .boxed(), ] .into_iter() .collect(); let mut exit_status = None; let mut new_env = None; while let Some(res) = stream.next().await { match res { Res::Read(event) => match event { crate::runner::Event::RunPipeline(new_span) => { event_w.send(Event::ChildRunPipeline(idx, new_span)); } crate::runner::Event::Suspend => { event_w.send(Event::ChildSuspend(idx)); } crate::runner::Event::Exit(env) => { new_env = Some(env); } }, Res::Exit(status) => { exit_status = Some(status.unwrap()); } } } event_w.send(Event::ChildExit( idx, ExitInfo::new(exit_status.unwrap()), new_env, )); } } enum State { Running((usize, usize)), Exited(ExitInfo), } impl State { fn exit_info(&self) -> Option<&ExitInfo> { match self { Self::Running(_) => None, Self::Exited(exit_info) => Some(exit_info), } } fn running(&self) -> bool { self.exit_info().is_none() } } #[derive(Debug)] pub struct ExitInfo { status: std::process::ExitStatus, instant: std::time::Instant, } impl ExitInfo { fn new(status: std::process::ExitStatus) -> Self { Self { status, instant: std::time::Instant::now(), } } }
pub fn lines(&self, entry_count: usize, focused: bool) -> usize { let running = self.running(); 1 + std::cmp::min( self.pty.with_vt(|vt| vt.output_lines(focused, running)), self.max_lines(entry_count), ) }
function_block-full_function
[ { "content": "#[allow(clippy::unnecessary_wraps)]\n\npub fn time(offset: time::UtcOffset) -> Result<String> {\n\n Ok(crate::format::time(\n\n time::OffsetDateTime::now_utc().to_offset(offset),\n\n ))\n\n}\n\n\n", "file_path": "src/info.rs", "rank": 0, "score": 243241.07392747345 }, ...
Rust
code_analysis/rust_parser/src/generics.rs
LucaCappelletti94/EnsmallenGraph
572532b6d3f4352bf58f9ccca955376acd95fd89
use super::*; #[derive(Debug, Clone, PartialEq)] pub enum GenericValue{ Type(Type), Lifetime(Lifetime), TypeAssignement(Type, Type), TypeInheritance(Type, Type), } impl Parse for GenericValue { fn parse(mut data: &[u8]) -> (&[u8], Self) { if data.starts_with(b"'") { let res = GenericValue::Lifetime(parse!(data, Lifetime)); return (data, res); } let start = parse!(data, Type); if data.starts_with(b":") { data = &data[1..]; let end = parse!(data, Type); return (data, GenericValue::TypeInheritance(start, end)); } if data.starts_with(b"=") { data = &data[1..]; let end = parse!(data, Type); return (data, GenericValue::TypeAssignement(start, end)); } (data, GenericValue::Type(start)) } } impl CmpWithoutModifiers for GenericValue { fn cmp_without_modifiers(&self, other: &GenericValue) -> bool { match (self, other) { (GenericValue::Type(t1), GenericValue::Type(t2)) => t1.cmp_without_modifiers(t2), (GenericValue::TypeAssignement(t1, t2), GenericValue::TypeAssignement(o1, o2)) => { t1.cmp_without_modifiers(o1) && t2.cmp_without_modifiers(o2) } _ => false, } } } impl PartialEq<&str> for GenericValue { fn eq(&self, other:&&str) -> bool { match self { GenericValue::Type(t) => t == other, GenericValue::TypeAssignement(t1, t2) => { match other.split_once("=") { Some((v1, v2)) => { t1 == v1 && t2 == v2 } None => false } } _ => false, } } } impl From<GenericValue> for String { fn from(x: GenericValue) -> String { match x { GenericValue::Lifetime(lt) => { format!("'{}", lt.0) } GenericValue::Type(t) => { String::from(t) } GenericValue::TypeAssignement(t1, t2) => { format!("{} = {}", String::from(t1), String::from(t2)) } GenericValue::TypeInheritance(t1, t2) => { format!("{} : {}", String::from(t1), String::from(t2)) } } } } #[derive(Debug, Clone, PartialEq)] pub struct Generics(pub Vec<GenericValue>); impl std::ops::Index<usize> for Generics { type Output = GenericValue; fn index(&self, index: usize) -> &Self::Output { &self.0[index] } } impl CanParse for Generics { fn can_parse(mut data: &[u8]) -> bool { data = skip_whitespace(data); data.starts_with(b"<") } } impl Parse for Generics { fn parse(mut data: &[u8]) -> (&[u8], Self) { let mut generics = Vec::new(); let (remainder, mut matching) = get_next_matching(data, b'<', b'>'); data = remainder; while !matching.is_empty() { generics.push(parse!(matching, GenericValue)); if matching.starts_with(b",") { matching = &matching[1..]; } } (data, Generics(generics)) } } impl Default for Generics { fn default() -> Self { Generics(Vec::new()) } } impl From<Generics> for String { fn from(x: Generics) -> String { if x.0.is_empty(){ return String::new(); } let mut result = "<".to_string(); for gen_val in x.0 { result.push_str(&String::from(gen_val)); result.push_str(", "); } result = result.trim_end_matches(&", ").to_string(); result.push('>'); result } } impl CmpWithoutModifiers for Generics { fn cmp_without_modifiers(&self, other:&Generics) -> bool { if self.0.len() != other.0.len() { return false; } for i in 0..self.0.len(){ if !self.0[i].cmp_without_modifiers(&other.0[i]){ return false; } } true } }
use super::*; #[derive(Debug, Clone, PartialEq)] pub enum GenericValue{ Type(Type), Lifetime(Lifetime), TypeAssignement(Type, Type), TypeInheritance(Type, Type), } impl Parse for GenericValue { fn parse(mut data: &[u8]) -> (&[u8], Self) { if data.starts_with(b"'") { let res = GenericValue::Lifetime(parse!(data, Lifetime)); return (data, res); } let start = parse!(data, Type); if data.starts_with(b":") { data = &data[1..]; let end = parse!(data, Type); return (data, GenericValue::TypeInheritance(start, end)); } if data.starts_with(b"=") { data = &data[1..]; let end = parse!(data, Type); return (data, GenericValue::TypeAssignement(start, end)); } (data, GenericValue::Type(start)) } } impl CmpWithoutModifiers for GenericValue { fn cmp_without_modifiers(&self, other: &GenericValue) -> bool { match (self, other) { (GenericValue::Type(t1), GenericValue::Type(t2)) => t1.cmp_without_modifiers(t2), (GenericValue::TypeAssignement(t1, t2), GenericValue::TypeAssignement(o1, o2)) => { t1.cmp_without_modifiers(o1) && t2.cmp_without_modifiers(o2) } _ => false, } } } impl PartialEq<&str> for GenericValue { fn eq(&self, other:&&str) -> bool { match self { GenericValue::Type(t) => t == other, GenericValue::TypeAssignement(t1, t2) => { match other.split_once("=") { Some((v1, v2)) => { t1 == v1 && t2 == v2 } None => false } } _ => false, } } } impl From<GenericValue> for String {
} #[derive(Debug, Clone, PartialEq)] pub struct Generics(pub Vec<GenericValue>); impl std::ops::Index<usize> for Generics { type Output = GenericValue; fn index(&self, index: usize) -> &Self::Output { &self.0[index] } } impl CanParse for Generics { fn can_parse(mut data: &[u8]) -> bool { data = skip_whitespace(data); data.starts_with(b"<") } } impl Parse for Generics { fn parse(mut data: &[u8]) -> (&[u8], Self) { let mut generics = Vec::new(); let (remainder, mut matching) = get_next_matching(data, b'<', b'>'); data = remainder; while !matching.is_empty() { generics.push(parse!(matching, GenericValue)); if matching.starts_with(b",") { matching = &matching[1..]; } } (data, Generics(generics)) } } impl Default for Generics { fn default() -> Self { Generics(Vec::new()) } } impl From<Generics> for String { fn from(x: Generics) -> String { if x.0.is_empty(){ return String::new(); } let mut result = "<".to_string(); for gen_val in x.0 { result.push_str(&String::from(gen_val)); result.push_str(", "); } result = result.trim_end_matches(&", ").to_string(); result.push('>'); result } } impl CmpWithoutModifiers for Generics { fn cmp_without_modifiers(&self, other:&Generics) -> bool { if self.0.len() != other.0.len() { return false; } for i in 0..self.0.len(){ if !self.0[i].cmp_without_modifiers(&other.0[i]){ return false; } } true } }
fn from(x: GenericValue) -> String { match x { GenericValue::Lifetime(lt) => { format!("'{}", lt.0) } GenericValue::Type(t) => { String::from(t) } GenericValue::TypeAssignement(t1, t2) => { format!("{} = {}", String::from(t1), String::from(t2)) } GenericValue::TypeInheritance(t1, t2) => { format!("{} : {}", String::from(t1), String::from(t2)) } } }
function_block-full_function
[]
Rust
crates/shell/build.rs
BSFishy/carton
0edcde473e381d526eecb6777d20349ff751b7d3
#![allow(clippy::if_same_then_else)] use std::env; use std::path::PathBuf; macro_rules! cargo { ($value:expr) => { println!("cargo:{}", $value) } } macro_rules! warning { ($message:expr) => { cargo!(format!("warning={}", $message)); }; ($message:expr $(, $extra:expr)*) => { warning!(format!($message $(, $extra)*)); } } macro_rules! config { ($key:expr) => { cargo!(format!("rustc-cfg={}", $key)); }; ($key:expr => $value:expr) => { config!(format!("{}=\"{}\"", $key, $value)); } } #[derive(Debug, Eq, PartialEq, Copy, Clone)] enum Platform { Windows, Mac, X11, Wayland, OpenGL, Vulkan, } fn main() { let mut platforms: Vec<Platform> = Vec::new(); add_platforms(&mut platforms); validate_platforms(&mut platforms); let platform = finalize_platform(platforms); link_with_platform(&platform); config!("platform" => match platform { Platform::Windows => "windows", Platform::Mac => "macos", Platform::X11 => "x11", Platform::Wayland => "wayland", Platform::OpenGL => "opengl", Platform::Vulkan => "vulkan", }); println!("cargo:rerun-if-changed=wrapper.h"); let mut bindings = bindgen::Builder::default() .header("wrapper.h") .clang_arg(format!("-D{}", get_clang_definition(&platform))) .use_core() .default_enum_style(bindgen::EnumVariation::Rust { non_exhaustive: true }) .parse_callbacks(Box::new(bindgen::CargoCallbacks)); if platform == Platform::Wayland { bindings = bindings .blacklist_item("FP_NAN") .blacklist_item("FP_INFINITE") .blacklist_item("FP_ZERO") .blacklist_item("FP_SUBNORMAL") .blacklist_item("FP_NORMAL"); } let bindings = bindings .generate() .expect("Unable to generate bindings"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!"); } fn add_platforms(platforms: &mut Vec<Platform>) { if cfg!(feature = "windows") { platforms.push(Platform::Windows) } if cfg!(feature = "macos") { platforms.push(Platform::Mac) } if cfg!(feature = "x11") { platforms.push(Platform::X11) } if cfg!(feature = "wayland") { platforms.push(Platform::Wayland) } if cfg!(feature = "opengl") { platforms.push(Platform::OpenGL) } if cfg!(feature = "vulkan") { platforms.push(Platform::Vulkan) } } fn validate_platforms(platforms: &mut Vec<Platform>) { if platforms.contains(&Platform::X11) && platforms.contains(&Platform::Wayland) { panic!("X11 and Wayland are mutually exclusive") } } fn finalize_platform(platforms: Vec<Platform>) -> Platform { let mut platform: Option<Platform> = None; if platforms.contains(&Platform::Vulkan) { platform = Some(Platform::Vulkan) } if platforms.contains(&Platform::OpenGL) { platform = Some(Platform::OpenGL); } if platform.is_none() { if cfg!(target_os = "windows") { if platforms.contains(&Platform::Windows) { platform = Some(Platform::Windows) } } else if cfg!(target_os = "macos") { if platforms.contains(&Platform::Mac) { platform = Some(Platform::Mac) } } else if cfg!(target_os = "linux") { if platforms.contains(&Platform::X11) { platform = Some(Platform::X11) } if platforms.contains(&Platform::Wayland) { platform = Some(Platform::Wayland) } } } if platform.is_none() { if cfg!(target_os = "windows") { platform = Some(Platform::Windows) } else if cfg!(target_os = "macos") { platform = Some(Platform::Mac) } else if cfg!(target_os = "linux") { platform = Some(Platform::X11) } if let Some(platform) = platform { warning!("No suitable platform specified. Defaulting to {:?}.", platform) } } platform.expect("Could not find a suitable platform") } fn link_with_platform(platform: &Platform) { match platform { Platform::X11 => { pkg_config::Config::new() .cargo_metadata(true) .atleast_version("1.14") .probe("xcb") .expect("Unable to find XCB"); } Platform::Wayland => { pkg_config::Config::new() .cargo_metadata(true) .atleast_version("1.18") .probe("wayland-client") .expect("Unable to find Wayland Client library"); } Platform::OpenGL => { if cfg!(target_os = "linux") { pkg_config::Config::new() .cargo_metadata(true) .atleast_version("4.5") .probe("opengl") .expect("Unable to find OpenGL"); } else { unimplemented!() } } _ => unimplemented!(), } } fn get_clang_definition(platform: &Platform) -> &'static str { match platform { Platform::Windows => "USE_WINDOWS", Platform::Mac => "USE_MACOS", Platform::X11 => "USE_XCB", Platform::Wayland => "USE_WAYLAND", Platform::OpenGL => "USE_OPENGL", Platform::Vulkan => "USE_VULKAN", } }
#![allow(clippy::if_same_then_else)] use std::env; use std::path::PathBuf; macro_rules! cargo { ($value:expr) => { println!("cargo:{}", $value) } } macro_rules! warning { ($message:expr) => { cargo!(format!("warning={}", $message)); }; ($message:expr $(, $extra:expr)*) => { warning!(format!($message $(, $extra)*)); } } macro_rules! config { ($key:expr) => { cargo!(format!("rustc-cfg={}", $key)); }; ($key:expr => $value:expr) => { config!(format!("{}=\"{}\"", $key, $value)); } } #[derive(Debug, Eq, PartialEq, Copy, Clone)] enum Platform { Windows, Mac, X11, Wayland, OpenGL, Vulkan, } fn main() { let mut platforms: Vec<Platform> = Vec::new(); add_platforms(&mut platforms); validate_platforms(&mut platforms); let platform = finalize_platform(platforms); link_with_platform(&platform); config!("platform" => match platform { Platform::Windows => "windows", Platform::Mac => "macos", Platform::X11 => "x11", Platform::Wayland => "wayland", Platform::OpenGL => "opengl", Platform::Vulkan => "vulkan", }); println!("cargo:rerun-if-changed=wrapper.h"); let mut bindings = bindgen::Builder::default() .header("wrapper.h") .clang_arg(format!("-D{}", get_clang_definition(&platform))) .use_core() .default_enum_style(bindgen::EnumVariation::Rust { non_exhaustive: true }) .parse_callbacks(Box::new(bindgen::CargoCallbacks));
let bindings = bindings .generate() .expect("Unable to generate bindings"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!"); } fn add_platforms(platforms: &mut Vec<Platform>) { if cfg!(feature = "windows") { platforms.push(Platform::Windows) } if cfg!(feature = "macos") { platforms.push(Platform::Mac) } if cfg!(feature = "x11") { platforms.push(Platform::X11) } if cfg!(feature = "wayland") { platforms.push(Platform::Wayland) } if cfg!(feature = "opengl") { platforms.push(Platform::OpenGL) } if cfg!(feature = "vulkan") { platforms.push(Platform::Vulkan) } } fn validate_platforms(platforms: &mut Vec<Platform>) { if platforms.contains(&Platform::X11) && platforms.contains(&Platform::Wayland) { panic!("X11 and Wayland are mutually exclusive") } } fn finalize_platform(platforms: Vec<Platform>) -> Platform { let mut platform: Option<Platform> = None; if platforms.contains(&Platform::Vulkan) { platform = Some(Platform::Vulkan) } if platforms.contains(&Platform::OpenGL) { platform = Some(Platform::OpenGL); } if platform.is_none() { if cfg!(target_os = "windows") { if platforms.contains(&Platform::Windows) { platform = Some(Platform::Windows) } } else if cfg!(target_os = "macos") { if platforms.contains(&Platform::Mac) { platform = Some(Platform::Mac) } } else if cfg!(target_os = "linux") { if platforms.contains(&Platform::X11) { platform = Some(Platform::X11) } if platforms.contains(&Platform::Wayland) { platform = Some(Platform::Wayland) } } } if platform.is_none() { if cfg!(target_os = "windows") { platform = Some(Platform::Windows) } else if cfg!(target_os = "macos") { platform = Some(Platform::Mac) } else if cfg!(target_os = "linux") { platform = Some(Platform::X11) } if let Some(platform) = platform { warning!("No suitable platform specified. Defaulting to {:?}.", platform) } } platform.expect("Could not find a suitable platform") } fn link_with_platform(platform: &Platform) { match platform { Platform::X11 => { pkg_config::Config::new() .cargo_metadata(true) .atleast_version("1.14") .probe("xcb") .expect("Unable to find XCB"); } Platform::Wayland => { pkg_config::Config::new() .cargo_metadata(true) .atleast_version("1.18") .probe("wayland-client") .expect("Unable to find Wayland Client library"); } Platform::OpenGL => { if cfg!(target_os = "linux") { pkg_config::Config::new() .cargo_metadata(true) .atleast_version("4.5") .probe("opengl") .expect("Unable to find OpenGL"); } else { unimplemented!() } } _ => unimplemented!(), } } fn get_clang_definition(platform: &Platform) -> &'static str { match platform { Platform::Windows => "USE_WINDOWS", Platform::Mac => "USE_MACOS", Platform::X11 => "USE_XCB", Platform::Wayland => "USE_WAYLAND", Platform::OpenGL => "USE_OPENGL", Platform::Vulkan => "USE_VULKAN", } }
if platform == Platform::Wayland { bindings = bindings .blacklist_item("FP_NAN") .blacklist_item("FP_INFINITE") .blacklist_item("FP_ZERO") .blacklist_item("FP_SUBNORMAL") .blacklist_item("FP_NORMAL"); }
if_condition
[]
Rust
src/data.rs
Tenebryo/file-system-stats
9a8d02e8782bb0a3be4d7bfbb2b81ba642986050
/* Copyright 2021 Sam Blazes 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. */ use std::{path::PathBuf, sync::{Arc, atomic::AtomicBool}}; use std::time::Duration; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::fs::*; use tokio::sync::Mutex; use async_channel::*; use tokio::sync::broadcast::channel; #[derive(Debug, Clone)] pub struct Entry { pub parent : usize, pub size : u64, pub path : PathBuf, pub children : Vec<usize>, pub num_files : u64, pub is_file : bool, pub expanded : bool, } #[derive(Debug)] pub struct ProgressState { pub count : AtomicUsize, pub done : AtomicUsize, pub complete : AtomicBool, } impl ProgressState { pub fn new() -> Self { Self { count : AtomicUsize::new(0), done : AtomicUsize::new(0), complete : AtomicBool::new(false), } } } #[derive(Debug, Clone)] pub struct DirectoryTreeData { pub entries : Arc<Mutex<Vec<Entry>>>, pub file_types : Arc<Mutex<std::collections::HashMap<Option<String>, u64>>>, } impl DirectoryTreeData { pub fn new() -> DirectoryTreeData { DirectoryTreeData { entries : empty_entry_list(), file_types : Arc::new(Mutex::new(std::collections::HashMap::new())), } } pub async fn from_root_path(path : PathBuf) -> DirectoryTreeData { DirectoryTreeData { entries : directory_entry_list(path).await, file_types : Arc::new(Mutex::new(std::collections::HashMap::new())), } } pub async fn recreate_from_root_path(&self, path : PathBuf) { recreate_directory_entry_list(path, self.entries.clone()).await; self.file_types.lock().await.clear(); } } const NTASKS : usize = 8; pub fn empty_entry_list() -> Arc<Mutex<Vec<Entry>>> { Arc::new(Mutex::new(vec![])) } pub async fn directory_entry_list(path : PathBuf) -> Arc<Mutex<Vec<Entry>>> { let meta = metadata(path.clone()).await.unwrap(); let is_file = meta.is_file(); Arc::new(Mutex::new(vec![Entry{ parent : usize::MAX, size : if is_file {meta.len()} else {0}, num_files : if is_file {1} else {0}, children : vec![], path, is_file, expanded : true, }])) } pub async fn recreate_directory_entry_list(path : PathBuf, entries : Arc<Mutex<Vec<Entry>>>) { let meta = metadata(path.clone()).await.unwrap(); let is_file = meta.is_file(); let mut lock = entries.lock().await; lock.clear(); lock.push(Entry{ parent : usize::MAX, size : if is_file {meta.len()} else {0}, num_files : if is_file {1} else {0}, children : vec![], path, is_file, expanded : true, }); } pub async fn scan_directory(root : usize, DirectoryTreeData{entries, file_types} : DirectoryTreeData, progress : Arc<ProgressState>) { let (tx, rx) : (Sender<Entry>, Receiver<Entry>)= unbounded(); let (done_tx, _) = channel(1); let waiting = Arc::new(AtomicUsize::new(0)); let mut handles = vec![]; for _ in 0..NTASKS { let rx = rx.clone(); let tx = tx.clone(); let mut done_rx = done_tx.subscribe(); let paths = entries.clone(); let progress = progress.clone(); let waiting = waiting.clone(); let file_types = file_types.clone(); let h = tokio::task::spawn(async move { done_rx.recv().await.unwrap(); loop { waiting.fetch_add(1, Ordering::SeqCst); tokio::select! { _ = done_rx.recv() => { break; } Ok(entry) = rx.recv() => { waiting.fetch_sub(1, Ordering::SeqCst); let i = { let mut locked = paths.lock().await; locked.push(entry.clone()); locked.len() - 1 }; if entry.is_file { let mut locked = paths.lock().await; let mut j = locked[i].parent; let n = locked.len(); let file_type = entry.path.extension().map(|ext| String::from(ext.to_string_lossy()).to_uppercase()); file_types.lock().await.entry(file_type) .and_modify(|v| { *v += entry.size; }) .or_insert(entry.size); locked[j].children.push(i); while j < n { locked[j].size += entry.size; locked[j].num_files += 1; j = locked[j].parent; } } else { { let mut locked = paths.lock().await; let j = locked[i].parent; locked[j].children.push(i); } if let Err(e) = process_directory(i, entry.path.clone(), &tx, progress.clone()).await { eprintln!("{:?}: {:?}", e, entry.path); } } progress.done.fetch_add(1, Ordering::SeqCst); } } } }); handles.push(h); } { let locked = entries.lock().await; let root_path = locked[root].path.clone(); if let Err(e) = process_directory(root, root_path, &tx, progress.clone()).await { eprintln!("{:?}", e); } done_tx.send(()).unwrap(); } let mut clock = tokio::time::interval(Duration::from_millis(10)); loop { clock.tick().await; if rx.is_empty() && waiting.load(Ordering::SeqCst) as usize == NTASKS { break; } } done_tx.send(()).unwrap(); for handle in &mut handles { handle.await.unwrap(); } progress.complete.store(true, Ordering::SeqCst); } async fn process_directory(i : usize, path : PathBuf, queue : &Sender<Entry>, progress : Arc<ProgressState>) -> std::io::Result<()> { let mut dir = read_dir(path).await?; loop { match dir.next_entry().await { Ok(Some(subdir)) => { let meta = subdir.metadata().await; if meta.is_err() { continue; } let meta = meta.unwrap(); let size = meta.len(); progress.count.fetch_add(1, Ordering::SeqCst); if meta.is_dir() { queue.send(Entry{ parent : i, size, num_files : 0, path : subdir.path().into(), children : vec![], is_file : false, expanded : false, }).await.unwrap(); } else if meta.is_file() { queue.send(Entry{ parent : i, size, num_files : 1, path : subdir.path().into(), children : vec![], is_file : true, expanded : false, }).await.unwrap(); } } Err(_) => {} _ => break } } Ok(()) } pub fn recalculate_data(entries : &mut [Entry]) { for e in entries.iter_mut() { if e.is_file { e.size = 0; e.num_files = 0; } e.children.clear(); } for i in 1..(entries.len()) { let p = entries[i].parent; entries[p].children.push(i); } fn r_help(entries : &mut [Entry], i : usize) -> (u64, u64) { let mut size = 0; let mut files = 0; for c in entries[i].children.clone() { let (s, f) = r_help(entries, c); size += s; files += f; } entries[i].size = size; entries[i].num_files = files; (size, files) } r_help(entries, 0); } pub fn delete_subtree(entries : &mut Vec<Entry>, subtree : usize) { let mut new_idx = entries.iter().map(|_| usize::MAX).collect::<Vec<_>>(); let mut next_i = 0; for i in 0..(entries.len()) { let parent = entries[i].parent; if parent == subtree || i == subtree { entries[i].parent = subtree; } else { new_idx[i] = next_i; next_i += 1; } } for (i, ni) in new_idx.iter().cloned().enumerate() { if i == ni || ni == usize::MAX { continue; } entries.swap(i, ni); } entries.truncate(next_i); recalculate_data(entries) } pub fn sort_subtree_by_size(i : usize, entries : &mut [Entry]) { for c in entries[i].children.clone() { sort_subtree_by_size(c, entries); } let mut j = i; while entries[j].parent < entries.len() { let mut children = entries[j].children.clone(); children.sort_by_cached_key(|&e| entries[e].size); entries[j].children = children; j = entries[j].parent; } } pub fn find_path_index(path : PathBuf, entries : &[Entry]) -> Option<usize> { let mut i = 0; 'outer: loop { for &c in entries[i].children.iter() { let p = &entries[c].path; if path == *p { return Some(c); } if path.starts_with(p) { i = c; continue 'outer; } } break } None } #[test] fn test_perf() { use std::time::Instant; let root = PathBuf::from("C:\\"); let progress = Arc::new(ProgressState::new()); let start = Instant::now(); tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap() .block_on(async { let entries = directory_entry_list(root).await; let file_types = Arc::new(Mutex::new(std::collections::HashMap::new())); scan_directory(0, DirectoryTreeData{entries, file_types}, progress).await }); let elapsed = start.elapsed(); eprintln!("Elapsed: {:?}", elapsed); }
/* Copyright 2021 Sam Blazes 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. */ use std::{path::PathBuf, sync::{Arc, atomic::AtomicBool}}; use std::time::Duration; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::fs::*; use tokio::sync::Mutex; use async_channel::*; use tokio::sync::broadcast::channel; #[derive(Debug, Clone)] pub struct Entry { pub parent : usize, pub size : u64, pub path : PathBuf, pub children : Vec<usize>, pub num_files : u64, pub is_file : bool, pub expanded : bool, } #[derive(Debug)] pub struct ProgressState { pub count : AtomicUsize, pub done : AtomicUsize, pub complete : AtomicBool, } impl ProgressState { pub fn new() -> Self { Self { count : AtomicUsize::new(0), done : AtomicUsize::new(0), complete : AtomicBool::new(false), } } } #[derive(Debug, Clone)] pub struct DirectoryTreeData { pub entries : Arc<Mutex<Vec<Entry>>>, pub file_types : Arc<Mutex<std::collections::HashMap<Option<String>, u64>>>, } impl DirectoryTreeData { pub fn new() -> DirectoryTreeData { DirectoryTreeData { entries : empty_entry_list(), file_types : Arc::new(Mutex::new(std::collections::HashMap::new())), } } pub async fn from_root_path(path : PathBuf) -> DirectoryTreeData { DirectoryTreeData { entries : directory_entry_list(path).await, file_types : Arc::new(Mutex::new(std::collections::HashMap::new())), } } pub async fn recreate_from_root_path(&self, path : PathBuf) { recreate_directory_entry_list(path, self.entries.clone()).await; self.file_types.lock().await.clear(); } } const NTASKS : usize = 8; pub fn empty_entry_list() -> Arc<Mutex<Vec<Entry>>> { Arc::new(Mutex::new(vec![])) } pub async fn directory_entry_list(path : PathBuf) -> Arc<Mutex<Vec<Entry>>> { let meta = metadata(path.clone()).await.unwrap(); let is_file = meta.is_file(); Arc::new(Mutex::new(vec![Entry{ parent : usize::MAX, size : if is_file {meta.len()} else {0}, num_files : if is_file {1} else {0}, children : vec![], path, is_file, expanded : true, }])) } pub async fn recreate_directory_entry_list(path : PathBuf, entries : Arc<Mutex<Vec<Entry>>>) { let meta = metadata(path.clone()).await.unwrap(); let is_file = meta.is_file(); let mut lock = entries.lock().await; lock.clear(); lock.push(Entry{ parent : usize::MAX, size : if is_file {meta.len()} else {0}, num_files : if is_file {1} else {0}, children : vec![], path, is_file, expanded : true, }); } pub async fn scan_directory(root : usize, DirectoryTreeData{entries, file_types} : DirectoryTreeData, progress : Arc<ProgressState>) { let (tx, rx) : (Sender<Entry>, Receiver<Entry>)= unbounded(); let (done_tx, _) = channel(1); let waiting = Arc::new(AtomicUsize::new(0)); let mut handles = vec![]; for _ in 0..NTASKS { let rx = rx.clone(); let tx = tx.clone(); let mut done_rx = done_tx.subscribe(); let paths = entries.clone(); let progress = progress.clone(); let waiting = waiting.clone(); let file_types = file_types.clone(); let h = tokio::task::spawn(async move { done_rx.recv().await.unwrap(); loop { waiting.fetch_add(1, Ordering::SeqCst); tokio::select! { _ = done_rx.recv() => { break; } Ok(entry) = rx.recv() => { waiting.fetch_sub(1, Ordering::SeqCst); let i = { let mut locked = paths.lock().await; locked.push(entry.clone()); locked.len() - 1 }; if entry.is_file { let mut locked = paths.lock().await; let mut j = locked[i].parent; let n = locked.len(); let file_type = entry.path.extension().map(|ext| String::from(ext.to_string_lossy()).to_uppercase()); file_types.lock().await.entry(file_type) .and_modify(|v| { *v += entry.size; }) .or_insert(entry.size); locked[j].children.push(i); while j < n { locked[j].size += entry.size; locked[j].num_files += 1; j = locked[j].parent; } } else { { let mut locked = paths.lock().await; let j = locked[i].parent; locked[j].children.push(i); } if let Err(e) = process_directory(i, entry.path.clone(), &tx, progress.clone()).await { eprintln!("{:?}: {:?}", e, entry.path); } } progress.done.fetch_add(1, Ordering::SeqCst); } } } }); handles.push(h); } { let locked = entries.lock().await; let root_path = locked[root].path.clone(); if let Err(e) = process_directory(root, root_path, &tx, progress.clone()).await { eprintln!("{:?}", e); } done_tx.send(()).unwrap(); } let mut clock = tokio::time::interval(Duration::from_millis(10)); loop { clock.tick().await; if rx.is_empty() && waiting.load(Ordering::SeqCst) as usize == NTASKS { break; } } done_tx.send(()).unwrap(); for handle in &mut handles { handle.await.unwrap(); } progress.complete.store(true, Ordering::SeqCst); } async fn process_directory(i : usize, path : PathBuf, queue : &Sender<Entry>, progress : Arc<ProgressState>) -> std::io::Result<()> { let mut dir = read_dir(path).await?; loop { match dir.next_entry().await { Ok(Some(subdir)) => { let meta = subdir.metadata().await; if meta.is_err() { continue; } let meta = meta.unwrap(); let size = meta.len(); progress.count.fetch_add(1, Ordering::SeqCst); if meta.is_dir() { queue.send(Entry{ parent : i, size, num_files : 0, path : subdir.path().into(), children : vec![], is_file : false, expanded : false, }).await.unwrap(); } else if meta.is_file() { queue.send(Entry{ parent : i, size, num_files : 1, path : subdir.path().into(), children : vec![], is_file : true, expanded : false, }).await.unwrap(); } } Err(_) => {} _ => break } } Ok(()) } pub fn recalculate_data(entries : &mut [Entry]) { for e in entries.iter_mut() { if e.is_file { e.size = 0; e.num_files = 0; } e.children.clear(); } for i in 1..(entries.len()) { let p = entries[i].parent; entries[p].children.push(i); } fn r_help(entries : &mut [Entry], i : usize) -> (u64, u64) { let mut size = 0; let mut files = 0; for c in entries[i].children.clone() { let (s, f) = r_help(entries, c); size += s; files += f; } entries[i].size = size; entries[i].num_files = files; (size, files) } r_help(entries, 0); }
pub fn sort_subtree_by_size(i : usize, entries : &mut [Entry]) { for c in entries[i].children.clone() { sort_subtree_by_size(c, entries); } let mut j = i; while entries[j].parent < entries.len() { let mut children = entries[j].children.clone(); children.sort_by_cached_key(|&e| entries[e].size); entries[j].children = children; j = entries[j].parent; } } pub fn find_path_index(path : PathBuf, entries : &[Entry]) -> Option<usize> { let mut i = 0; 'outer: loop { for &c in entries[i].children.iter() { let p = &entries[c].path; if path == *p { return Some(c); } if path.starts_with(p) { i = c; continue 'outer; } } break } None } #[test] fn test_perf() { use std::time::Instant; let root = PathBuf::from("C:\\"); let progress = Arc::new(ProgressState::new()); let start = Instant::now(); tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap() .block_on(async { let entries = directory_entry_list(root).await; let file_types = Arc::new(Mutex::new(std::collections::HashMap::new())); scan_directory(0, DirectoryTreeData{entries, file_types}, progress).await }); let elapsed = start.elapsed(); eprintln!("Elapsed: {:?}", elapsed); }
pub fn delete_subtree(entries : &mut Vec<Entry>, subtree : usize) { let mut new_idx = entries.iter().map(|_| usize::MAX).collect::<Vec<_>>(); let mut next_i = 0; for i in 0..(entries.len()) { let parent = entries[i].parent; if parent == subtree || i == subtree { entries[i].parent = subtree; } else { new_idx[i] = next_i; next_i += 1; } } for (i, ni) in new_idx.iter().cloned().enumerate() { if i == ni || ni == usize::MAX { continue; } entries.swap(i, ni); } entries.truncate(next_i); recalculate_data(entries) }
function_block-full_function
[ { "content": "/// Build ui elements\n\nfn display_file_tree(display_entries : &mut Vec<Entry>, ui : &Ui) {\n\n \n\n let cw = ui.window_content_region_width();\n\n\n\n #[derive(Debug, Clone, Copy, Default)]\n\n struct DrawParams {\n\n psize : u64,\n\n content_width : f32,\n\n }\n\n\n...
Rust
src/connectivity/overnet/lib/core/src/fidl_tests/mod.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
#![cfg(test)] use crate::future_help::log_errors; use crate::link::Link; use crate::router::test_util::{run, test_router_options}; use crate::router::Router; use crate::runtime::spawn; use fidl::HandleBased; use fuchsia_zircon_status as zx_status; use futures::prelude::*; use std::rc::Rc; mod channel; mod socket; struct Service(futures::channel::mpsc::Sender<fidl::Channel>); impl fidl_fuchsia_overnet::ServiceProviderProxyInterface for Service { fn connect_to_service( &self, chan: fidl::Channel, _connection_info: fidl_fuchsia_overnet::ConnectionInfo, ) -> std::result::Result<(), fidl::Error> { let mut sender = self.0.clone(); spawn(log_errors( async move { sender.send(chan).await.map_err(Into::into) }, "failed to send incoming request handle", )); Ok(()) } } struct Fixture { dist_a_to_b: fidl::Channel, dist_b: fidl::Channel, dist_a_to_c: fidl::Channel, dist_c: fidl::Channel, tx_fin: Option<futures::channel::oneshot::Sender<()>>, } fn forward(sender: Rc<Link>, receiver: Rc<Link>) { spawn(log_errors( async move { let mut frame = [0u8; 2048]; while let Some(n) = sender.next_send(&mut frame).await? { receiver.received_packet(&mut frame[..n]).await?; } Ok(()) }, "forwarder failed", )); } async fn link(a: &Rc<Router>, b: &Rc<Router>) { let ab = a.new_link(b.node_id()).await.unwrap(); let ba = b.new_link(a.node_id()).await.unwrap(); forward(ab.clone(), ba.clone()); forward(ba, ab); } #[derive(Clone, Copy, Debug)] enum Target { A, B, C, } impl Fixture { fn new() -> Fixture { let (tx_init, rx_init) = std::sync::mpsc::channel(); let (tx_fin, rx_fin) = futures::channel::oneshot::channel(); std::thread::spawn(move || { run(|| async move { let router1 = Router::new(test_router_options()).unwrap(); let router2 = Router::new(test_router_options()).unwrap(); let router3 = Router::new(test_router_options()).unwrap(); link(&router1, &router2).await; link(&router2, &router3).await; link(&router3, &router1).await; const SERVICE: &'static str = "distribute_handle"; let (send_handle, mut recv_handle) = futures::channel::mpsc::channel(1); router2 .service_map() .register_service(SERVICE.to_string(), Box::new(Service(send_handle.clone()))) .await; router3 .service_map() .register_service(SERVICE.to_string(), Box::new(Service(send_handle))) .await; let (dist_a_to_b, dist_b) = fidl::Channel::create().unwrap(); let (dist_a_to_c, dist_c) = fidl::Channel::create().unwrap(); router1.connect_to_service(router2.node_id(), SERVICE, dist_b).await.unwrap(); let dist_b = recv_handle.next().await.unwrap(); router1.connect_to_service(router3.node_id(), SERVICE, dist_c).await.unwrap(); let dist_c = recv_handle.next().await.unwrap(); tx_init.send((dist_a_to_b, dist_b)).unwrap(); tx_init.send((dist_a_to_c, dist_c)).unwrap(); rx_fin.await.unwrap(); }) }); let (dist_a_to_b, dist_b) = rx_init.recv().unwrap(); let (dist_a_to_c, dist_c) = rx_init.recv().unwrap(); Fixture { dist_a_to_b, dist_b, dist_a_to_c, dist_c, tx_fin: Some(tx_fin) } } fn distribute_handle<H: HandleBased>(&self, h: H, target: Target) -> H { let h = h.into_handle(); log::trace!("distribute_handle: make {:?} on {:?}", h, target); let (dist_local, dist_remote) = match target { Target::A => return H::from_handle(h), Target::B => (&self.dist_a_to_b, &self.dist_b), Target::C => (&self.dist_a_to_c, &self.dist_c), }; assert!(dist_local.write(&[], &mut vec![h]) == Ok(())); loop { let (mut bytes, mut handles) = (Vec::new(), Vec::new()); match dist_remote.read_split(&mut bytes, &mut handles) { Ok(()) => { assert_eq!(bytes, vec![]); assert_eq!(handles.len(), 1); let h = handles.into_iter().next().unwrap(); log::trace!("distribute_handle: remote is {:?}", h); return H::from_handle(h); } Err(zx_status::Status::SHOULD_WAIT) => { continue; } Err(e) => panic!("Unexpected error {:?}", e), } } } } impl Drop for Fixture { fn drop(&mut self) { self.tx_fin.take().unwrap().send(()).unwrap(); } }
#![cfg(test)] use crate::future_help::log_errors; use crate::link::Link; use crate::router::test_util::{run, test_router_options}; use crate::router::Router; use crate::runtime::spawn; use fidl::HandleBased; use fuchsia_zircon_status as zx_status; use futures::prelude::*; use std::rc::Rc; mod channel; mod socket; struct Service(futures::channel::mpsc::Sender<fidl::Channel>); impl fidl_fuchsia_overnet::ServiceProviderProxyInterface for Service { fn connect_to_service( &self, chan: fidl::Channel, _connection_info: fidl_fuchsia_overnet::ConnectionInfo, ) -> std::result::Result<(), fidl::Error> { let mut sender = self.0.clone(); spawn(log_errors( async move { sender.send(chan).await.map_err(Into::into) }, "failed to send incoming request handle", )); Ok(()) } } struct Fixture { dist_a_to_b: fidl::Channel, dist_b: fidl::Channel, dist_a_to_c: fidl::Channel, dist_c: fidl::Channel, tx_fin: Option<futures::channel::oneshot::Sender<()>>, } fn forward(sender: Rc<Link>, receiver: Rc<Link>) { spawn(log_errors( async move { let mut frame = [0u8; 2048]; while let Some(n) = sender.next_send(&mut frame).await? { receiver.received_packet(&mut frame[..n]).await?; } Ok(()) }, "forwarder failed", )); } async fn link(a: &Rc<Router>, b: &Rc<Router>) { let ab = a.new_link(b.node_id()).await.unwrap(); let ba = b.new_link(a.node_id()).await.unwrap(); forward(ab.clone(), ba.clone()); forward(ba, ab); } #[derive(Clone, Copy, Debug)] enum Target { A, B, C, } impl Fixture { fn new() -> Fixture { let (tx_init, rx_init) = std::sync::mpsc::channel(); let (tx_fin, rx_fin) = futures::channel::oneshot::channel(); std::thread::spawn(move || { run(|| async move { let router1 = Router::new(test_router_options()).unwrap(); let router2 = Router::new(test_router_options()).unwrap(); let router3 = Router::new(test_router_options()).unwrap(); link(&router1, &router2).await; link(&router2, &router3).await; link(&router3, &router1).await; const SERVICE: &'static str = "distribute_handle"; let (send_handle, mut recv_handle) = futures::channel::mpsc::channel(1); router2 .service_map() .register_service(SERVICE.to_string(), Box::new(Service(send_handle.clone()))) .await; router3 .service_map() .register_service(SERVICE.to_string(), Box::new(Service(send_handle))) .await; let (dist_a_to_b, dist_b) = fidl::Channel::create().unwrap(); let (dist_a_to_c, dist_c) = fidl::Channel::create().unwrap(); router1.connect_to_service(router2.node_id(), SERVICE, dist_b).await.unwrap(); let dist_b = recv_handle.next().await.unwrap(); router1.connect_to_service(router3.node_id(), SERVICE, dist_c).await.unwrap(); let dist_c = recv_handle.next().await.unwrap(); tx_init.send((dist_a_to_b, dist_b)).unwrap(); tx_init.send((dist_a_to_c, dist_c)).unwrap(); rx_fin.await.unwrap(); }) }); let (dist_a_to_b, dist_b) = rx_init.recv().unwrap(); let (dist_a_to_c, dist_c) = rx_init.recv().unwrap(); Fixture { dist_a_to_b, dist_b, dist_a_to_c, dist_c, tx_fin: Some(tx_fin) } }
} impl Drop for Fixture { fn drop(&mut self) { self.tx_fin.take().unwrap().send(()).unwrap(); } }
fn distribute_handle<H: HandleBased>(&self, h: H, target: Target) -> H { let h = h.into_handle(); log::trace!("distribute_handle: make {:?} on {:?}", h, target); let (dist_local, dist_remote) = match target { Target::A => return H::from_handle(h), Target::B => (&self.dist_a_to_b, &self.dist_b), Target::C => (&self.dist_a_to_c, &self.dist_c), }; assert!(dist_local.write(&[], &mut vec![h]) == Ok(())); loop { let (mut bytes, mut handles) = (Vec::new(), Vec::new()); match dist_remote.read_split(&mut bytes, &mut handles) { Ok(()) => { assert_eq!(bytes, vec![]); assert_eq!(handles.len(), 1); let h = handles.into_iter().next().unwrap(); log::trace!("distribute_handle: remote is {:?}", h); return H::from_handle(h); } Err(zx_status::Status::SHOULD_WAIT) => { continue; } Err(e) => panic!("Unexpected error {:?}", e), } } }
function_block-full_function
[]
Rust
src/tasks/git.rs
jokeyrhyme/dotfiles-rs
8e723ee271675ba783e15e608164813a4a136efb
use std::{collections::HashMap, fs, str}; use serde_derive::Deserialize; use crate::{ lib::task::{self, Status, Task}, utils, }; const COMMAND_DELIMITERS: &[char] = &[';', '|', '&']; const ERROR_MSG: &str = "error: git"; pub fn task() -> Task { Task { name: String::from("git"), sync, ..Default::default() } } #[derive(Debug, Deserialize, PartialEq)] struct ComplexConfigEntry { value: String, #[serde(default)] when: String, } impl<S> From<S> for ComplexConfigEntry where S: AsRef<str>, { fn from(s: S) -> ComplexConfigEntry { ComplexConfigEntry { value: String::from(s.as_ref()), when: String::new(), } } } #[derive(Debug, Deserialize, PartialEq)] struct Config { config: HashMap<String, ConfigEntry>, } impl Config { fn new() -> Config { Config { config: HashMap::<String, ConfigEntry>::new(), } } } impl<S> From<S> for Config where S: AsRef<str>, { fn from(s: S) -> Config { match toml::from_str(&s.as_ref()) { Ok(c) => c, Err(error) => { println!("warning: git: unable to parse TOML, {}", error); Config::new() } } } } #[derive(Debug, Deserialize, PartialEq)] #[serde(untagged)] enum ConfigEntry { Basic(String), Complex(ComplexConfigEntry), } fn extract_commands<S>(s: S) -> Vec<String> where S: AsRef<str>, { s.as_ref() .split(|c: char| COMMAND_DELIMITERS.contains(&c)) .filter_map(|s| match s.trim().split(' ').next() { Some("") => None, Some(s) => Some(String::from(s)), None => None, }) .collect() } fn sync() -> task::Result { if !utils::git::has() { return Ok(Status::Skipped); } let cfg = Config::from(load_config()); for (key, ce) in cfg.config { let cce = match ce { ConfigEntry::Basic(s) => ComplexConfigEntry::from(s), ConfigEntry::Complex(c) => c, }; match cce.when.as_str() { "unset" => { let current = utils::process::command_output("git", &["config", "--global", "--get", &key])?; if str::from_utf8(&current.stdout) .unwrap_or_default() .trim() .is_empty() { utils::process::command_spawn_wait( "git", &["config", "--global", &key, &cce.value], )?; } } "which" => { if extract_commands(cce.value.clone()) .iter() .all(|v| which::which(v).is_ok()) { utils::process::command_spawn_wait( "git", &["config", "--global", &key, &cce.value], )?; } } _ => { utils::process::command_spawn_wait( "git", &["config", "--global", &key, &cce.value], )?; } }; } if !utils::nodejs::has_npx() { return Ok(Status::Skipped); } utils::process::command_spawn_wait("npx", &["-q", "npm-merge-driver", "install", "--global"]) .expect(ERROR_MSG); if utils::nodejs::has_yarn() { utils::process::command_spawn_wait( "npx", &[ "-q", "npm-merge-driver", "install", "--global", "--driver-name", "yarn-merge-driver", "--driver", "npx npm-merge-driver merge %A %O %B %P -c yarn", "--files", "yarn.lock", ], ) .expect(ERROR_MSG); } Ok(Status::Done) } fn load_config() -> String { let cfg_path = utils::env::home_dir().join(".dotfiles/config/git.toml"); match fs::read_to_string(&cfg_path) { Ok(s) => s, Err(error) => { println!("git: ignoring config: {}", error); String::new() } } } #[cfg(test)] mod test { use super::*; #[test] fn extract_commands_from_strings() { assert_eq!(extract_commands("gpg"), vec![String::from("gpg")]); assert_eq!( extract_commands("diff | less"), vec![String::from("diff"), String::from("less")] ); assert_eq!( extract_commands("diff foo bar; less"), vec![String::from("diff"), String::from("less")] ); assert_eq!( extract_commands("diff && less foo"), vec![String::from("diff"), String::from("less")] ); } #[test] fn parse_config_toml() { let input = r#" [config] "color.ui" = "foo.bar" "gpg.program" = { value = "gpg", when = "which" } "#; let mut want = HashMap::<String, ConfigEntry>::new(); want.insert( String::from("color.ui"), ConfigEntry::Basic(String::from("foo.bar")), ); want.insert( String::from("gpg.program"), ConfigEntry::Complex(ComplexConfigEntry { value: String::from("gpg"), when: String::from("which"), }), ); let cfg = Config::from(input); assert_eq!(want, cfg.config); } }
use std::{collections::HashMap, fs, str}; use serde_derive::Deserialize; use crate::{ lib::task::{self, Status, Task}, utils, }; const COMMAND_DELIMITERS: &[char] = &[';', '|', '&']; const ERROR_MSG: &str = "error: git"; pub fn task() -> Task { Task { name: String::from("git"), sync, ..Default::default() } } #[derive(Debug, Deserialize, PartialEq)] struct ComplexConfigEntry { value: String, #[serde(default)] when: String, } impl<S> From<S> for ComplexConfigEntry where S: AsRef<str>, { fn from(s: S) -> ComplexConfigEntry { ComplexConfigEntry { value: String::from(s.as_ref()), when: String::new(), } } } #[derive(Debug, Deserialize, PartialEq)] struct Config { config: HashMap<String, ConfigEntry>, } impl Config { fn new() -> Config { Config { config: HashMap::<String, ConfigEntry>::new(), } } } impl<S> From<S> for Config where S: AsRef<str>, { fn from(s: S) -> Config { match toml::from_str(&s.as_ref()) { Ok(c) => c, Err(error) => { println!("warning: git: unable to parse TOML, {}", error); Config::new() } } } } #[derive(Debug, Deserialize, PartialEq)] #[serde(untagged)] enum ConfigEntry { Basic(String), Complex(ComplexConfigEntry), }
fn sync() -> task::Result { if !utils::git::has() { return Ok(Status::Skipped); } let cfg = Config::from(load_config()); for (key, ce) in cfg.config { let cce = match ce { ConfigEntry::Basic(s) => ComplexConfigEntry::from(s), ConfigEntry::Complex(c) => c, }; match cce.when.as_str() { "unset" => { let current = utils::process::command_output("git", &["config", "--global", "--get", &key])?; if str::from_utf8(&current.stdout) .unwrap_or_default() .trim() .is_empty() { utils::process::command_spawn_wait( "git", &["config", "--global", &key, &cce.value], )?; } } "which" => { if extract_commands(cce.value.clone()) .iter() .all(|v| which::which(v).is_ok()) { utils::process::command_spawn_wait( "git", &["config", "--global", &key, &cce.value], )?; } } _ => { utils::process::command_spawn_wait( "git", &["config", "--global", &key, &cce.value], )?; } }; } if !utils::nodejs::has_npx() { return Ok(Status::Skipped); } utils::process::command_spawn_wait("npx", &["-q", "npm-merge-driver", "install", "--global"]) .expect(ERROR_MSG); if utils::nodejs::has_yarn() { utils::process::command_spawn_wait( "npx", &[ "-q", "npm-merge-driver", "install", "--global", "--driver-name", "yarn-merge-driver", "--driver", "npx npm-merge-driver merge %A %O %B %P -c yarn", "--files", "yarn.lock", ], ) .expect(ERROR_MSG); } Ok(Status::Done) } fn load_config() -> String { let cfg_path = utils::env::home_dir().join(".dotfiles/config/git.toml"); match fs::read_to_string(&cfg_path) { Ok(s) => s, Err(error) => { println!("git: ignoring config: {}", error); String::new() } } } #[cfg(test)] mod test { use super::*; #[test] fn extract_commands_from_strings() { assert_eq!(extract_commands("gpg"), vec![String::from("gpg")]); assert_eq!( extract_commands("diff | less"), vec![String::from("diff"), String::from("less")] ); assert_eq!( extract_commands("diff foo bar; less"), vec![String::from("diff"), String::from("less")] ); assert_eq!( extract_commands("diff && less foo"), vec![String::from("diff"), String::from("less")] ); } #[test] fn parse_config_toml() { let input = r#" [config] "color.ui" = "foo.bar" "gpg.program" = { value = "gpg", when = "which" } "#; let mut want = HashMap::<String, ConfigEntry>::new(); want.insert( String::from("color.ui"), ConfigEntry::Basic(String::from("foo.bar")), ); want.insert( String::from("gpg.program"), ConfigEntry::Complex(ComplexConfigEntry { value: String::from("gpg"), when: String::from("which"), }), ); let cfg = Config::from(input); assert_eq!(want, cfg.config); } }
fn extract_commands<S>(s: S) -> Vec<String> where S: AsRef<str>, { s.as_ref() .split(|c: char| COMMAND_DELIMITERS.contains(&c)) .filter_map(|s| match s.trim().split(' ').next() { Some("") => None, Some(s) => Some(String::from(s)), None => None, }) .collect() }
function_block-full_function
[ { "content": "pub fn latest_version() -> Result<String, task::Error> {\n\n let tags: Vec<utils::github::Tag> = utils::github::fetch_tags(\"golang\", \"go\")?;\n\n let release_tags: Vec<utils::github::Tag> = tags\n\n .into_iter()\n\n .filter(|t| {\n\n // release tags look like \"go...
Rust
src/db/raw.rs
wrenger/schiller-lib
fd1e45797f602db7ec037a6892b6d1bff26d287f
use std::collections::HashMap; pub trait DatabaseExt { fn fetch(&self, statement: &str) -> Result<Vec<Vec<String>>, sqlite::Error>; fn transaction(&self) -> Result<Transaction, sqlite::Error>; } impl DatabaseExt for sqlite::Connection { fn fetch(&self, statement: &str) -> Result<Vec<Vec<String>>, sqlite::Error> { let mut result = vec![]; self.iterate(statement, |pairs| { result.push( pairs .iter() .map(|&(_, value)| value.unwrap_or_default().into()) .collect(), ); true })?; Ok(result) } fn transaction(&self) -> Result<Transaction, sqlite::Error> { self.execute("begin")?; Ok(Transaction { db: self }) } } pub struct Transaction<'a> { db: &'a sqlite::Connection, } impl<'a> Transaction<'a> { pub fn commit(self) -> Result<(), sqlite::Error> { self.db.execute("commit")?; std::mem::forget(self); Ok(()) } } impl<'a> Drop for Transaction<'a> { fn drop(&mut self) { self.db.execute("rollback").ok(); } } pub trait StatementExt { fn columns(&self) -> HashMap<String, usize>; } impl<'a> StatementExt for sqlite::Statement<'a> { fn columns(&self) -> HashMap<String, usize> { (0..self.column_count()) .map(|i| (self.column_name(i).to_string(), i)) .collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn connection() { sqlite::Connection::open(":memory:").unwrap(); } #[test] fn fetch() { let db = sqlite::Connection::open(":memory:").unwrap(); db.execute("create table abc (a, b, c)").unwrap(); db.execute("insert into abc values ('a', 'b', 'c')") .unwrap(); let result = db.fetch("select * from abc").unwrap(); assert_eq!( vec![vec![ String::from("a"), String::from("b"), String::from("c") ]], result ); } #[test] fn multiple() { let db = sqlite::Connection::open(":memory:").unwrap(); db.execute( "begin; \ create table abc (a, b, c); \ insert into abc values ('d', 'e', 'f'); \ commit;", ) .unwrap(); let result = db .fetch( "insert into abc values ('a', 'b', 'c'); \ select * from abc order by a", ) .unwrap(); assert_eq!( vec![ vec![String::from("a"), String::from("b"), String::from("c")], vec![String::from("d"), String::from("e"), String::from("f")] ], result ); } #[test] fn prepare() { let db = sqlite::Connection::open(":memory:").unwrap(); db.execute("create table abc (a, b, c)").unwrap(); let mut stmt = db.prepare("insert into abc values (?, ?, ?)").unwrap(); stmt.bind(1, "1").unwrap(); stmt.bind(2, "2").unwrap(); stmt.bind(3, "3").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); let mut stmt = db.prepare("insert into abc values (?3, ?2, ?1)").unwrap(); stmt.bind(1, "4").unwrap(); stmt.bind(2, "5").unwrap(); stmt.bind(3, "6").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); assert_eq!( vec![ vec![String::from("1"), String::from("2"), String::from("3")], vec![String::from("6"), String::from("5"), String::from("4")] ], db.fetch("select * from abc").unwrap() ); let mut stmt = db.prepare("select a from abc where a='1'").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Row); assert_eq!(stmt.read::<i64>(0).unwrap(), 1); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); } #[test] fn transaction() { let db = sqlite::Connection::open(":memory:").unwrap(); db.execute("create table abc (a not null, b, c)").unwrap(); { let _transaction = db.transaction().unwrap(); let mut stmt = db.prepare("insert into abc values (?, ?, ?)").unwrap(); stmt.bind(1, "4").unwrap(); stmt.bind(2, "5").unwrap(); stmt.bind(3, "6").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); }; assert!(db.fetch("select * from abc").unwrap().is_empty()); { let _transaction = db.transaction().unwrap(); let mut stmt = db.prepare("insert into abc values (?, ?, ?)").unwrap(); stmt.bind(2, "5").unwrap(); stmt.bind(3, "6").unwrap(); stmt.next().expect_err("Null violation!"); }; assert!(db.fetch("select * from abc").unwrap().is_empty()); { let transaction = db.transaction().unwrap(); let mut stmt = db.prepare("insert into abc values (?, ?, ?)").unwrap(); stmt.bind(1, "1").unwrap(); stmt.bind(2, "2").unwrap(); stmt.bind(3, "3").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); println!("finish -> commit"); transaction.commit().unwrap(); }; assert_eq!( vec![vec![ String::from("1"), String::from("2"), String::from("3") ],], db.fetch("select * from abc").unwrap() ); } }
use std::collections::HashMap; pub trait DatabaseExt { fn fetch(&self, statement: &str) -> Result<Vec<Vec<String>>, sqlite::Error>; fn transaction(&self) -> Result<Transaction, sqlite::Error>; } impl DatabaseExt for sqlite::Connection {
fn transaction(&self) -> Result<Transaction, sqlite::Error> { self.execute("begin")?; Ok(Transaction { db: self }) } } pub struct Transaction<'a> { db: &'a sqlite::Connection, } impl<'a> Transaction<'a> { pub fn commit(self) -> Result<(), sqlite::Error> { self.db.execute("commit")?; std::mem::forget(self); Ok(()) } } impl<'a> Drop for Transaction<'a> { fn drop(&mut self) { self.db.execute("rollback").ok(); } } pub trait StatementExt { fn columns(&self) -> HashMap<String, usize>; } impl<'a> StatementExt for sqlite::Statement<'a> { fn columns(&self) -> HashMap<String, usize> { (0..self.column_count()) .map(|i| (self.column_name(i).to_string(), i)) .collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn connection() { sqlite::Connection::open(":memory:").unwrap(); } #[test] fn fetch() { let db = sqlite::Connection::open(":memory:").unwrap(); db.execute("create table abc (a, b, c)").unwrap(); db.execute("insert into abc values ('a', 'b', 'c')") .unwrap(); let result = db.fetch("select * from abc").unwrap(); assert_eq!( vec![vec![ String::from("a"), String::from("b"), String::from("c") ]], result ); } #[test] fn multiple() { let db = sqlite::Connection::open(":memory:").unwrap(); db.execute( "begin; \ create table abc (a, b, c); \ insert into abc values ('d', 'e', 'f'); \ commit;", ) .unwrap(); let result = db .fetch( "insert into abc values ('a', 'b', 'c'); \ select * from abc order by a", ) .unwrap(); assert_eq!( vec![ vec![String::from("a"), String::from("b"), String::from("c")], vec![String::from("d"), String::from("e"), String::from("f")] ], result ); } #[test] fn prepare() { let db = sqlite::Connection::open(":memory:").unwrap(); db.execute("create table abc (a, b, c)").unwrap(); let mut stmt = db.prepare("insert into abc values (?, ?, ?)").unwrap(); stmt.bind(1, "1").unwrap(); stmt.bind(2, "2").unwrap(); stmt.bind(3, "3").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); let mut stmt = db.prepare("insert into abc values (?3, ?2, ?1)").unwrap(); stmt.bind(1, "4").unwrap(); stmt.bind(2, "5").unwrap(); stmt.bind(3, "6").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); assert_eq!( vec![ vec![String::from("1"), String::from("2"), String::from("3")], vec![String::from("6"), String::from("5"), String::from("4")] ], db.fetch("select * from abc").unwrap() ); let mut stmt = db.prepare("select a from abc where a='1'").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Row); assert_eq!(stmt.read::<i64>(0).unwrap(), 1); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); } #[test] fn transaction() { let db = sqlite::Connection::open(":memory:").unwrap(); db.execute("create table abc (a not null, b, c)").unwrap(); { let _transaction = db.transaction().unwrap(); let mut stmt = db.prepare("insert into abc values (?, ?, ?)").unwrap(); stmt.bind(1, "4").unwrap(); stmt.bind(2, "5").unwrap(); stmt.bind(3, "6").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); }; assert!(db.fetch("select * from abc").unwrap().is_empty()); { let _transaction = db.transaction().unwrap(); let mut stmt = db.prepare("insert into abc values (?, ?, ?)").unwrap(); stmt.bind(2, "5").unwrap(); stmt.bind(3, "6").unwrap(); stmt.next().expect_err("Null violation!"); }; assert!(db.fetch("select * from abc").unwrap().is_empty()); { let transaction = db.transaction().unwrap(); let mut stmt = db.prepare("insert into abc values (?, ?, ?)").unwrap(); stmt.bind(1, "1").unwrap(); stmt.bind(2, "2").unwrap(); stmt.bind(3, "3").unwrap(); assert_eq!(stmt.next().unwrap(), sqlite::State::Done); println!("finish -> commit"); transaction.commit().unwrap(); }; assert_eq!( vec![vec![ String::from("1"), String::from("2"), String::from("3") ],], db.fetch("select * from abc").unwrap() ); } }
fn fetch(&self, statement: &str) -> Result<Vec<Vec<String>>, sqlite::Error> { let mut result = vec![]; self.iterate(statement, |pairs| { result.push( pairs .iter() .map(|&(_, value)| value.unwrap_or_default().into()) .collect(), ); true })?; Ok(result) }
function_block-full_function
[ { "content": "/// MARC21 Parsing\n\n///\n\n/// ## See Also\n\n/// https://www.dnb.de/EN/Professionell/Metadatendienste/Datenbezug/SRU/sru_node.html\n\npub fn parse(response: &str, isbn: &str) -> api::Result<BookData> {\n\n let document = roxmltree::Document::parse(response)?;\n\n\n\n let mut first_result ...
Rust
webnis-server/src/webnis.rs
EwoutH/webnis
078814931bd5dab47eebe0c21d32d3045a4d6040
use std::collections::HashMap; use std::sync::Arc; use actix_web::http::StatusCode; use actix_web::HttpResponse; use serde_json; use crate::config; use crate::db; use crate::db::MapType; use crate::errors::WnError; use crate::format; use crate::iplist::IpList; use crate::lua; use crate::util::*; #[derive(Clone)] pub(crate) struct Webnis { pub inner: Arc<WebnisInner>, } pub(crate) struct WebnisInner { pub config: config::Config, pub securenets: Option<IpList>, } impl Webnis { pub fn new(config: config::Config, securenets: Option<IpList>) -> Webnis { Webnis { inner: Arc::new(WebnisInner { config: config, securenets: securenets, }), } } } impl Webnis { pub fn handle_info(&self, domain: &str) -> HttpResponse { let domain = match self.inner.config.find_domain(domain) { None => return json_error(StatusCode::BAD_REQUEST, None, "Domain not found"), Some(d) => d, }; let mut maps = HashMap::new(); for mapname in &domain.maps { let mut map_keys = Vec::new(); let mapvec = match self.inner.config.map_.get(mapname) { Some(i) => i, None => continue, }; for m in mapvec { let keys = m.key.iter().chain(m.keys.iter()).chain(m.key_alias.keys()); map_keys.extend(keys); } let mut hm = HashMap::new(); hm.insert("keys", map_keys); maps.insert(mapname, hm); } #[derive(Serialize)] struct Reply<T> { maps: T, } let r = Reply { maps: maps }; let reply = serde_json::to_value(r).unwrap(); json_result(StatusCode::OK, &reply) } pub fn handle_auth(&self, domain: String, is_json: bool, body: Vec<u8>) -> HttpResponse { let domain = match self.inner.config.find_domain(&domain) { None => return json_error(StatusCode::BAD_REQUEST, None, "Domain not found"), Some(d) => d, }; let authinfo = match AuthInfo::from_post_body(&body, is_json) { None => return json_error(StatusCode::BAD_REQUEST, None, "Body parameters missing"), Some(ai) => ai, }; let auth = match domain.auth.as_ref().and_then(|a| self.inner.config.auth.get(a)) { None => return json_error(StatusCode::NOT_FOUND, None, "Authentication not enabled"), Some(a) => a, }; if let Some(ref lua_func) = auth.lua_function { let lauth = lua::AuthInfo { username: authinfo.username, password: authinfo.password, map: auth.map.clone(), key: auth.key.clone(), extra: authinfo.extra, }; let res = match lua::lua_auth(lua_func, &domain.name, lauth) { Ok((serde_json::Value::Null, status)) => { if status == 0 { json_error( StatusCode::FORBIDDEN, Some(StatusCode::UNAUTHORIZED), "Password incorrect", ) } else { json_error( StatusCode::from_u16(status).unwrap(), Some(StatusCode::UNAUTHORIZED), "Password incorrect", ) } }, Ok((val, status)) => { if status == 0 { json_result(StatusCode::OK, &val) } else { json_result_raw(StatusCode::from_u16(status).unwrap(), &val) } }, Err(_) => json_error(StatusCode::INTERNAL_SERVER_ERROR, None, "Internal server error"), }; return res; } let auth_map = auth.map.as_ref().unwrap(); let auth_key = auth.key.as_ref().unwrap(); match self.auth_map(domain, auth_map, auth_key, &authinfo.username, &authinfo.password) { Ok(true) => json_result(StatusCode::OK, &json!({})), Ok(false) => { json_error( StatusCode::FORBIDDEN, Some(StatusCode::UNAUTHORIZED), "Password incorrect", ) }, Err(WnError::MapNotFound) => { return json_error(StatusCode::NOT_FOUND, None, "Associated auth map not found"); }, Err(_) => json_error(StatusCode::INTERNAL_SERVER_ERROR, None, "Internal server error"), } } fn auth_map( &self, dom: &config::Domain, map: &str, key: &str, username: &str, passwd: &str, ) -> Result<bool, WnError> { let (map, keyname) = match self.inner.config.find_map(map, key) { None => { warn!("auth_map: map {} with key {} not found", map, key); return Err(WnError::MapNotFound); }, Some(m) => m, }; let res = match map.map_type { MapType::Gdbm => self.lookup_gdbm_map(dom, map, username), MapType::Json => self.lookup_json_map(dom, map, keyname, username), _ => { warn!("auth_map: map {}: unsupported {:?}", map.name, map.map_type); return Err(WnError::DbOther); }, }; let json = match res { Ok(jv) => jv, Err(WnError::KeyNotFound) => return Ok(false), Err(e) => return Err(e), }; let res = match json.get("passwd").map(|p| p.as_str()).unwrap_or(None) { None => false, Some(hash) => check_unix_password(passwd, hash), }; Ok(res) } pub fn lua_map_auth( &self, domain: &str, map: &str, key: &str, username: &str, passwd: &str, ) -> Result<bool, WnError> { let domain = match self.inner.config.find_domain(&domain) { None => return Err(WnError::DbOther), Some(d) => d, }; self.auth_map(domain, map, key, username, passwd) } pub fn handle_map(&self, domain: &str, map: &str, query: &HashMap<String, String>) -> HttpResponse { let domain = match self.inner.config.find_domain(&domain) { None => return json_error(StatusCode::BAD_REQUEST, None, "Domain not found"), Some(d) => d, }; let (keyname, keyval) = match query.iter().next() { None => return json_error(StatusCode::BAD_REQUEST, None, "Query params missing"), Some(kv) => kv, }; let (map, keyname) = match self.inner.config.find_allowed_map(&domain, map, keyname) { None => return json_error(StatusCode::NOT_FOUND, None, "No such map"), Some(m) => m, }; let res = match map.map_type { MapType::Gdbm => self.lookup_gdbm_map(domain, map, keyval), MapType::Json => self.lookup_json_map(domain, map, keyname, keyval), MapType::Lua => self.lookup_lua_map(domain, map, keyname, keyval), MapType::None => unreachable!(), }; match res { Err(WnError::KeyNotFound) => json_error(StatusCode::NOT_FOUND, None, "No such key in map"), Err(WnError::MapNotFound) => json_error(StatusCode::NOT_FOUND, None, "No such map"), Err(WnError::UnknownFormat) => json_error(StatusCode::NOT_FOUND, None, "Unknown map format"), Err(WnError::SerializeJson(_)) => json_error(StatusCode::NOT_FOUND, None, "Serialize error"), Err(_) => json_error(StatusCode::INTERNAL_SERVER_ERROR, None, "Error reading database"), Ok(r) => json_result(StatusCode::OK, &r), } } pub fn lua_map_lookup( &self, domain: &str, mapname: &str, keyname: &str, keyval: &str, ) -> Result<serde_json::Value, WnError> { let domain = match self.inner.config.find_domain(&domain) { None => return Err(WnError::DbOther), Some(d) => d, }; let (map, keyname) = match self.inner.config.find_map(mapname, keyname) { None => return Err(WnError::MapNotFound), Some(m) => m, }; let res = match map.map_type { MapType::Gdbm => self.lookup_gdbm_map(domain, map, keyval), MapType::Json => self.lookup_json_map(domain, map, keyname, keyval), _ => Err(WnError::Other), }; match res { Err(WnError::KeyNotFound) => Ok(json!(null)), x => x, } } fn lookup_gdbm_map( &self, dom: &config::Domain, map: &config::Map, keyval: &str, ) -> Result<serde_json::Value, WnError> { let format = match map.map_format { None => return Err(WnError::UnknownFormat), Some(ref s) => s, }; let path = format!("{}/{}", dom.db_dir, map.map_file.as_ref().unwrap()); let line = db::gdbm_lookup(&path, keyval)?; format::line_to_json(&line, format, &map.map_output) } fn lookup_json_map( &self, dom: &config::Domain, map: &config::Map, keyname: &str, keyval: &str, ) -> Result<serde_json::Value, WnError> { let path = format!("{}/{}", dom.db_dir, map.map_file.as_ref().unwrap()); db::json_lookup(path, keyname, keyval) } fn lookup_lua_map( &self, dom: &config::Domain, map: &config::Map, keyname: &str, keyval: &str, ) -> Result<serde_json::Value, WnError> { match lua::lua_map(&map.lua_function.as_ref().unwrap(), &dom.name, keyname, keyval) { Ok(serde_json::Value::Null) => Err(WnError::KeyNotFound), Ok(m) => Ok(m), Err(_) => Err(WnError::Other), } } }
use std::collections::HashMap; use std::sync::Arc; use actix_web::http::StatusCode; use actix_web::HttpResponse; use serde_json; use crate::config; use crate::db; use crate::db::MapType; use crate::errors::WnError; use crate::format; use crate::iplist::IpList; use crate::lua; use crate::util::*; #[derive(Clone)] pub(crate) struct Webnis { pub inner: Arc<WebnisInner>, } pub(crate) struct WebnisInner { pub config: config::Config, pub securenets: Option<IpList>, } impl Webnis { pub fn new(config: config::Config, securenets: Option<IpList>) -> Webnis { Webnis { inner: Arc::new(WebnisInner { config: config, securenets: securenets, }), } } } impl Webnis {
pub fn handle_auth(&self, domain: String, is_json: bool, body: Vec<u8>) -> HttpResponse { let domain = match self.inner.config.find_domain(&domain) { None => return json_error(StatusCode::BAD_REQUEST, None, "Domain not found"), Some(d) => d, }; let authinfo = match AuthInfo::from_post_body(&body, is_json) { None => return json_error(StatusCode::BAD_REQUEST, None, "Body parameters missing"), Some(ai) => ai, }; let auth = match domain.auth.as_ref().and_then(|a| self.inner.config.auth.get(a)) { None => return json_error(StatusCode::NOT_FOUND, None, "Authentication not enabled"), Some(a) => a, }; if let Some(ref lua_func) = auth.lua_function { let lauth = lua::AuthInfo { username: authinfo.username, password: authinfo.password, map: auth.map.clone(), key: auth.key.clone(), extra: authinfo.extra, }; let res = match lua::lua_auth(lua_func, &domain.name, lauth) { Ok((serde_json::Value::Null, status)) => { if status == 0 { json_error( StatusCode::FORBIDDEN, Some(StatusCode::UNAUTHORIZED), "Password incorrect", ) } else { json_error( StatusCode::from_u16(status).unwrap(), Some(StatusCode::UNAUTHORIZED), "Password incorrect", ) } }, Ok((val, status)) => { if status == 0 { json_result(StatusCode::OK, &val) } else { json_result_raw(StatusCode::from_u16(status).unwrap(), &val) } }, Err(_) => json_error(StatusCode::INTERNAL_SERVER_ERROR, None, "Internal server error"), }; return res; } let auth_map = auth.map.as_ref().unwrap(); let auth_key = auth.key.as_ref().unwrap(); match self.auth_map(domain, auth_map, auth_key, &authinfo.username, &authinfo.password) { Ok(true) => json_result(StatusCode::OK, &json!({})), Ok(false) => { json_error( StatusCode::FORBIDDEN, Some(StatusCode::UNAUTHORIZED), "Password incorrect", ) }, Err(WnError::MapNotFound) => { return json_error(StatusCode::NOT_FOUND, None, "Associated auth map not found"); }, Err(_) => json_error(StatusCode::INTERNAL_SERVER_ERROR, None, "Internal server error"), } } fn auth_map( &self, dom: &config::Domain, map: &str, key: &str, username: &str, passwd: &str, ) -> Result<bool, WnError> { let (map, keyname) = match self.inner.config.find_map(map, key) { None => { warn!("auth_map: map {} with key {} not found", map, key); return Err(WnError::MapNotFound); }, Some(m) => m, }; let res = match map.map_type { MapType::Gdbm => self.lookup_gdbm_map(dom, map, username), MapType::Json => self.lookup_json_map(dom, map, keyname, username), _ => { warn!("auth_map: map {}: unsupported {:?}", map.name, map.map_type); return Err(WnError::DbOther); }, }; let json = match res { Ok(jv) => jv, Err(WnError::KeyNotFound) => return Ok(false), Err(e) => return Err(e), }; let res = match json.get("passwd").map(|p| p.as_str()).unwrap_or(None) { None => false, Some(hash) => check_unix_password(passwd, hash), }; Ok(res) } pub fn lua_map_auth( &self, domain: &str, map: &str, key: &str, username: &str, passwd: &str, ) -> Result<bool, WnError> { let domain = match self.inner.config.find_domain(&domain) { None => return Err(WnError::DbOther), Some(d) => d, }; self.auth_map(domain, map, key, username, passwd) } pub fn handle_map(&self, domain: &str, map: &str, query: &HashMap<String, String>) -> HttpResponse { let domain = match self.inner.config.find_domain(&domain) { None => return json_error(StatusCode::BAD_REQUEST, None, "Domain not found"), Some(d) => d, }; let (keyname, keyval) = match query.iter().next() { None => return json_error(StatusCode::BAD_REQUEST, None, "Query params missing"), Some(kv) => kv, }; let (map, keyname) = match self.inner.config.find_allowed_map(&domain, map, keyname) { None => return json_error(StatusCode::NOT_FOUND, None, "No such map"), Some(m) => m, }; let res = match map.map_type { MapType::Gdbm => self.lookup_gdbm_map(domain, map, keyval), MapType::Json => self.lookup_json_map(domain, map, keyname, keyval), MapType::Lua => self.lookup_lua_map(domain, map, keyname, keyval), MapType::None => unreachable!(), }; match res { Err(WnError::KeyNotFound) => json_error(StatusCode::NOT_FOUND, None, "No such key in map"), Err(WnError::MapNotFound) => json_error(StatusCode::NOT_FOUND, None, "No such map"), Err(WnError::UnknownFormat) => json_error(StatusCode::NOT_FOUND, None, "Unknown map format"), Err(WnError::SerializeJson(_)) => json_error(StatusCode::NOT_FOUND, None, "Serialize error"), Err(_) => json_error(StatusCode::INTERNAL_SERVER_ERROR, None, "Error reading database"), Ok(r) => json_result(StatusCode::OK, &r), } } pub fn lua_map_lookup( &self, domain: &str, mapname: &str, keyname: &str, keyval: &str, ) -> Result<serde_json::Value, WnError> { let domain = match self.inner.config.find_domain(&domain) { None => return Err(WnError::DbOther), Some(d) => d, }; let (map, keyname) = match self.inner.config.find_map(mapname, keyname) { None => return Err(WnError::MapNotFound), Some(m) => m, }; let res = match map.map_type { MapType::Gdbm => self.lookup_gdbm_map(domain, map, keyval), MapType::Json => self.lookup_json_map(domain, map, keyname, keyval), _ => Err(WnError::Other), }; match res { Err(WnError::KeyNotFound) => Ok(json!(null)), x => x, } } fn lookup_gdbm_map( &self, dom: &config::Domain, map: &config::Map, keyval: &str, ) -> Result<serde_json::Value, WnError> { let format = match map.map_format { None => return Err(WnError::UnknownFormat), Some(ref s) => s, }; let path = format!("{}/{}", dom.db_dir, map.map_file.as_ref().unwrap()); let line = db::gdbm_lookup(&path, keyval)?; format::line_to_json(&line, format, &map.map_output) } fn lookup_json_map( &self, dom: &config::Domain, map: &config::Map, keyname: &str, keyval: &str, ) -> Result<serde_json::Value, WnError> { let path = format!("{}/{}", dom.db_dir, map.map_file.as_ref().unwrap()); db::json_lookup(path, keyname, keyval) } fn lookup_lua_map( &self, dom: &config::Domain, map: &config::Map, keyname: &str, keyval: &str, ) -> Result<serde_json::Value, WnError> { match lua::lua_map(&map.lua_function.as_ref().unwrap(), &dom.name, keyname, keyval) { Ok(serde_json::Value::Null) => Err(WnError::KeyNotFound), Ok(m) => Ok(m), Err(_) => Err(WnError::Other), } } }
pub fn handle_info(&self, domain: &str) -> HttpResponse { let domain = match self.inner.config.find_domain(domain) { None => return json_error(StatusCode::BAD_REQUEST, None, "Domain not found"), Some(d) => d, }; let mut maps = HashMap::new(); for mapname in &domain.maps { let mut map_keys = Vec::new(); let mapvec = match self.inner.config.map_.get(mapname) { Some(i) => i, None => continue, }; for m in mapvec { let keys = m.key.iter().chain(m.keys.iter()).chain(m.key_alias.keys()); map_keys.extend(keys); } let mut hm = HashMap::new(); hm.insert("keys", map_keys); maps.insert(mapname, hm); } #[derive(Serialize)] struct Reply<T> { maps: T, } let r = Reply { maps: maps }; let reply = serde_json::to_value(r).unwrap(); json_result(StatusCode::OK, &reply) }
function_block-full_function
[ { "content": "// Read the TOML config into a config::Condig struct.\n\npub fn read(toml_file: impl AsRef<Path>) -> io::Result<Config> {\n\n let buffer = std::fs::read_to_string(&toml_file)?;\n\n\n\n // initial parse.\n\n let mut config: Config = match toml::from_str(&buffer) {\n\n Ok(v) => Ok(v)...
Rust
src/api.rs
IslandUsurper/mailchimp-rs
cfa26fffbe925df6b0878ea55bf4284097cc699f
use crate::internal::api::Api; use crate::internal::error_type::MailchimpErrorType; use crate::internal::request::MailchimpRequest; use crate::types::Ping; use serde::de::DeserializeOwned; use serde::ser::Serialize; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug, Clone)] pub struct MailchimpApi { i_api: Box<Api<MailchimpRequest>>, } impl MailchimpApi { pub fn new<'a>(api_key: &'a str) -> Self { let mut creds = api_key.split('-').collect::<Vec<&str>>(); if creds.len() <= 1 { creds.push("usX"); } MailchimpApi { i_api: Box::new(Api::<MailchimpRequest>::new( creds[1], creds[0], Box::new(MailchimpRequest::new()), )), } } pub fn domain(&self) -> String { self.i_api.domain() } pub fn version(&self) -> String { self.i_api.api_version() } pub fn post<'a, T, P>(&self, endpoint: &'a str, payload: P) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, P: Serialize, { self.i_api.post_edge::<T, P>(endpoint, payload) } pub fn patch<'a, T, P>(&self, endpoint: &'a str, payload: P) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, P: Serialize, { self.i_api.patch_edge::<T, P>(endpoint, payload) } pub fn put<'a, T, P>(&self, endpoint: &'a str, payload: P) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, P: Serialize, { self.i_api.put_edge::<T, P>(endpoint, payload) } pub fn get<'a, T>( &self, endpoint: &'a str, payload: HashMap<String, String>, ) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, { self.i_api.get_edge(endpoint, payload) } pub fn delete<'a, T>( &self, endpoint: &'a str, payload: HashMap<String, String>, ) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, { self.i_api.delete_edge(endpoint, payload) } pub fn ping(&self) -> Result<Ping, MailchimpErrorType> { self.get::<Ping>("ping", HashMap::new()) } } impl Default for MailchimpApi { fn default() -> Self { MailchimpApi { i_api: Box::new(Api::<MailchimpRequest>::new( "", "", Box::new(MailchimpRequest::new()), )), } } } pub trait MailchimpApiUpdate { /** * Update API */ fn set_api(&mut self, api: Rc<MailchimpApi>); }
use crate::internal::api::Api; use crate::internal::error_type::MailchimpErrorType; use crate::internal::request::MailchimpRequest; use crate::types::Ping; use serde::de::DeserializeOwned; use serde::ser::Serialize; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug, Clone)] pub struct MailchimpApi { i_api: Box<Api<MailchimpRequest>>, } impl MailchimpApi { pub fn new<'a>(api_key: &'a str) -> Self { let mut creds = api_key.split('-').collect::<Vec<&str>>(); if creds.len() <= 1 { creds.push("usX"); } MailchimpApi { i_api: Box::new(Api::<MailchimpRequest>::new( creds[1], creds[0], Box::new(MailchimpRequest::new()), )), } } pub fn domain(&self) -> String { self.i_api.domain() } pub fn version(&self) -> String { self.i_api.api_version() } pub fn post<'a, T, P>(&self, endpoint: &'a str, payload: P) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, P: Serialize, { self.i_api.post_edge::<T, P>(endpoint, payload) } pub fn patch<'a, T, P>(&self, endpoint: &'a str, payload: P) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, P: Serialize, { self.i_api.patch_edge::<T, P>(endpoint, payload) } pub fn put<'a, T, P>(&self, endpoint: &'a str, payload: P) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, P: Serialize, { self.i_api.put_edge::<T, P>(endpoint, payload) } pub fn get<'a, T>( &self, endpoint: &'a str, payload: HashMap<String, String>, ) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, { self.i_api.get_edge(endpoint, payload) } pub fn delete<'a, T>( &self, endpoint: &'a str, payload: HashMap<String, String>, ) -> Result<T, MailchimpErrorType> where T: DeserializeOwned, { self.i_api.delete_edge(endpoint, payload) } pub fn ping(&self) -> Result<Ping, MailchimpErrorType> { self.get::<Ping>("ping", HashMap::new(
MailchimpRequest>::new( "", "", Box::new(MailchimpRequest::new()), )), } } } pub trait MailchimpApiUpdate { /** * Update API */ fn set_api(&mut self, api: Rc<MailchimpApi>); }
)) } } impl Default for MailchimpApi { fn default() -> Self { MailchimpApi { i_api: Box::new(Api::<
random
[ { "content": "///\n\n/// ====================================================================\n\n///\n\n///\n\nfn connect_mqtt<'a>(host: &'a str, user_name: &'a str, password: &'a str) -> mqtt::Client {\n\n let endpoint = String::from(\"tcp://\") + host;\n\n let create_options = mqtt::CreateOptionsBuilder...
Rust
grader/src/submission/mod.rs
programming-in-th/rusty-grader
7538071915566577692cafc36ba7dadcc983654c
use crate::errors::{GraderError, GraderResult}; use crate::instance; use crate::instance::{Instance, RunVerdict}; use crate::submission::result::*; use crate::utils::{get_base_path, get_code_extension, get_env, get_message}; use manifest::Manifest; use std::{fs, io::Write, path::Path, path::PathBuf, process::Command}; pub mod manifest; pub mod result; #[cfg(test)] mod tests; #[derive(Debug)] pub enum SubmissionStatus { Initialized, Compiling, Compiled, CompilationError(String), Running(u64), Done(SubmissionResult), } impl Default for SubmissionStatus { fn default() -> Self { SubmissionStatus::Initialized } } #[derive(Debug)] pub enum SubmissionMessage { Status(SubmissionStatus), RunResult(RunResult), GroupResult(GroupResult), } impl Default for SubmissionMessage { fn default() -> Self { SubmissionMessage::Status(SubmissionStatus::Initialized) } } pub trait DisplayFnT: FnMut(SubmissionMessage) {} impl<F> DisplayFnT for F where F: FnMut(SubmissionMessage) {} impl std::fmt::Debug for dyn DisplayFnT { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "DisplayFunction") } } pub type DisplayFn<'a> = Box<dyn DisplayFnT + 'a>; #[derive(Default)] pub struct Submission<'a> { pub task_id: String, pub submission_id: String, pub language: String, pub code_path: Vec<PathBuf>, pub task_manifest: Manifest, pub tmp_path: PathBuf, pub task_path: PathBuf, pub bin_path: PathBuf, pub message_handler: Option<DisplayFn<'a>>, } impl<'a> std::fmt::Display for Submission<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "Submission {} {} {} {:?} {:?} {:?} {:?} {:?}", self.task_id, self.submission_id, self.language, self.code_path, self.task_manifest, self.tmp_path, self.task_path, self.bin_path ) } } impl<'a> Submission<'a> { pub fn from<T>( task_id: T, submission_id: T, language: T, code: &[String], message_handler: Option<DisplayFn<'a>>, ) -> GraderResult<Self> where T: Into<String>, { let task_id = task_id.into(); let submission_id = submission_id.into(); let language = language.into(); let tmp_path = PathBuf::from(get_env("TEMPORARY_PATH")).join(&submission_id); fs::create_dir(&tmp_path)?; let extension = get_code_extension(&language); let task_path = get_base_path().join("tasks").join(&task_id); if task_path.join("compile_files").is_dir() { let entries = fs::read_dir(task_path.join("compile_files"))?; for entry in entries { let path = entry?; fs::copy(&path.path(), tmp_path.join(&path.file_name()))?; } } Ok(Submission { task_id, submission_id, language, code_path: code .iter() .enumerate() .map(|(idx, val)| { let code_path = tmp_path.join(format!("code_{}.{}", &idx.to_string(), &extension)); let mut file = fs::File::create(&code_path)?; file.write_all(val.as_bytes())?; Ok(code_path) }) .collect::<GraderResult<Vec<_>>>()?, task_manifest: Manifest::from(task_path.join("manifest.yaml"))?, tmp_path, task_path, bin_path: PathBuf::new(), message_handler, }) } pub fn compile(&mut self) -> GraderResult<()> { if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::Status(SubmissionStatus::Compiling)) } let compiler_path = get_base_path() .join("scripts") .join("compile_scripts") .join(&self.language); let mut args = vec![&self.tmp_path]; self.code_path.iter().for_each(|path| { args.push(&path); }); let mut tmp_compile_files = vec![]; if let Some(compile_files) = &self.task_manifest.compile_files { for compile_file in compile_files .get(&self.language) .ok_or(GraderError::invalid_index())? { tmp_compile_files.push(self.tmp_path.join(&compile_file)); } } tmp_compile_files.iter().for_each(|path| { args.push(&path); }); let compile_output = Command::new(compiler_path).args(args).output()?; let compile_output_args = String::from_utf8(compile_output.stdout.clone())? .lines() .map(|s| s.to_string()) .collect::<Vec<String>>(); let return_code: i32 = compile_output_args .get(0) .ok_or(GraderError::invalid_index())? .parse()?; self.bin_path = PathBuf::from( compile_output_args .get(1) .ok_or(GraderError::invalid_index())?, ); if let Some(message_handler) = &mut self.message_handler { match return_code { 0 => message_handler(SubmissionMessage::Status(SubmissionStatus::Compiled)), _ => message_handler(SubmissionMessage::Status( SubmissionStatus::CompilationError(String::from_utf8(compile_output.stdout)?), )), } } Ok(()) } fn run_each(&mut self, checker: &Path, runner: &Path, index: u64) -> GraderResult<RunResult> { if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::Status(SubmissionStatus::Running(index))) } let input_path = self .task_path .join("testcases") .join(format!("{}.in", index)); let output_path = self.tmp_path.join(format!("output_{}", index)); let sol_path = self .task_path .join("testcases") .join(format!("{}.sol", index)); let mut instance = instance! { time_limit: self.task_manifest.time_limit.ok_or(GraderError::invalid_value())?, memory_limit: self.task_manifest.memory_limit.ok_or(GraderError::invalid_value())? * 1000, bin_path: self.bin_path.clone(), input_path: input_path.clone(), output_path: output_path.clone(), runner_path: runner.to_path_buf() }; instance.init()?; let instance_result = instance.run()?; let mut run_result = RunResult::from( self.submission_id.to_owned(), index, instance_result.time_usage, instance_result.memory_usage, ); run_result.status = match instance_result.status { RunVerdict::VerdictOK => { let args = vec![&input_path, &output_path, &sol_path]; let checker_result = Command::new(&checker).args(args).output()?; let checker_output = String::from_utf8(checker_result.stdout)? .trim_end_matches('\n') .lines() .map(|s| s.to_string()) .collect::<Vec<String>>(); run_result.score = checker_output .get(1) .ok_or(GraderError::invalid_index())? .parse()?; run_result.message = checker_output .get(2) .map_or(String::new(), |v| v.to_owned()); checker_output .get(0) .ok_or(GraderError::invalid_index())? .as_str() .to_owned() } RunVerdict::VerdictTLE => String::from("Time Limit Exceeded"), RunVerdict::VerdictMLE => String::from("Memory Limit Exceeded"), RunVerdict::VerdictRE => String::from("Runtime Error"), RunVerdict::VerdictSG => String::from("Signal Error"), _ => String::from("Judge Error"), }; if run_result.message.is_empty() { run_result.message = get_message(&run_result.status); } if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::RunResult(run_result.clone())) } Ok(run_result) } pub fn run(&mut self) -> GraderResult<SubmissionResult> { let checker = self.task_manifest .checker .as_ref() .map_or(self.task_path.join("checker"), |file| { get_base_path() .join("scripts") .join("checker_scripts") .join(&file) }); let grouper = self.task_manifest .grouper .as_ref() .map_or(self.task_path.join("grouper"), |file| { get_base_path() .join("scripts") .join("grouper_scripts") .join(&file) }); let runner = get_base_path() .join("scripts") .join("runner_scripts") .join(&self.language); let mut last_test = 1; let mut total_score: f64 = 0.0; let mut total_full_score: u64 = 0; let mut group_results = Vec::new(); for (group_index, (full_score, tests)) in self.task_manifest.groups.clone().iter().enumerate() { total_full_score += full_score; let mut skip = false; let mut args = vec![full_score.to_string()]; let mut group_result = GroupResult::from( *full_score, self.submission_id.to_owned(), (group_index + 1) as u64, ); for index in last_test..(last_test + tests) { let run_result = if skip { RunResult::from(self.submission_id.to_owned(), index, 0.0, 0) } else { self.run_each(&checker, &runner, index)? }; args.push(run_result.score.to_string()); skip = &run_result.status != "Correct" && &run_result.status != "Partially Correct"; group_result.run_result.push(run_result); } if !skip { let grouper_result = Command::new(&grouper).args(args).output()?; group_result.score = String::from_utf8(grouper_result.stdout)? .trim_end_matches('\n') .parse()?; total_score += group_result.score; } if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::GroupResult(group_result.clone())); } group_results.push(group_result); last_test += tests; } let submission_result = SubmissionResult { score: total_score, full_score: total_full_score, submission_id: self.submission_id.to_owned(), group_result: group_results, }; if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::Status(SubmissionStatus::Done( submission_result.clone(), ))); } Ok(submission_result) } } impl<'a> Drop for Submission<'a> { fn drop(&mut self) { fs::remove_dir_all(&self.tmp_path); } }
use crate::errors::{GraderError, GraderResult}; use crate::instance; use crate::instance::{Instance, RunVerdict}; use crate::submission::result::*; use crate::utils::{get_base_path, get_code_extension, get_env, get_message}; use manifest::Manifest; use std::{fs, io::Write, path::Path, path::PathBuf, process::Command}; pub mod manifest; pub mod result; #[cfg(test)] mod tests; #[derive(Debug)] pub enum SubmissionStatus { Initialized, Compiling, Compiled, CompilationError(String), Running(u64), Done(SubmissionResult), } impl Default for SubmissionStatus { fn default() -> Self { SubmissionStatus::Initialized } } #[derive(Debug)] pub enum SubmissionMessage { Status(SubmissionStatus), RunResult(RunResult), GroupResult(GroupResult), } impl Default for SubmissionMessage { fn default() -> Self { SubmissionMessage::Status(SubmissionStatus::Initialized) } } pub trait DisplayFnT: FnMut(SubmissionMessage) {} impl<F> DisplayFnT for F where F: FnMut(SubmissionMessage) {} impl std::fmt::Debug for dyn DisplayFnT { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "DisplayFunction") } } pub type DisplayFn<'a> = Box<dyn DisplayFnT + 'a>; #[derive(Default)] pub struct Submission<'a> { pub task_id: String, pub submission_id: String, pub language: String, pub code_path: Vec<PathBuf>, pub task_manifest: Manifest, pub tmp_path: PathBuf, pub task_path: PathBuf, pub bin_path: PathBuf, pub message_handler: Option<DisplayFn<'a>>, } impl<'a> std::fmt::Display for Submission<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "Submission {} {} {} {:?} {:?} {:?} {:?} {:?}", self.task_id, self.submission_id, self.language, self.code_path, self.task_manifest, self.tmp_path, self.task_path, self.bin_path ) } } impl<'a> Submission<'a> { pub fn from<T>( task_id: T, submission_id: T, language: T, code: &[String], message_handler: Option<DisplayFn<'a>>, ) -> GraderResult<Self> where T: Into<String>, { let task_id = task_id.into(); let submission_id = submission_id.into(); let language = language.into(); let tmp_path = PathBuf::from(get_env("TEMPORARY_PATH")).join(&submission_id); fs::create_dir(&tmp_path)?; let extension = get_code_extension(&language); let task_path = get_base_path().join("tasks").join(&task_id); if task_path.join("compile_files").is_dir() { let entries = fs::read_dir(task_path.join("compile_files"))?; for entry in entries { let path = entry?; fs::copy(&path.path(), tmp_path.join(&path.file_name()))?; } } Ok(Submission { task_id, submission_id, language, code_path: code .iter() .enumerate() .map(|(idx, val)| { let code_path = tmp_path.join(format!("code_{}.{}", &idx.to_string(), &extension)); let mut file = fs::File::create(&code_path)?; file.write_all(val.as_bytes())?; Ok(code_path) }) .collect::<GraderResult<Vec<_>>>()?, task_manifest: Manifest::from(task_path.join("manifest.yaml"))?, tmp_path, task_path, bin_path: PathBuf::new(), message_handler, }) } pub fn compile(&mut self) -> GraderResult<()> { if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::Status(SubmissionStatus::Compiling)) } let compiler_path = get_base_path() .join("scripts") .join("compile_scripts") .join(&self.language); let mut args = vec![&self.tmp_path]; self.code_path.iter().for_each(|path| { args.push(&path); }); let mut tmp_compile_files = vec![]; if let Some(compile_files) = &self.task_manifest.compile_files { for compile_file in compile_files .get(&self.language) .ok_or(GraderError::invalid_index())? { tmp_compile_files.push(self.tmp_path.join(&compile_file)); } } tmp_compile_files.iter().for_each(|path| { args.push(&path); }); let compile_output = Command::new(compiler_path).args(args).output()?; let compile_output_args = String::from_utf8(compile_output.stdout.clone())? .lines() .map(|s| s.to_string()) .collect::<Vec<String>>(); let return_code: i32 = compile_output_args .get(0) .ok_or(GraderError::invalid_index())? .parse()?; self.bin_path = PathBuf::from( compile_output_args .get(1) .ok_or(GraderError::invalid_index())?, ); if let Some(message_handler) = &mut self.message_handler { match return_code { 0 => message_handler(SubmissionMessage::Status(SubmissionStatus::Compiled)), _ => message_handler(SubmissionMessage::Status( SubmissionStatus::CompilationError(String::from_utf8(compile_output.stdout)?), )), } } Ok(()) }
pub fn run(&mut self) -> GraderResult<SubmissionResult> { let checker = self.task_manifest .checker .as_ref() .map_or(self.task_path.join("checker"), |file| { get_base_path() .join("scripts") .join("checker_scripts") .join(&file) }); let grouper = self.task_manifest .grouper .as_ref() .map_or(self.task_path.join("grouper"), |file| { get_base_path() .join("scripts") .join("grouper_scripts") .join(&file) }); let runner = get_base_path() .join("scripts") .join("runner_scripts") .join(&self.language); let mut last_test = 1; let mut total_score: f64 = 0.0; let mut total_full_score: u64 = 0; let mut group_results = Vec::new(); for (group_index, (full_score, tests)) in self.task_manifest.groups.clone().iter().enumerate() { total_full_score += full_score; let mut skip = false; let mut args = vec![full_score.to_string()]; let mut group_result = GroupResult::from( *full_score, self.submission_id.to_owned(), (group_index + 1) as u64, ); for index in last_test..(last_test + tests) { let run_result = if skip { RunResult::from(self.submission_id.to_owned(), index, 0.0, 0) } else { self.run_each(&checker, &runner, index)? }; args.push(run_result.score.to_string()); skip = &run_result.status != "Correct" && &run_result.status != "Partially Correct"; group_result.run_result.push(run_result); } if !skip { let grouper_result = Command::new(&grouper).args(args).output()?; group_result.score = String::from_utf8(grouper_result.stdout)? .trim_end_matches('\n') .parse()?; total_score += group_result.score; } if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::GroupResult(group_result.clone())); } group_results.push(group_result); last_test += tests; } let submission_result = SubmissionResult { score: total_score, full_score: total_full_score, submission_id: self.submission_id.to_owned(), group_result: group_results, }; if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::Status(SubmissionStatus::Done( submission_result.clone(), ))); } Ok(submission_result) } } impl<'a> Drop for Submission<'a> { fn drop(&mut self) { fs::remove_dir_all(&self.tmp_path); } }
fn run_each(&mut self, checker: &Path, runner: &Path, index: u64) -> GraderResult<RunResult> { if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::Status(SubmissionStatus::Running(index))) } let input_path = self .task_path .join("testcases") .join(format!("{}.in", index)); let output_path = self.tmp_path.join(format!("output_{}", index)); let sol_path = self .task_path .join("testcases") .join(format!("{}.sol", index)); let mut instance = instance! { time_limit: self.task_manifest.time_limit.ok_or(GraderError::invalid_value())?, memory_limit: self.task_manifest.memory_limit.ok_or(GraderError::invalid_value())? * 1000, bin_path: self.bin_path.clone(), input_path: input_path.clone(), output_path: output_path.clone(), runner_path: runner.to_path_buf() }; instance.init()?; let instance_result = instance.run()?; let mut run_result = RunResult::from( self.submission_id.to_owned(), index, instance_result.time_usage, instance_result.memory_usage, ); run_result.status = match instance_result.status { RunVerdict::VerdictOK => { let args = vec![&input_path, &output_path, &sol_path]; let checker_result = Command::new(&checker).args(args).output()?; let checker_output = String::from_utf8(checker_result.stdout)? .trim_end_matches('\n') .lines() .map(|s| s.to_string()) .collect::<Vec<String>>(); run_result.score = checker_output .get(1) .ok_or(GraderError::invalid_index())? .parse()?; run_result.message = checker_output .get(2) .map_or(String::new(), |v| v.to_owned()); checker_output .get(0) .ok_or(GraderError::invalid_index())? .as_str() .to_owned() } RunVerdict::VerdictTLE => String::from("Time Limit Exceeded"), RunVerdict::VerdictMLE => String::from("Memory Limit Exceeded"), RunVerdict::VerdictRE => String::from("Runtime Error"), RunVerdict::VerdictSG => String::from("Signal Error"), _ => String::from("Judge Error"), }; if run_result.message.is_empty() { run_result.message = get_message(&run_result.status); } if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::RunResult(run_result.clone())) } Ok(run_result) }
function_block-full_function
[ { "content": "pub fn get_code_extension(language: &str) -> String {\n\n let config = load_yaml(get_base_path().join(\"scripts\").join(\"config.yaml\"));\n\n\n\n for lang in yaml_unwrap_hash(config, \"language\")\n\n .unwrap()\n\n .into_vec()\n\n .unwrap()\n\n {\n\n if Some(l...
Rust
api/swim_form_derive/src/structural/mod.rs
swimos/swim-rust
f1a2be7bb4eb8f38e6ecc19bba4a8c876016183c
use crate::structural::model::enumeration::{EnumDef, EnumModel, SegregatedEnumModel}; use crate::structural::model::record::{SegregatedStructModel, StructDef, StructModel}; use crate::structural::model::StructLike; use crate::structural::model::ValidateFrom; use crate::structural::read::DeriveStructuralReadable; use crate::structural::write::DeriveStructuralWritable; use proc_macro2::TokenStream; use quote::ToTokens; use swim_utilities::errors::Errors; use syn::{Data, DeriveInput, Generics}; pub mod model; pub mod read; pub mod write; pub fn build_derive_structural_form(input: DeriveInput) -> Result<TokenStream, Errors<syn::Error>> { match &input.data { Data::Struct(ds) => { let def = StructDef::new(&input.ident, &input, &input.attrs, ds); struct_derive_structural_form(def, &input.generics) } Data::Enum(de) => { let def = EnumDef::new(&input.ident, &input, &input.attrs, de); enum_derive_structural_form(def, &input.generics) } _ => Err(Errors::of(syn::Error::new_spanned( input, "Union types are not supported.", ))), } } pub fn build_derive_structural_writable( input: DeriveInput, ) -> Result<TokenStream, Errors<syn::Error>> { match &input.data { Data::Struct(ds) => { let def = StructDef::new(&input.ident, &input, &input.attrs, ds); struct_derive_structural_writable(def, &input.generics) } Data::Enum(de) => { let def = EnumDef::new(&input.ident, &input, &input.attrs, de); enum_derive_structural_writable(def, &input.generics) } _ => Err(Errors::of(syn::Error::new_spanned( input, "Union types are not supported.", ))), } } fn struct_derive_structural_writable<'a, Flds: StructLike>( input: StructDef<'a, Flds>, generics: &'a Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = StructModel::validate(input).into_result()?; let segregated = SegregatedStructModel::from(&model); let derive = DeriveStructuralWritable(segregated, generics); Ok(derive.into_token_stream()) } fn struct_derive_structural_form<'a, Flds: StructLike>( input: StructDef<'a, Flds>, generics: &'a Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = StructModel::validate(input).into_result()?; let segregated = SegregatedStructModel::from(&model); let derive_writable = DeriveStructuralWritable(segregated.clone(), generics); let derive_readable = DeriveStructuralReadable(segregated, generics); Ok(quote! { #derive_writable #derive_readable }) } fn enum_derive_structural_form<'a>( input: EnumDef<'a>, generics: &'a Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = EnumModel::validate(input).into_result()?; let segregated = SegregatedEnumModel::from(&model); let derive_writable = DeriveStructuralWritable(segregated.clone(), generics); let derive_readable = DeriveStructuralReadable(segregated, generics); Ok(quote! { #derive_writable #derive_readable }) } fn enum_derive_structural_writable<'a>( input: EnumDef<'a>, generics: &'a Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = EnumModel::validate(input).into_result()?; let segregated = SegregatedEnumModel::from(&model); let derive = DeriveStructuralWritable(segregated, generics); Ok(derive.into_token_stream()) } pub fn build_derive_structural_readable( input: DeriveInput, ) -> Result<TokenStream, Errors<syn::Error>> { match &input.data { Data::Struct(ds) => { let def = StructDef::new(&input.ident, &input, &input.attrs, ds); struct_derive_structural_readable(def, &input.generics) } Data::Enum(de) => { let def = EnumDef::new(&input.ident, &input, &input.attrs, de); enum_derive_structural_readable(def, &input.generics) } _ => Err(Errors::of(syn::Error::new_spanned( input, "Union types are not supported.", ))), } } fn struct_derive_structural_readable<Flds: StructLike>( input: StructDef<'_, Flds>, generics: &Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = StructModel::validate(input).into_result()?; let segregated = SegregatedStructModel::from(&model); let derive = DeriveStructuralReadable(segregated, generics); Ok(derive.into_token_stream()) } fn enum_derive_structural_readable( input: EnumDef<'_>, generics: &Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = EnumModel::validate(input).into_result()?; let segregated = SegregatedEnumModel::from(&model); let derive = DeriveStructuralReadable(segregated, generics); Ok(derive.into_token_stream()) } fn add_bounds(original: &Generics, generics: &mut Generics, bound: syn::TraitBound) { let bounds = original.type_params().map(|param| { let id = &param.ident; parse_quote!(#id: #bound) }); let where_clause = generics.make_where_clause(); for bound in bounds.into_iter() { where_clause.predicates.push(bound); } }
use crate::structural::model::enumeration::{EnumDef, EnumModel, SegregatedEnumModel}; use crate::structural::model::record::{SegregatedStructModel, StructDef, StructModel}; use crate::structural::model::StructLike; use crate::structural::model::ValidateFrom; use crate::structural::read::DeriveStructuralReadable; use crate::structural::write::DeriveStructuralWritable; use proc_macro2::TokenStream; use quote::ToTokens; use swim_utilities::errors::Errors; use syn::{Data, DeriveInput, Generics}; pub mod model; pub mod read; pub mod write; pub fn build_derive_structural_form(input: DeriveInput) -> Result<TokenStream, Errors<syn::Error>> { match &input.data { Data::Struct(ds) => { let def = StructDef::new(&input.ident, &input, &input.attrs, ds); struct_derive_structural_form(def, &input.generics) } Data::Enum(de) => { let def = EnumDef::new(&input.ident, &input, &input.attrs, de); enum_derive_structural_form(def, &input.generics) } _ => Err(Errors::of(syn::Error::new_spanned( input, "Union types are not supported.", ))), } } pub fn build_derive_structural_writable( input: DeriveInput, ) -> Result<TokenStream, Errors<syn::Error>> { match &input.data { Data::Struct(ds) => { let def = StructDef::new(&input.ident, &input, &input.attrs, ds); struct_derive_structural_writable(def, &input.generics) } Data::Enum(de) => { let def = EnumDef::new(&input.ident, &input, &input.attrs, de); enum_derive_structural_writable(def, &input.generics) } _ => Err(Errors::of(syn::Error::new_spanned( input, "Union types are not supported.", ))), } } fn struct_derive_structural_writable<'a, Flds: StructLike>( input: StructDef<'a, Flds>, generics: &'a Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = StructModel::validate(input).into_result()?; let segregated = SegregatedStructModel::from(&model); let derive = DeriveStructuralWritable(segregated, generics); Ok(derive.into_token_stream()) } fn struct_derive_structural_form<'a, Flds: StructLike>( input: StructDef<'a, Flds>, generics: &'a Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = StructModel::validate(input).into_result()?; let segregated = SegregatedStructModel::from(&model); let derive_writable = DeriveStructuralWritable(segregated.clone(), generics); let derive_readable = DeriveStructuralReadable(segregated, generics); Ok(quote! { #derive_writable #derive_readable }) } fn enum_derive_structural_form<'a>( input: EnumDef<'a>, generics: &'a Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = EnumModel::validate(input).into_result()?; let segregated = SegregatedEnumModel::from(&model); let derive_writable = DeriveStructuralWritable(segregated.clone(), generics); let derive_readable = DeriveStructuralReadable(segregated, generics); Ok(quote! { #derive_writable #derive_readable }) } fn enum_derive_structural_writable<'a>( input: EnumDef<'a>, generics: &'a Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = EnumModel::validate(input).into_result()?; let segregated = SegregatedEnumModel::from(&model); let derive = DeriveStructuralWritable(segregated, generics); Ok(derive.into_token_stream()) } pub fn build_derive_structural_readable( input: DeriveInput, ) -> Result<TokenStream, Errors<syn::Error>> { match &input.data { Data::Struct(ds) => { let def = StructDef::new(&input.ident, &input, &input.attrs, ds); struct_derive_structural_readable(def, &input.generics) } Data::Enum(de) => { let def = EnumDef::new(&input.ident, &input, &input.attrs, de); enum_derive_structural_readable(def, &input.generics) } _ => Err(Errors::of(syn::Error::new_spanned( input, "Union types are not supported.", ))), } } fn struct_derive_structural_readable<Flds: StructLike>( input: StructDef<'_, Flds>, generics: &Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = StructModel:
nerics, generics: &mut Generics, bound: syn::TraitBound) { let bounds = original.type_params().map(|param| { let id = &param.ident; parse_quote!(#id: #bound) }); let where_clause = generics.make_where_clause(); for bound in bounds.into_iter() { where_clause.predicates.push(bound); } }
:validate(input).into_result()?; let segregated = SegregatedStructModel::from(&model); let derive = DeriveStructuralReadable(segregated, generics); Ok(derive.into_token_stream()) } fn enum_derive_structural_readable( input: EnumDef<'_>, generics: &Generics, ) -> Result<TokenStream, Errors<syn::Error>> { let model = EnumModel::validate(input).into_result()?; let segregated = SegregatedEnumModel::from(&model); let derive = DeriveStructuralReadable(segregated, generics); Ok(derive.into_token_stream()) } fn add_bounds(original: &Ge
random
[ { "content": "fn recognize_item(input: ReadEvent<'_>) -> ItemEvent {\n\n match input {\n\n ReadEvent::Extant => ItemEvent::Primitive(Value::Extant),\n\n ReadEvent::Number(NumericValue::Int(n)) => {\n\n ItemEvent::Primitive(if let Ok(m) = i32::try_from(n) {\n\n Value::I...
Rust
src/sys/component_manager/src/vmex.rs
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
use { crate::{ capability::*, model::{error::*, hooks::*}, }, cm_rust::CapabilityPath, failure::Error, fidl::endpoints::ServerEnd, fidl_fuchsia_boot as fboot, fidl_fuchsia_security_resource as fsec, fuchsia_async as fasync, fuchsia_component::client::connect_to_service, fuchsia_zircon::{self as zx, HandleBased}, futures::{future::BoxFuture, prelude::*}, lazy_static::lazy_static, log::warn, std::{convert::TryInto, sync::Arc}, }; lazy_static! { pub static ref VMEX_CAPABILITY_PATH: CapabilityPath = "/svc/fuchsia.process.Vmex".try_into().unwrap(); } pub struct VmexService { inner: Arc<VmexServiceInner>, } impl VmexService { pub fn new() -> Self { Self { inner: Arc::new(VmexServiceInner::new()) } } pub fn hooks(&self) -> Vec<HookRegistration> { vec![HookRegistration { event_type: EventType::RouteBuiltinCapability, callback: self.inner.clone(), }] } pub async fn serve(mut stream: fsec::VmexRequestStream) -> Result<(), Error> { let root_resource_provider = connect_to_service::<fboot::RootResourceMarker>()?; let root_resource = root_resource_provider.get().await?; while let Some(fsec::VmexRequest::Get { responder }) = stream.try_next().await? { let vmex_handle = root_resource.create_child(zx::ResourceKind::VMEX, None, 0, 0, b"vmex")?; let restricted_vmex_handle = vmex_handle.replace_handle( zx::Rights::TRANSFER | zx::Rights::DUPLICATE | zx::Rights::INSPECT, )?; responder.send(zx::Resource::from(restricted_vmex_handle))?; } Ok(()) } } struct VmexServiceInner; impl VmexServiceInner { pub fn new() -> Self { Self {} } async fn on_route_builtin_capability_async<'a>( self: Arc<Self>, capability: &'a ComponentManagerCapability, capability_provider: Option<Box<dyn ComponentManagerCapabilityProvider>>, ) -> Result<Option<Box<dyn ComponentManagerCapabilityProvider>>, ModelError> { match capability { ComponentManagerCapability::LegacyService(capability_path) if *capability_path == *VMEX_CAPABILITY_PATH => { Ok(Some(Box::new(VmexCapabilityProvider::new()) as Box<dyn ComponentManagerCapabilityProvider>)) } _ => Ok(capability_provider), } } } impl Hook for VmexServiceInner { fn on<'a>(self: Arc<Self>, event: &'a Event) -> BoxFuture<'a, Result<(), ModelError>> { Box::pin(async move { match event { Event::RouteBuiltinCapability { realm: _, capability, capability_provider } => { let mut capability_provider = capability_provider.lock().await; *capability_provider = self .on_route_builtin_capability_async(capability, capability_provider.take()) .await?; } _ => {} }; Ok(()) }) } } struct VmexCapabilityProvider; impl VmexCapabilityProvider { pub fn new() -> Self { Self {} } } impl ComponentManagerCapabilityProvider for VmexCapabilityProvider { fn open( &self, _flags: u32, _open_mode: u32, _relative_path: String, server_end: zx::Channel, ) -> BoxFuture<Result<(), ModelError>> { let server_end = ServerEnd::<fsec::VmexMarker>::new(server_end); let stream: fsec::VmexRequestStream = server_end.into_stream().unwrap(); fasync::spawn(async move { let result = VmexService::serve(stream).await; if let Err(e) = result { warn!("VmexService.open failed: {}", e); } }); Box::pin(async { Ok(()) }) } } #[cfg(test)] mod tests { use { super::*, crate::model::{Realm, ResolverRegistry}, fidl::endpoints::ClientEnd, fuchsia_async as fasync, fuchsia_zircon::AsHandleRef, fuchsia_zircon_sys as sys, futures::lock::Mutex, }; fn root_resource_available() -> bool { let bin = std::env::args().next(); match bin.as_ref().map(String::as_ref) { Some("/pkg/test/component_manager_tests") => false, Some("/pkg/test/component_manager_boot_env_tests") => true, _ => panic!("Unexpected test binary name {:?}", bin), } } fn serve_vmex() -> Result<fsec::VmexProxy, Error> { let (proxy, stream) = fidl::endpoints::create_proxy_and_stream::<fsec::VmexMarker>()?; fasync::spawn_local( VmexService::serve(stream) .unwrap_or_else(|e| panic!("Error while serving vmex service: {}", e)), ); Ok(proxy) } #[fasync::run_singlethreaded(test)] async fn fail_with_no_root_resource() -> Result<(), Error> { if root_resource_available() { return Ok(()); } let (_, stream) = fidl::endpoints::create_proxy_and_stream::<fsec::VmexMarker>()?; assert!(!VmexService::serve(stream).await.is_ok()); Ok(()) } #[fasync::run_singlethreaded(test)] async fn kind_type_is_vmex() -> Result<(), Error> { if !root_resource_available() { return Ok(()); } let vmex_provider = serve_vmex()?; let vmex_resource = vmex_provider.get().await?; let resource_info = vmex_resource.info()?; assert_eq!(resource_info.kind, zx::sys::ZX_RSRC_KIND_VMEX); assert_eq!(resource_info.base, 0); assert_eq!(resource_info.size, 0); Ok(()) } #[fasync::run_singlethreaded(test)] async fn minimal_rights_assigned() -> Result<(), Error> { if !root_resource_available() { return Ok(()); } let vmex_provider = serve_vmex()?; let vmex_resource = vmex_provider.get().await?; let resource_info = zx::Handle::from(vmex_resource).basic_info()?; assert_eq!( resource_info.rights, zx::Rights::DUPLICATE | zx::Rights::TRANSFER | zx::Rights::INSPECT ); Ok(()) } #[fasync::run_singlethreaded(test)] async fn connect_to_vmex_service() -> Result<(), Error> { if !root_resource_available() { return Ok(()); } let vmex_service = Arc::new(VmexService::new()); let hooks = Hooks::new(None); hooks.install(vmex_service.hooks()).await; let capability_provider = Arc::new(Mutex::new(None)); let capability = ComponentManagerCapability::LegacyService(VMEX_CAPABILITY_PATH.clone()); let (client, server) = zx::Channel::create()?; let realm = { let resolver = ResolverRegistry::new(); let root_component_url = "test:///root".to_string(); Arc::new(Realm::new_root_realm(resolver, root_component_url)) }; let event = Event::RouteBuiltinCapability { realm: realm.clone(), capability: capability.clone(), capability_provider: capability_provider.clone(), }; hooks.dispatch(&event).await?; let capability_provider = capability_provider.lock().await.take(); if let Some(capability_provider) = capability_provider { capability_provider.open(0, 0, String::new(), server).await?; } let vmex_client = ClientEnd::<fsec::VmexMarker>::new(client) .into_proxy() .expect("failed to create launcher proxy"); let vmex_resource = vmex_client.get().await?; assert_ne!(vmex_resource.raw_handle(), sys::ZX_HANDLE_INVALID); Ok(()) } }
use { crate::{ capability::*, model::{error::*, hooks::*}, }, cm_rust::CapabilityPath, failure::Error, fidl::endpoints::ServerEnd, fidl_fuchsia_boot as fboot, fidl_fuchsia_security_resource as fsec, fuchsia_async as fasync, fuchsia_component::client::connect_to_service, fuchsia_zircon::{self as zx, HandleBased}, futures::{future::BoxFuture, prelude::*}, lazy_static::lazy_static, log::warn, std::{convert::TryInto, sync::Arc}, }; lazy_static! { pub static ref VMEX_CAPABILITY_PATH: CapabilityPath = "/svc/fuchsia.process.Vmex".try_into().unwrap(); } pub struct VmexService { inner: Arc<VmexServiceInner>, } impl VmexService { pub fn new() -> Self { Self { inner: Arc::new(VmexServiceInner::new()) } } pub fn hooks(&self) -> Vec<HookRegistration> { vec![HookRegistration { event_type: EventType::RouteBuiltinCapability, callback: self.inner.clone(), }] } pub async fn serve(mut stream: fsec::VmexRequestStream) -> Result<(), Error> { let root_resource_provider
| panic!("Error while serving vmex service: {}", e)), ); Ok(proxy) } #[fasync::run_singlethreaded(test)] async fn fail_with_no_root_resource() -> Result<(), Error> { if root_resource_available() { return Ok(()); } let (_, stream) = fidl::endpoints::create_proxy_and_stream::<fsec::VmexMarker>()?; assert!(!VmexService::serve(stream).await.is_ok()); Ok(()) } #[fasync::run_singlethreaded(test)] async fn kind_type_is_vmex() -> Result<(), Error> { if !root_resource_available() { return Ok(()); } let vmex_provider = serve_vmex()?; let vmex_resource = vmex_provider.get().await?; let resource_info = vmex_resource.info()?; assert_eq!(resource_info.kind, zx::sys::ZX_RSRC_KIND_VMEX); assert_eq!(resource_info.base, 0); assert_eq!(resource_info.size, 0); Ok(()) } #[fasync::run_singlethreaded(test)] async fn minimal_rights_assigned() -> Result<(), Error> { if !root_resource_available() { return Ok(()); } let vmex_provider = serve_vmex()?; let vmex_resource = vmex_provider.get().await?; let resource_info = zx::Handle::from(vmex_resource).basic_info()?; assert_eq!( resource_info.rights, zx::Rights::DUPLICATE | zx::Rights::TRANSFER | zx::Rights::INSPECT ); Ok(()) } #[fasync::run_singlethreaded(test)] async fn connect_to_vmex_service() -> Result<(), Error> { if !root_resource_available() { return Ok(()); } let vmex_service = Arc::new(VmexService::new()); let hooks = Hooks::new(None); hooks.install(vmex_service.hooks()).await; let capability_provider = Arc::new(Mutex::new(None)); let capability = ComponentManagerCapability::LegacyService(VMEX_CAPABILITY_PATH.clone()); let (client, server) = zx::Channel::create()?; let realm = { let resolver = ResolverRegistry::new(); let root_component_url = "test:///root".to_string(); Arc::new(Realm::new_root_realm(resolver, root_component_url)) }; let event = Event::RouteBuiltinCapability { realm: realm.clone(), capability: capability.clone(), capability_provider: capability_provider.clone(), }; hooks.dispatch(&event).await?; let capability_provider = capability_provider.lock().await.take(); if let Some(capability_provider) = capability_provider { capability_provider.open(0, 0, String::new(), server).await?; } let vmex_client = ClientEnd::<fsec::VmexMarker>::new(client) .into_proxy() .expect("failed to create launcher proxy"); let vmex_resource = vmex_client.get().await?; assert_ne!(vmex_resource.raw_handle(), sys::ZX_HANDLE_INVALID); Ok(()) } }
= connect_to_service::<fboot::RootResourceMarker>()?; let root_resource = root_resource_provider.get().await?; while let Some(fsec::VmexRequest::Get { responder }) = stream.try_next().await? { let vmex_handle = root_resource.create_child(zx::ResourceKind::VMEX, None, 0, 0, b"vmex")?; let restricted_vmex_handle = vmex_handle.replace_handle( zx::Rights::TRANSFER | zx::Rights::DUPLICATE | zx::Rights::INSPECT, )?; responder.send(zx::Resource::from(restricted_vmex_handle))?; } Ok(()) } } struct VmexServiceInner; impl VmexServiceInner { pub fn new() -> Self { Self {} } async fn on_route_builtin_capability_async<'a>( self: Arc<Self>, capability: &'a ComponentManagerCapability, capability_provider: Option<Box<dyn ComponentManagerCapabilityProvider>>, ) -> Result<Option<Box<dyn ComponentManagerCapabilityProvider>>, ModelError> { match capability { ComponentManagerCapability::LegacyService(capability_path) if *capability_path == *VMEX_CAPABILITY_PATH => { Ok(Some(Box::new(VmexCapabilityProvider::new()) as Box<dyn ComponentManagerCapabilityProvider>)) } _ => Ok(capability_provider), } } } impl Hook for VmexServiceInner { fn on<'a>(self: Arc<Self>, event: &'a Event) -> BoxFuture<'a, Result<(), ModelError>> { Box::pin(async move { match event { Event::RouteBuiltinCapability { realm: _, capability, capability_provider } => { let mut capability_provider = capability_provider.lock().await; *capability_provider = self .on_route_builtin_capability_async(capability, capability_provider.take()) .await?; } _ => {} }; Ok(()) }) } } struct VmexCapabilityProvider; impl VmexCapabilityProvider { pub fn new() -> Self { Self {} } } impl ComponentManagerCapabilityProvider for VmexCapabilityProvider { fn open( &self, _flags: u32, _open_mode: u32, _relative_path: String, server_end: zx::Channel, ) -> BoxFuture<Result<(), ModelError>> { let server_end = ServerEnd::<fsec::VmexMarker>::new(server_end); let stream: fsec::VmexRequestStream = server_end.into_stream().unwrap(); fasync::spawn(async move { let result = VmexService::serve(stream).await; if let Err(e) = result { warn!("VmexService.open failed: {}", e); } }); Box::pin(async { Ok(()) }) } } #[cfg(test)] mod tests { use { super::*, crate::model::{Realm, ResolverRegistry}, fidl::endpoints::ClientEnd, fuchsia_async as fasync, fuchsia_zircon::AsHandleRef, fuchsia_zircon_sys as sys, futures::lock::Mutex, }; fn root_resource_available() -> bool { let bin = std::env::args().next(); match bin.as_ref().map(String::as_ref) { Some("/pkg/test/component_manager_tests") => false, Some("/pkg/test/component_manager_boot_env_tests") => true, _ => panic!("Unexpected test binary name {:?}", bin), } } fn serve_vmex() -> Result<fsec::VmexProxy, Error> { let (proxy, stream) = fidl::endpoints::create_proxy_and_stream::<fsec::VmexMarker>()?; fasync::spawn_local( VmexService::serve(stream) .unwrap_or_else(|e
random
[]
Rust
src/bin/upgrade/main.rs
thiagoarrais/cargo-edit
265ddb082c0f490a12d9dfb254195717b2ba8d51
#![warn( missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications )] #[macro_use] extern crate error_chain; use crate::errors::*; use cargo_edit::{find, get_latest_dependency, CrateName, Dependency, LocalManifest}; use failure::Fail; use std::collections::HashMap; use std::io::Write; use std::path::{Path, PathBuf}; use std::process; use structopt::StructOpt; use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor}; mod errors { error_chain! { links { CargoEditLib(::cargo_edit::Error, ::cargo_edit::ErrorKind); } foreign_links { CargoMetadata(::failure::Compat<::cargo_metadata::Error>); } } } #[derive(Debug, StructOpt)] #[structopt(bin_name = "cargo")] enum Command { #[structopt(name = "upgrade", author = "")] #[structopt( after_help = "This command differs from `cargo update`, which updates the dependency versions recorded in the local lock file (Cargo.lock). If `<dependency>`(s) are provided, only the specified dependencies will be upgraded. The version to upgrade to for each can be specified with e.g. `docopt@0.8.0` or `serde@>=0.9,<2.0`. Dev, build, and all target dependencies will also be upgraded. Only dependencies from crates.io are supported. Git/path dependencies will be ignored. All packages in the workspace will be upgraded if the `--all` flag is supplied. The `--all` flag may be supplied in the presence of a virtual manifest." )] Upgrade(Args), } #[derive(Debug, StructOpt)] struct Args { dependency: Vec<String>, #[structopt(long = "manifest-path", value_name = "path")] manifest_path: Option<PathBuf>, #[structopt(long = "all")] all: bool, #[structopt(long = "allow-prerelease")] allow_prerelease: bool, #[structopt(long = "dry-run")] dry_run: bool, } struct Manifests(Vec<(LocalManifest, cargo_metadata::Package)>); impl Manifests { fn get_all(manifest_path: &Option<PathBuf>) -> Result<Self> { let mut cmd = cargo_metadata::MetadataCommand::new(); cmd.no_deps(); if let Some(path) = manifest_path { cmd.manifest_path(path); } let result = cmd .exec() .map_err(|e| Error::from(e.compat()).chain_err(|| "Failed to get workspace metadata"))?; result .packages .into_iter() .map(|package| { Ok(( LocalManifest::try_new(Path::new(&package.manifest_path))?, package, )) }) .collect::<Result<Vec<_>>>() .map(Manifests) } fn get_local_one(manifest_path: &Option<PathBuf>) -> Result<Self> { let resolved_manifest_path: String = find(&manifest_path)?.to_string_lossy().into(); let manifest = LocalManifest::find(&manifest_path)?; let mut cmd = cargo_metadata::MetadataCommand::new(); cmd.no_deps(); if let Some(path) = manifest_path { cmd.manifest_path(path); } let result = cmd .exec() .map_err(|e| Error::from(e.compat()).chain_err(|| "Invalid manifest"))?; let packages = result.packages; let package = packages .iter() .find(|p| p.manifest_path.to_string_lossy() == resolved_manifest_path) .chain_err(|| { "Found virtual manifest, but this command requires running against an \ actual package in this workspace. Try adding `--all`." })?; Ok(Manifests(vec![(manifest, package.to_owned())])) } fn get_dependencies(&self, only_update: Vec<String>) -> Result<DesiredUpgrades> { fn is_version_dep(dependency: &cargo_metadata::Dependency) -> bool { match dependency.source { Some(ref s) => s.splitn(2, '+').next() == Some("registry"), _ => false, } } Ok(DesiredUpgrades(if only_update.is_empty() { self.0 .iter() .flat_map(|&(_, ref package)| package.dependencies.clone()) .filter(is_version_dep) .map(|dependency| (dependency.name, None)) .collect() } else { only_update .into_iter() .map(|name| { if let Some(dependency) = CrateName::new(&name.clone()).parse_as_version()? { Ok(( dependency.name.clone(), dependency.version().map(String::from), )) } else { Ok((name, None)) } }) .collect::<Result<_>>()? })) } fn upgrade(self, upgraded_deps: &ActualUpgrades, dry_run: bool) -> Result<()> { if dry_run { let bufwtr = BufferWriter::stdout(ColorChoice::Always); let mut buffer = bufwtr.buffer(); buffer .set_color(ColorSpec::new().set_fg(Some(Color::Cyan)).set_bold(true)) .chain_err(|| "Failed to set output colour")?; write!(&mut buffer, "Starting dry run. ") .chain_err(|| "Failed to write dry run message")?; buffer .set_color(&ColorSpec::new()) .chain_err(|| "Failed to clear output colour")?; writeln!(&mut buffer, "Changes will not be saved.") .chain_err(|| "Failed to write dry run message")?; bufwtr .print(&buffer) .chain_err(|| "Failed to print dry run message")?; } for (mut manifest, package) in self.0 { println!("{}:", package.name); for (name, version) in &upgraded_deps.0 { manifest.upgrade(&Dependency::new(name).set_version(version), dry_run)?; } } Ok(()) } } struct DesiredUpgrades(HashMap<String, Option<String>>); struct ActualUpgrades(HashMap<String, String>); impl DesiredUpgrades { fn get_upgraded(self, allow_prerelease: bool) -> Result<ActualUpgrades> { self.0 .into_iter() .map(|(name, version)| { if let Some(v) = version { Ok((name, v)) } else { get_latest_dependency(&name, allow_prerelease) .map(|new_dep| { ( name, new_dep .version() .expect("Invalid dependency type") .to_string(), ) }) .chain_err(|| "Failed to get new version") } }) .collect::<Result<_>>() .map(ActualUpgrades) } } fn process(args: Args) -> Result<()> { let Args { dependency, manifest_path, all, allow_prerelease, dry_run, .. } = args; let manifests = if all { Manifests::get_all(&manifest_path) } else { Manifests::get_local_one(&manifest_path) }?; let existing_dependencies = manifests.get_dependencies(dependency)?; let upgraded_dependencies = existing_dependencies.get_upgraded(allow_prerelease)?; manifests.upgrade(&upgraded_dependencies, dry_run) } fn main() { let args: Command = Command::from_args(); let Command::Upgrade(args) = args; if let Err(err) = process(args) { eprintln!("Command failed due to unhandled error: {}\n", err); for e in err.iter().skip(1) { eprintln!("Caused by: {}", e); } if let Some(backtrace) = err.backtrace() { eprintln!("Backtrace: {:?}", backtrace); } process::exit(1); } }
#![warn( missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications )] #[macro_use] extern crate error_chain; use crate::errors::*; use cargo_edit::{find, get_latest_dependency, CrateName, Dependency, LocalManifest}; use failure::Fail; use std::collections::HashMap; use std::io::Write; use std::path::{Path, PathBuf}; use std::process; use structopt::StructOpt; use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor}; mod errors { error_chain! { links { CargoEditLib(::cargo_edit::Error, ::cargo_edit::ErrorKind); } foreign_links { CargoMetadata(::failure::Compat<::cargo_metadata::Error>); } } } #[derive(Debug, StructOpt)] #[structopt(bin_name = "cargo")] enum Command { #[structopt(name = "upgrade", author = "")] #[structopt( after_help = "This command differs from `cargo update`, which updates the dependency versions recorded in the local lock file (Cargo.lock). If `<dependency>`(s) are provided, only the specified dependencies will be upgraded. The version to upgrade to for each can be specified with e.g. `docopt@0.8.0` or `serde@>=0.9,<2.0`. Dev, build, and all target dependencies will also be upgraded. Only dependencies from crates.io are supported. Git/path dependencies will be ignored. All packages in the workspace will be upgraded if the `--all` flag is supplied. The `--all` flag may be supplied in the presence of a virtual manifest." )] Upgrade(Args), } #[derive(Debug, StructOpt)] struct Args { dependency: Vec<String>, #[structopt(long = "manifest-path", value_name = "path")] manifest_path: Option<PathBuf>, #[structopt(long = "all")] all: bool, #[structopt(long = "allow-prerelease")] allow_prerelease: bool, #[structopt(long = "dry-run")] dry_run: bool, } struct Manifests(Vec<(LocalManifest, cargo_metadata::Package)>); impl Manifests { fn get_all(manifest_path: &Option<PathBuf>) -> Result<Self> { let mut cmd = cargo_metadata::MetadataCommand::new(); cmd.no_deps(); if let Some(path) = manifest_path { cmd.manifest_path(path); } let result = cmd .exec() .map_err(|e| Error::from(e.compat()).chain_err(|| "Failed to get workspace metadata"))?; result .packages .into_iter() .map(|package| { Ok(( LocalManifest::try_new(Path::new(&package.manifest_path))?, package, )) }) .collect::<Result<Vec<_>>>() .map(Manifests) } fn get_local_one(manifest_path: &Option<PathBuf>) -> Result<Self> { let resolved_manifest_path: String = find(&manifest_path)?.to_string_lossy().into(); let manifest = LocalManifest::find(&manifest_path)?; let mut cmd = cargo_metadata::MetadataCommand::new(); cmd.no_deps(); if let Some(path) = manifest_path { cmd.manifest_path(path); } let result = cmd .exec() .map_err(|e| Error::from(e.compat()).chain_err(|| "Invalid manifest"))?; let packages = result.packages; let package = packages .iter() .find(|p| p.manifest_path.to_string_lossy() == resolved_manifest_path) .chain_err(|| { "Found virtual manifest, but this command requires running against an \ actual package in this workspace. Try adding `--all`." })?; Ok(Manifests(vec![(manifest, package.to_owned())])) } fn get_dependencies(&self, only_update: Vec<String>) -> Result<DesiredUpgrades> {
Ok(DesiredUpgrades(if only_update.is_empty() { self.0 .iter() .flat_map(|&(_, ref package)| package.dependencies.clone()) .filter(is_version_dep) .map(|dependency| (dependency.name, None)) .collect() } else { only_update .into_iter() .map(|name| { if let Some(dependency) = CrateName::new(&name.clone()).parse_as_version()? { Ok(( dependency.name.clone(), dependency.version().map(String::from), )) } else { Ok((name, None)) } }) .collect::<Result<_>>()? })) } fn upgrade(self, upgraded_deps: &ActualUpgrades, dry_run: bool) -> Result<()> { if dry_run { let bufwtr = BufferWriter::stdout(ColorChoice::Always); let mut buffer = bufwtr.buffer(); buffer .set_color(ColorSpec::new().set_fg(Some(Color::Cyan)).set_bold(true)) .chain_err(|| "Failed to set output colour")?; write!(&mut buffer, "Starting dry run. ") .chain_err(|| "Failed to write dry run message")?; buffer .set_color(&ColorSpec::new()) .chain_err(|| "Failed to clear output colour")?; writeln!(&mut buffer, "Changes will not be saved.") .chain_err(|| "Failed to write dry run message")?; bufwtr .print(&buffer) .chain_err(|| "Failed to print dry run message")?; } for (mut manifest, package) in self.0 { println!("{}:", package.name); for (name, version) in &upgraded_deps.0 { manifest.upgrade(&Dependency::new(name).set_version(version), dry_run)?; } } Ok(()) } } struct DesiredUpgrades(HashMap<String, Option<String>>); struct ActualUpgrades(HashMap<String, String>); impl DesiredUpgrades { fn get_upgraded(self, allow_prerelease: bool) -> Result<ActualUpgrades> { self.0 .into_iter() .map(|(name, version)| { if let Some(v) = version { Ok((name, v)) } else { get_latest_dependency(&name, allow_prerelease) .map(|new_dep| { ( name, new_dep .version() .expect("Invalid dependency type") .to_string(), ) }) .chain_err(|| "Failed to get new version") } }) .collect::<Result<_>>() .map(ActualUpgrades) } } fn process(args: Args) -> Result<()> { let Args { dependency, manifest_path, all, allow_prerelease, dry_run, .. } = args; let manifests = if all { Manifests::get_all(&manifest_path) } else { Manifests::get_local_one(&manifest_path) }?; let existing_dependencies = manifests.get_dependencies(dependency)?; let upgraded_dependencies = existing_dependencies.get_upgraded(allow_prerelease)?; manifests.upgrade(&upgraded_dependencies, dry_run) } fn main() { let args: Command = Command::from_args(); let Command::Upgrade(args) = args; if let Err(err) = process(args) { eprintln!("Command failed due to unhandled error: {}\n", err); for e in err.iter().skip(1) { eprintln!("Caused by: {}", e); } if let Some(backtrace) = err.backtrace() { eprintln!("Backtrace: {:?}", backtrace); } process::exit(1); } }
fn is_version_dep(dependency: &cargo_metadata::Dependency) -> bool { match dependency.source { Some(ref s) => s.splitn(2, '+').next() == Some("registry"), _ => false, } }
function_block-full_function
[ { "content": "fn get_name_from_manifest(manifest: &Manifest) -> Result<String> {\n\n manifest\n\n .data\n\n .as_table()\n\n .get(\"package\")\n\n .and_then(|m| m[\"name\"].as_str().map(std::string::ToString::to_string))\n\n .ok_or_else(|| ErrorKind::ParseCargoToml.into())\n...
Rust
rpg-cli/src/main.rs
Jomy10/rpg-lang
e7f283633ff5931fe4aef27bdabf4e794a840369
use std::{env, fs}; use std::path::Path; use std::process::Command; use std::time::Duration; use clap::{App, arg}; use directories_next::ProjectDirs; use rpg_compiler::{Config}; use rpg_compiler::user_output::CompileError; use simple_colors::{blue, green}; use spinner::{SpinnerHandle, SpinnerBuilder}; use spinners::utils::spinner_data::SpinnerData; pub struct ColoredSpinner { handle: SpinnerHandle, } impl ColoredSpinner { pub fn new(message: String) -> Self { let spinner_data = SpinnerData {frames: vec![ "\x1b[34m⠋\x1b[0m", "\x1b[34m⠙\x1b[0m", "\x1b[34m⠚\x1b[0m", "\x1b[34m⠞\x1b[0m", "\x1b[34m⠖\x1b[0m", "\x1b[34m⠦\x1b[0m", "\x1b[34m⠴\x1b[0m", "\x1b[34m⠲\x1b[0m", "\x1b[34m⠳\x1b[0m", "\x1b[34m⠓\x1b[0m" ], interval: 80}; let handle = SpinnerBuilder::new(message) .spinner(spinner_data.frames.clone()) .step(Duration::from_millis(spinner_data.interval.into())) .start(); ColoredSpinner { handle } } pub fn message(&self, message: String) -> Option<String> { self.handle.update(message) } pub fn stop(self) { self.handle.close(); } } fn main() { let dir = ProjectDirs::from("be", "jonaseveraert", "rpgc").expect("No valid home directory path could be retrieved from the operating system"); let data_dir = dir.data_dir(); let matches = App::new("RPG Compiler") .version("0.1.0") .author("Jonas Everaert <info@jonaseveraert.be>") .about("The official compiler for the RPG esoteric programming language") .arg(arg!([file] "The .rpg source file you wish to compile")) .arg( arg!([output_dir] "Sets the output directory of the compiled app") ) .arg( arg!(-r --release "Compiles the program with optimizations") ) .arg( arg!(-d --debug "Compiles the program without optimization (default)") ) .arg( arg!(-m --max_char <VALUE> "Optionally sets the maximum amount of characters allowed in the program, setting it to more than 10 is considered cheating, though.") .required(false) ) .arg( arg!(-v --verbose "Prints out more error messages") ) .subcommand( App::new("clean") .about("Cleans the build folder"), ) .get_matches(); if let Some(file) = matches.value_of("file") { let debug = !matches.is_present("release"); let verbose = matches.is_present("verbose"); let max_char = matches.value_of("max_char"); let _output_dir = matches.value_of("output_dir"); let cd = env::current_dir().expect_compile_error("Could not find current working directory"); let output_dir: &Path; if let Some(dir) = _output_dir { output_dir = Path::new(dir); } else { output_dir = cd.as_path() }; let app_name = "rpg"; let compiled = if verbose == true || max_char.is_some() { unsafe { rpg_compiler::compile_with_config( file, Config { max_char: if max_char.is_some() { max_char.unwrap().parse::<usize>().expect_compile_error("Did not specify a valid number for max_char") } else { 10 }, verbose }, ) } } else { rpg_compiler::compile(file) }; let compiled_path = Path::new(data_dir).join("tmp_compiled"); if !compiled_path.exists() { fs::create_dir_all(&compiled_path).expect_compile_error("Couldn't create working directory."); fs::create_dir(&compiled_path.join("src")).expect_compile_error("Couldn't create working directory."); fs::write(&compiled_path.join("Cargo.toml"), CARGO_TOML).expect_compile_error("Couldn't create working directory."); } fs::write(&compiled_path.join("src").join("main.rs"), compiled).expect_compile_error("Couldn't write compiled source file."); let sp = ColoredSpinner::new("Compiling rust project...".to_string()); let o = if cfg!(target_os = "windows") { Command::new("cmd") .args(["/C", &format!("cd \"{}\" && cargo build{}", compiled_path.to_str().expect_compile_error( "unable to convert compiled path to string." ), if debug {""} else {" --release"} ).trim()]) .output() .expect_compile_error("Failed to execute rust compiler") } else { Command::new("sh") .arg("-c") .arg(&format!("cd \"{}\" && cargo build{}", compiled_path.to_str().expect_compile_error( "unable to convert compiled path to string." ), if debug {""} else {" --release"} ).trim()) .output() .expect_compile_error("Failed to execute rust compiler") }; sp.stop(); if verbose { let out = String::from_utf8(o.stdout).expect("Couldn't convert utf8."); let out = out.trim(); let err = String::from_utf8(o.stderr).expect("Couldn't convert utf8."); let err = err.trim(); println!("{out}"); println!("{err}"); } println!(); let sp = ColoredSpinner::new("Copying...".to_string()); let output_dir = Path::new(output_dir); let compiled_file_dir = compiled_path.join("target").join("debug").join(app_name); fs::write(output_dir.join(app_name), fs::read(compiled_file_dir).expect_compile_error("Compiled file not found or no read access.")).expect_compile_error("Couldn't write output file."); sp.message("Setting file permissions...".to_string()); let o = if cfg!(target_os = "windows") { Command::new("cmd") .args(["/C", &format!("icacls {app_name} /grant user:(gw,ge,d,wd,ra,rea)")]) .output() .expect_compile_error("Failed to execute rust compiler") } else { Command::new("sh") .arg("-c") .arg(&format!("chmod +x {app_name}")) .output() .expect_compile_error("Failed to execute rust compiler") }; sp.stop(); if verbose { println!("{}", String::from_utf8(o.stdout).expect("Couldn't parse stdout").trim()); println!("{}", String::from_utf8(o.stderr).expect("Couldn't parse stderr").trim()); } println!("\n{}", blue!("Compilation successful.")) } else if let Some(("clean", _)) = matches.subcommand() { fs::remove_dir_all(data_dir).expect("Couldn't remove working directory."); println!("{}", green!("Cleaned build folder")) } else { println!("Please specify a source file") } } const CARGO_TOML: &str = r#"[package] name = "rpg" version = "0.1.0" edition = "2021""#;
use std::{env, fs}; use std::path::Path; use std::process::Command; use std::time::Duration; use clap::{App, arg}; use directories_next::ProjectDirs; use rpg_compiler::{Config}; use rpg_compiler::user_output::CompileError; use simple_colors::{blue, green}; use spinner::{SpinnerHandle, SpinnerBuilder}; use spinners::utils::spinner_data::SpinnerData; pub struct ColoredSpinner { handle: SpinnerHandle, } impl ColoredSpinner { pub fn new(message: String) -> Self { let spinner_data = SpinnerData {frames: vec![ "\x1b[34m⠋\x1b[0m", "\x1b[34m⠙\x1b[0m", "\x1b[34m⠚\x1b[0m", "\x1b[34m⠞\x1b[0m", "\x1b[34m⠖\x1b[0m", "\x1b[34m⠦\x1b[0m", "\x1b[34m⠴\x1b[0m", "\x1b[34m⠲\x1b[0m", "\x1b[34m⠳\x1b[0m", "\x1b[34m⠓\x1b[0m" ], interval: 80}; let handle = SpinnerBuilder::new(message) .spinner(spinner_data.frames.clone()) .step(Duration::from_millis(spinner_data.interval.into())) .start(); ColoredSpinner { handle } } pub fn message(&self, message: String) -> Option<String> { self.handle.update(message) } pub fn stop(self) { self.handle.close(); } } fn main() {
let data_dir = dir.data_dir(); let matches = App::new("RPG Compiler") .version("0.1.0") .author("Jonas Everaert <info@jonaseveraert.be>") .about("The official compiler for the RPG esoteric programming language") .arg(arg!([file] "The .rpg source file you wish to compile")) .arg( arg!([output_dir] "Sets the output directory of the compiled app") ) .arg( arg!(-r --release "Compiles the program with optimizations") ) .arg( arg!(-d --debug "Compiles the program without optimization (default)") ) .arg( arg!(-m --max_char <VALUE> "Optionally sets the maximum amount of characters allowed in the program, setting it to more than 10 is considered cheating, though.") .required(false) ) .arg( arg!(-v --verbose "Prints out more error messages") ) .subcommand( App::new("clean") .about("Cleans the build folder"), ) .get_matches(); if let Some(file) = matches.value_of("file") { let debug = !matches.is_present("release"); let verbose = matches.is_present("verbose"); let max_char = matches.value_of("max_char"); let _output_dir = matches.value_of("output_dir"); let cd = env::current_dir().expect_compile_error("Could not find current working directory"); let output_dir: &Path; if let Some(dir) = _output_dir { output_dir = Path::new(dir); } else { output_dir = cd.as_path() }; let app_name = "rpg"; let compiled = if verbose == true || max_char.is_some() { unsafe { rpg_compiler::compile_with_config( file, Config { max_char: if max_char.is_some() { max_char.unwrap().parse::<usize>().expect_compile_error("Did not specify a valid number for max_char") } else { 10 }, verbose }, ) } } else { rpg_compiler::compile(file) }; let compiled_path = Path::new(data_dir).join("tmp_compiled"); if !compiled_path.exists() { fs::create_dir_all(&compiled_path).expect_compile_error("Couldn't create working directory."); fs::create_dir(&compiled_path.join("src")).expect_compile_error("Couldn't create working directory."); fs::write(&compiled_path.join("Cargo.toml"), CARGO_TOML).expect_compile_error("Couldn't create working directory."); } fs::write(&compiled_path.join("src").join("main.rs"), compiled).expect_compile_error("Couldn't write compiled source file."); let sp = ColoredSpinner::new("Compiling rust project...".to_string()); let o = if cfg!(target_os = "windows") { Command::new("cmd") .args(["/C", &format!("cd \"{}\" && cargo build{}", compiled_path.to_str().expect_compile_error( "unable to convert compiled path to string." ), if debug {""} else {" --release"} ).trim()]) .output() .expect_compile_error("Failed to execute rust compiler") } else { Command::new("sh") .arg("-c") .arg(&format!("cd \"{}\" && cargo build{}", compiled_path.to_str().expect_compile_error( "unable to convert compiled path to string." ), if debug {""} else {" --release"} ).trim()) .output() .expect_compile_error("Failed to execute rust compiler") }; sp.stop(); if verbose { let out = String::from_utf8(o.stdout).expect("Couldn't convert utf8."); let out = out.trim(); let err = String::from_utf8(o.stderr).expect("Couldn't convert utf8."); let err = err.trim(); println!("{out}"); println!("{err}"); } println!(); let sp = ColoredSpinner::new("Copying...".to_string()); let output_dir = Path::new(output_dir); let compiled_file_dir = compiled_path.join("target").join("debug").join(app_name); fs::write(output_dir.join(app_name), fs::read(compiled_file_dir).expect_compile_error("Compiled file not found or no read access.")).expect_compile_error("Couldn't write output file."); sp.message("Setting file permissions...".to_string()); let o = if cfg!(target_os = "windows") { Command::new("cmd") .args(["/C", &format!("icacls {app_name} /grant user:(gw,ge,d,wd,ra,rea)")]) .output() .expect_compile_error("Failed to execute rust compiler") } else { Command::new("sh") .arg("-c") .arg(&format!("chmod +x {app_name}")) .output() .expect_compile_error("Failed to execute rust compiler") }; sp.stop(); if verbose { println!("{}", String::from_utf8(o.stdout).expect("Couldn't parse stdout").trim()); println!("{}", String::from_utf8(o.stderr).expect("Couldn't parse stderr").trim()); } println!("\n{}", blue!("Compilation successful.")) } else if let Some(("clean", _)) = matches.subcommand() { fs::remove_dir_all(data_dir).expect("Couldn't remove working directory."); println!("{}", green!("Cleaned build folder")) } else { println!("Please specify a source file") } } const CARGO_TOML: &str = r#"[package] name = "rpg" version = "0.1.0" edition = "2021""#;
let dir = ProjectDirs::from("be", "jonaseveraert", "rpgc").expect("No valid home directory path could be retrieved from the operating system");
assignment_statement
[ { "content": "pub fn compile(file: &str) -> String {\n\n let sp = ColoredSpinner::new(\"Reading input...\".to_string());\n\n let code = fs::read_to_string(file).expect_compile_error(&format!(\"{file} could not be found.\"));\n\n let code = rm_comments(&code);\n\n let code = code.trim();\n\n sp.st...
Rust
ignition-host/src/process/pipe.rs
mvanbem/ignition
d22dffd786ff10f69ffa5f8d36cd46fd06288e00
use std::ptr::copy_nonoverlapping; use std::sync::{Arc, Mutex}; use std::task::Poll; use replace_with::{replace_with_or_abort, replace_with_or_abort_and_return}; use tokio::sync::mpsc::UnboundedSender; use crate::{TaskId, WakeParams}; struct SendPointer<T>(*const T); unsafe impl<T> Send for SendPointer<T> {} struct SendPointerMut<T>(*mut T); unsafe impl<T> Send for SendPointerMut<T> {} pub struct PipeReader { inner: Arc<Mutex<InnerPipe>>, } pub struct PipeWriter { inner: Arc<Mutex<InnerPipe>>, } struct InnerPipe { state: PipeState, } enum PipeState { Idle, PendingRead { read_wake_queue_sender: UnboundedSender<WakeParams>, read_task_id: TaskId, dst: SendPointerMut<u8>, dst_len: u32, }, PendingWrite { write_wake_queue_sender: UnboundedSender<WakeParams>, write_task_id: TaskId, src: SendPointer<u8>, src_len: u32, }, Closed, } pub fn pipe() -> (PipeReader, PipeWriter) { let inner = Arc::new(Mutex::new(InnerPipe { state: PipeState::Idle, })); ( PipeReader { inner: Arc::clone(&inner), }, PipeWriter { inner }, ) } impl InnerPipe { fn close(&mut self) { replace_with_or_abort(&mut self.state, |state| match state { PipeState::Idle => PipeState::Closed, PipeState::PendingRead { read_wake_queue_sender, read_task_id, .. } => { read_wake_queue_sender .send(WakeParams { task_id: read_task_id, param: 0, }) .unwrap(); PipeState::Closed } PipeState::PendingWrite { .. } => { todo!("write to a closed pipe") } PipeState::Closed => PipeState::Closed, }); } } impl PipeReader { pub unsafe fn read( &self, read_wake_queue_sender: &UnboundedSender<WakeParams>, read_task_id: TaskId, dst: *mut u8, dst_len: u32, ) -> Poll<u32> { if dst_len == 0 { return Poll::Ready(0); } let mut inner = self.inner.lock().unwrap(); replace_with_or_abort_and_return(&mut inner.state, |state| match state { PipeState::Idle => ( Poll::Pending, PipeState::PendingRead { read_wake_queue_sender: read_wake_queue_sender.clone(), read_task_id, dst: SendPointerMut(dst), dst_len, }, ), PipeState::PendingRead { .. } => { todo!("read with a read already pending") } PipeState::PendingWrite { write_wake_queue_sender, write_task_id, src, src_len, } => { let len = dst_len.min(src_len); unsafe { copy_nonoverlapping(src.0, dst, len as _) } write_wake_queue_sender .send(WakeParams { task_id: write_task_id, param: len, }) .unwrap(); (Poll::Ready(len), PipeState::Idle) } PipeState::Closed => (Poll::Ready(0), PipeState::Closed), }) } pub fn close(&self) { self.inner.lock().unwrap().close(); } } impl PipeWriter { pub unsafe fn write( &self, write_wake_queue_sender: &UnboundedSender<WakeParams>, write_task_id: TaskId, src: *const u8, src_len: u32, ) -> Poll<u32> { if src_len == 0 { return Poll::Ready(0); } let mut inner = self.inner.lock().unwrap(); replace_with_or_abort_and_return(&mut inner.state, |state| match state { PipeState::Idle => ( Poll::Pending, PipeState::PendingWrite { write_wake_queue_sender: write_wake_queue_sender.clone(), write_task_id, src: SendPointer(src), src_len, }, ), PipeState::PendingRead { read_wake_queue_sender, read_task_id, dst, dst_len, } => { let len = src_len.min(dst_len); unsafe { copy_nonoverlapping(src, dst.0, len as _) } read_wake_queue_sender .send(WakeParams { task_id: read_task_id, param: len, }) .unwrap(); (Poll::Ready(len), PipeState::Idle) } PipeState::PendingWrite { .. } => todo!("write with a write already pending"), PipeState::Closed => todo!("write to a closed pipe"), }) } pub fn close(&self) { self.inner.lock().unwrap().close(); } }
use std::ptr::copy_nonoverlapping; use std::sync::{Arc, Mutex}; use std::task::Poll; use replace_with::{replace_with_or_abort, replace_with_or_abort_and_return}; use tokio::sync::mpsc::UnboundedSender; use crate::{TaskId, WakeParams}; struct SendPointer<T>(*const T); unsafe impl<T> Send for SendPointer<T> {} struct SendPointerMut<T>(*mut T); unsafe impl<T> Send for SendPointerMut<T> {} pub struct PipeReader { inner: Arc<Mutex<InnerPipe>>, } pub struct PipeWriter { inner: Arc<Mutex<InnerPipe>>, } struct InnerPipe { state: PipeState, } enum PipeState { Idle, PendingRead { read_wake_queue_sender: UnboundedSender<WakeParams>, read_task_id: TaskId, dst: SendPointerMut<u8>, dst_len: u32, }, PendingWrite { write_wake_queue_sender: UnboundedSender<WakeParams>, write_task_id: TaskId, src: SendPointer<u8>, src_len: u32, }, Closed, } pub fn pipe() -> (PipeReader, PipeWriter) { let inner = Arc::new(Mutex::new(InnerPipe { state: PipeState::Idle, })); ( PipeReader { inner: Arc::clone(&inner), }, PipeWriter { inner }, ) } impl InnerPipe { fn close(&mut self) { replace_with_or_abort(&mut self.state, |state| match state { PipeState::Idle => PipeState::Closed, PipeState::PendingRead { read_wake_queue_sender, read_task_id, .. } => { read_wake_queue_sender .send(WakeParams { task_id: read_task_id, param: 0, }) .unwrap(); PipeState::Closed } PipeState::PendingWrite { .. } => { todo!("write to a closed pipe") } PipeState::Closed => PipeState::Closed, }); } } impl PipeReader { pub unsafe fn read( &self, read_wake_queue_sender: &UnboundedSender<WakeParams>, read_task_id: TaskId, dst: *mut u8, dst_len: u32, ) -> Poll<u32> { if dst_len == 0 { return Poll::Ready(0); } let mut inner = self.inner.lock().unwrap(); replace_with_or_abort_and_return(&mut inner.state, |state| match state { PipeState::Idle => ( Poll::Pending, PipeState::PendingRead { read_wake_queue_sender: read_wake_queue_sender.clone(), read_task_id, dst: SendPointerMut(dst), dst_len, }, ),
pub fn close(&self) { self.inner.lock().unwrap().close(); } } impl PipeWriter { pub unsafe fn write( &self, write_wake_queue_sender: &UnboundedSender<WakeParams>, write_task_id: TaskId, src: *const u8, src_len: u32, ) -> Poll<u32> { if src_len == 0 { return Poll::Ready(0); } let mut inner = self.inner.lock().unwrap(); replace_with_or_abort_and_return(&mut inner.state, |state| match state { PipeState::Idle => ( Poll::Pending, PipeState::PendingWrite { write_wake_queue_sender: write_wake_queue_sender.clone(), write_task_id, src: SendPointer(src), src_len, }, ), PipeState::PendingRead { read_wake_queue_sender, read_task_id, dst, dst_len, } => { let len = src_len.min(dst_len); unsafe { copy_nonoverlapping(src, dst.0, len as _) } read_wake_queue_sender .send(WakeParams { task_id: read_task_id, param: len, }) .unwrap(); (Poll::Ready(len), PipeState::Idle) } PipeState::PendingWrite { .. } => todo!("write with a write already pending"), PipeState::Closed => todo!("write to a closed pipe"), }) } pub fn close(&self) { self.inner.lock().unwrap().close(); } }
PipeState::PendingRead { .. } => { todo!("read with a read already pending") } PipeState::PendingWrite { write_wake_queue_sender, write_task_id, src, src_len, } => { let len = dst_len.min(src_len); unsafe { copy_nonoverlapping(src.0, dst, len as _) } write_wake_queue_sender .send(WakeParams { task_id: write_task_id, param: len, }) .unwrap(); (Poll::Ready(len), PipeState::Idle) } PipeState::Closed => (Poll::Ready(0), PipeState::Closed), }) }
function_block-function_prefix_line
[ { "content": "#[doc(hidden)]\n\npub fn wake_internal(task_id: u32, param: usize, init: fn()) {\n\n if task_id == u32::MAX {\n\n init();\n\n } else {\n\n dispatch_wake(TaskId(task_id), param);\n\n }\n\n run();\n\n}\n\n\n\n// TODO: Expand this into a fancy proc macro, something like #[ig...
Rust
src/krull64.rs
SamiPerttu/rand_krull
1b613461fb08329588506efaf091206492ae9726
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use wrapping_arithmetic::wrappit; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Eq, PartialEq, Debug)] pub struct Krull64 { lcg0: u64, lcg1: u64, stream: u64, } #[inline] fn origin_0(stream: u64) -> u64 { !stream } #[inline] fn origin_128(stream: u64) -> u128 { origin_0(stream) as u128 } impl Krull64 { #[inline] fn lcg_128(&self) -> u128 { self.lcg0 as u128 | ((self.lcg1 as u128) << 64) } #[inline] fn multiplier(&self) -> u64 { super::LCG_M65_1 as u64 } #[inline] fn multiplier_128(&self) -> u128 { super::LCG_M65_1 } #[inline] fn increment_128(&self) -> u128 { ((self.stream as u128) << 1) | 1 } #[inline] fn origin_0(&self) -> u64 { origin_0(self.stream) } #[inline] fn origin_128(&self) -> u128 { origin_128(self.stream) } #[wrappit] #[inline] pub fn step(&mut self) -> u64 { let lcg = (self.lcg0 as u128) * self.multiplier() as u128 + self.increment_128(); self.lcg1 = ((lcg >> 64) as u64) + self.lcg1 * self.multiplier() + self.lcg0; self.lcg0 = lcg as u64; self.get() } #[inline] pub fn step_128(&mut self) -> u128 { self.step() as u128 | ((self.step() as u128) << 64) } #[wrappit] #[inline] pub fn get(&self) -> u64 { let x = self.lcg1; let x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; let x = (x ^ (x >> 27)) * 0x94d049bb133111eb; let x = (x ^ (x >> 31)) * 0xd6e8feb86659fd93; x ^ (x >> 32) } #[wrappit] #[inline] pub fn step_slow(&mut self) -> u64 { let lcg = self.lcg_128() * self.multiplier_128() + self.increment_128(); self.lcg0 = lcg as u64; self.lcg1 = (lcg >> 64) as u64; self.get() } #[allow(clippy::new_without_default)] pub fn new() -> Self { Krull64 { lcg0: origin_0(0), lcg1: 0, stream: 0, } } pub fn from_32(seed: u32) -> Self { Krull64::from_64(seed as u64) } pub fn from_64(seed: u64) -> Self { Krull64 { lcg0: origin_0(seed), lcg1: 0, stream: seed, } } pub fn from_128(seed: u128) -> Self { let mut krull = Krull64::from_64(((seed >> 64) ^ seed) as u64); krull.set_position((seed as u128) << 64); krull } pub fn jump(&mut self, steps: i128) { let lcg = crate::lcg::get_state( self.multiplier_128(), self.increment_128(), self.lcg_128(), steps as u128, ); self.lcg0 = lcg as u64; self.lcg1 = (lcg >> 64) as u64; } pub fn position(&self) -> u128 { crate::lcg::get_iterations( self.multiplier_128(), self.increment_128(), self.origin_128(), self.lcg_128(), ) } pub fn set_position(&mut self, position: u128) { let lcg = crate::lcg::get_state( self.multiplier_128(), self.increment_128(), self.origin_128(), position, ); self.lcg0 = lcg as u64; self.lcg1 = (lcg >> 64) as u64; } #[inline] pub fn reset(&mut self) { self.lcg0 = self.origin_0(); self.lcg1 = 0; } #[inline] pub fn stream(&self) -> u64 { self.stream } pub fn set_stream(&mut self, stream: u64) { self.stream = stream; self.reset(); } } use super::{Error, RngCore, SeedableRng}; impl RngCore for Krull64 { fn next_u32(&mut self) -> u32 { self.step() as u32 } fn next_u64(&mut self) -> u64 { self.step() } fn fill_bytes(&mut self, dest: &mut [u8]) { let bytes = dest.len(); let mut i = 0; while i < bytes { let x = self.step(); let j = bytes.min(i + 8); dest[i..j].copy_from_slice(&x.to_le_bytes()[0..(j - i)]); i = j; } } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { self.fill_bytes(dest); Ok(()) } } impl SeedableRng for Krull64 { type Seed = [u8; 16]; fn from_seed(seed: Self::Seed) -> Self { Krull64::from_128(u128::from_le_bytes(seed)) } } #[cfg(test)] mod tests { use super::super::*; use super::*; #[test] pub fn run_tests() { let krull64_expected: [u64; 16] = [ 0x57c1b6c1df5ed4d2, 0x1efdba83398cf412, 0xa02d8dfda06ac9ce, 0xf6e3f32be5e81841, 0xc2a690083e597e0d, 0x3b1b2ed3fa6c15aa, 0x241c691340a479b2, 0x88c24c8d79bb67c1, 0x09f213c4fc2b61dc, 0xa4b6ad95c713c951, 0xa43904ae3341edf7, 0xee2dca4d5fd5f8fa, 0x27bdddbeaa4aadb0, 0x98c78e68dbf634b2, 0xf0edc57017a0d5a5, 0x8647ea5de51eca23, ]; let mut krull64 = Krull64::from_64(0); for x in krull64_expected { assert_eq!(x, krull64.next_u64()); } let mut r: u128 = 0; let mut rnd = || -> u128 { r = r.wrapping_mul(LCG_M128_1).wrapping_add(0xffff); r }; for _ in 0..1 << 12 { let seed = rnd() as u64; let mut krull1 = Krull64::new(); assert_eq!(0, krull1.stream()); assert_eq!(0, krull1.position()); krull1.set_stream(seed); assert_eq!(seed, krull1.stream()); assert_eq!(0, krull1.position()); let mut krull2 = Krull64::from_64(seed); assert_eq!(seed, krull2.stream()); assert_eq!(0, krull2.position()); let pos2 = rnd(); let pos1 = pos2 & rnd(); krull1.set_position(pos1); krull2.set_position(pos2); assert_eq!(pos1, krull1.position()); assert_eq!(pos2, krull2.position()); krull1.jump((pos2 - pos1) as i128); assert_eq!(pos2, krull1.position()); assert_eq!(krull1.next_u64(), krull2.next_u64()); krull1.jump(-1); assert_eq!(pos2, krull1.position()); krull2.jump(-1); assert_eq!(pos2, krull2.position()); krull1.jump(-((pos2 - pos1) as i128)); assert_eq!(pos1, krull1.position()); let n = 1 + (rnd() & 0x3ff); for _ in 0..n { krull1.next_u64(); } assert_eq!(pos1 + n, krull1.position()); assert_eq!(seed, krull1.stream()); let bytes = 1 + (rnd() & 0x7f); let mut buffer1 = [0u8; 0x80]; let mut buffer2 = [0u8; 0x80]; krull1.reset(); assert_eq!(0, krull1.position()); krull1.fill_bytes(&mut buffer1[0..bytes as usize]); krull2.reset(); for i in 0..0x10 { let x = krull2.next_u64(); buffer2[(i << 3)..((i + 1) << 3)].copy_from_slice(&x.to_le_bytes()); } assert!(buffer1[0..bytes as usize] .iter() .zip(buffer2[0..bytes as usize].iter()) .all(|(x, y)| x == y)); } } }
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use wrapping_arithmetic::wrappit; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Eq, PartialEq, Debug)] pub struct Krull64 { lcg0: u64, lcg1: u64, stream: u64, } #[inline] fn origin_0(stream: u64) -> u64 { !stream } #[inline] fn origin_128(stream: u64) -> u128 { origin_0(stream) as u128 } impl Krull64 { #[inline] fn lcg_128(&self) -> u128 { self.lcg0 as u128 | ((self.lcg1 as u128) << 64) } #[inline] fn multiplier(&self) -> u64 { super::LCG_M65_1 as u64 } #[inline] fn multiplier_128(&self) -> u128 { super::LCG_M65_1 } #[inline] fn increment_128(&self) -> u128 { ((self.stream as u128) << 1) | 1 } #[inline] fn origin_0(&self) -> u64 { origin_0(self.stream) } #[inline] fn origin_128(&self) -> u128 { origin_128(self.stream) } #[wrappit] #[inline] pub fn step(&mut self) -> u64 { let lcg = (self.lcg0 as u128) * self.multiplier() as u128 + self.increment_128(); self.lcg1 = ((lcg >> 64) as u64) + self.lcg1 * self.multiplier() + self.lcg0; self.lcg0 = lcg as u64; self.get() } #[inline] pub fn step_128(&mut self) -> u128 { self.step() as u128 | ((self.step() as u128) << 64) } #[wrappit] #[inline] pub fn get(&self) -> u64 { let x = self.lcg1; let x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; let x = (x ^ (x >> 27)) * 0x94d049bb133111eb; let x = (x ^ (x >> 31)) * 0xd6e8feb86659fd93; x ^ (x >> 32) } #[wrappit] #[inline] pub fn step_slow(&mut self) -> u64 { let lcg = self.lcg_128() * self.multiplier_128() + self.increment_128(); self.lcg0 = lcg as u64; self.lcg1 = (lcg >> 64) as u64; self.get() } #[allow(clippy::new_without_default)] pub fn new() -> Self { Krull64 { lcg0: origin_0(0), lcg1: 0, stream: 0, } } pub fn from_32(seed: u32) -> Self { Krull64::from_64(seed as u64) }
pub fn from_128(seed: u128) -> Self { let mut krull = Krull64::from_64(((seed >> 64) ^ seed) as u64); krull.set_position((seed as u128) << 64); krull } pub fn jump(&mut self, steps: i128) { let lcg = crate::lcg::get_state( self.multiplier_128(), self.increment_128(), self.lcg_128(), steps as u128, ); self.lcg0 = lcg as u64; self.lcg1 = (lcg >> 64) as u64; } pub fn position(&self) -> u128 { crate::lcg::get_iterations( self.multiplier_128(), self.increment_128(), self.origin_128(), self.lcg_128(), ) } pub fn set_position(&mut self, position: u128) { let lcg = crate::lcg::get_state( self.multiplier_128(), self.increment_128(), self.origin_128(), position, ); self.lcg0 = lcg as u64; self.lcg1 = (lcg >> 64) as u64; } #[inline] pub fn reset(&mut self) { self.lcg0 = self.origin_0(); self.lcg1 = 0; } #[inline] pub fn stream(&self) -> u64 { self.stream } pub fn set_stream(&mut self, stream: u64) { self.stream = stream; self.reset(); } } use super::{Error, RngCore, SeedableRng}; impl RngCore for Krull64 { fn next_u32(&mut self) -> u32 { self.step() as u32 } fn next_u64(&mut self) -> u64 { self.step() } fn fill_bytes(&mut self, dest: &mut [u8]) { let bytes = dest.len(); let mut i = 0; while i < bytes { let x = self.step(); let j = bytes.min(i + 8); dest[i..j].copy_from_slice(&x.to_le_bytes()[0..(j - i)]); i = j; } } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { self.fill_bytes(dest); Ok(()) } } impl SeedableRng for Krull64 { type Seed = [u8; 16]; fn from_seed(seed: Self::Seed) -> Self { Krull64::from_128(u128::from_le_bytes(seed)) } } #[cfg(test)] mod tests { use super::super::*; use super::*; #[test] pub fn run_tests() { let krull64_expected: [u64; 16] = [ 0x57c1b6c1df5ed4d2, 0x1efdba83398cf412, 0xa02d8dfda06ac9ce, 0xf6e3f32be5e81841, 0xc2a690083e597e0d, 0x3b1b2ed3fa6c15aa, 0x241c691340a479b2, 0x88c24c8d79bb67c1, 0x09f213c4fc2b61dc, 0xa4b6ad95c713c951, 0xa43904ae3341edf7, 0xee2dca4d5fd5f8fa, 0x27bdddbeaa4aadb0, 0x98c78e68dbf634b2, 0xf0edc57017a0d5a5, 0x8647ea5de51eca23, ]; let mut krull64 = Krull64::from_64(0); for x in krull64_expected { assert_eq!(x, krull64.next_u64()); } let mut r: u128 = 0; let mut rnd = || -> u128 { r = r.wrapping_mul(LCG_M128_1).wrapping_add(0xffff); r }; for _ in 0..1 << 12 { let seed = rnd() as u64; let mut krull1 = Krull64::new(); assert_eq!(0, krull1.stream()); assert_eq!(0, krull1.position()); krull1.set_stream(seed); assert_eq!(seed, krull1.stream()); assert_eq!(0, krull1.position()); let mut krull2 = Krull64::from_64(seed); assert_eq!(seed, krull2.stream()); assert_eq!(0, krull2.position()); let pos2 = rnd(); let pos1 = pos2 & rnd(); krull1.set_position(pos1); krull2.set_position(pos2); assert_eq!(pos1, krull1.position()); assert_eq!(pos2, krull2.position()); krull1.jump((pos2 - pos1) as i128); assert_eq!(pos2, krull1.position()); assert_eq!(krull1.next_u64(), krull2.next_u64()); krull1.jump(-1); assert_eq!(pos2, krull1.position()); krull2.jump(-1); assert_eq!(pos2, krull2.position()); krull1.jump(-((pos2 - pos1) as i128)); assert_eq!(pos1, krull1.position()); let n = 1 + (rnd() & 0x3ff); for _ in 0..n { krull1.next_u64(); } assert_eq!(pos1 + n, krull1.position()); assert_eq!(seed, krull1.stream()); let bytes = 1 + (rnd() & 0x7f); let mut buffer1 = [0u8; 0x80]; let mut buffer2 = [0u8; 0x80]; krull1.reset(); assert_eq!(0, krull1.position()); krull1.fill_bytes(&mut buffer1[0..bytes as usize]); krull2.reset(); for i in 0..0x10 { let x = krull2.next_u64(); buffer2[(i << 3)..((i + 1) << 3)].copy_from_slice(&x.to_le_bytes()); } assert!(buffer1[0..bytes as usize] .iter() .zip(buffer2[0..bytes as usize].iter()) .all(|(x, y)| x == y)); } } }
pub fn from_64(seed: u64) -> Self { Krull64 { lcg0: origin_0(seed), lcg1: 0, stream: seed, } }
function_block-full_function
[ { "content": "#[inline]\n\nfn origin_b_128() -> u128 {\n\n origin_b0() as u128\n\n}\n\n\n\nimpl Krull65 {\n\n #[inline]\n\n fn multiplier_a(&self) -> u64 {\n\n super::LCG_M65_1 as u64\n\n }\n\n\n\n #[inline]\n\n fn multiplier_a_128(&self) -> u128 {\n\n super::LCG_M65_1\n\n }\n...
Rust
compiler/src/parser/mod.rs
dvberkel/bergen
81aeb2347655590ba01f1fe813a926a3ec8d26de
use super::brnfck::Command; const NEWLINE: u8 = 10u8; pub fn parse(source: &[u8]) -> Result<Vec<Command>, ParseError> { rows(source).and_then(|(top, middle, bottom)| { if top.len() != middle.len() || middle.len() != bottom.len() { return Err(ParseError::DifferentNumberOfRows); } let mut program = vec![]; let mut column = 0; while column < top.len() { if let Some((command, next_column)) = peek(column, top, middle, bottom) { column = next_column; program.push(command); } else { return Err(ParseError::UnknownMountainRange(column)); } } Ok(program) }) } fn peek(column: usize, top: &[u8], middle: &[u8], bottom: &[u8]) -> Option<(Command, usize)> { if (column + 6) <= top.len() { if &top[column..column + 6] == " /\\ ".as_bytes() && &middle[column..column + 6] == " / \\ ".as_bytes() && &bottom[column..column + 6] == "/ \\".as_bytes() { return Some((Command::IncrementPointer, column + 6)); } } if (column + 8) <= top.len() { if &top[column..column + 8] == " /\\/\\ ".as_bytes() && &middle[column..column + 8] == " / \\ ".as_bytes() && &bottom[column..column + 8] == "/ \\".as_bytes() { return Some((Command::DecrementPointer, column + 8)); } } if (column + 4) <= top.len() { if &top[column..column + 4] == " ".as_bytes() && &middle[column..column + 4] == " /\\ ".as_bytes() && &bottom[column..column + 4] == "/ \\".as_bytes() { return Some((Command::Increment, column + 4)); } } if (column + 6) <= top.len() { if &top[column..column + 6] == " ".as_bytes() && &middle[column..column + 6] == " /\\/\\ ".as_bytes() && &bottom[column..column + 6] == "/ \\".as_bytes() { return Some((Command::Decrement, column + 6)); } } if (column + 8) <= top.len() { if &top[column..column + 8] == " /\\ ".as_bytes() && &middle[column..column + 8] == " / \\/\\ ".as_bytes() && &bottom[column..column + 8] == "/ \\".as_bytes() { return Some((Command::JumpAhead, column + 8)); } } if (column + 8) <= top.len() { if &top[column..column + 8] == " /\\ ".as_bytes() && &middle[column..column + 8] == " /\\/ \\ ".as_bytes() && &bottom[column..column + 8] == "/ \\".as_bytes() { return Some((Command::JumpBack, column + 8)); } } if (column + 2) <= top.len() { if &top[column..column + 2] == " ".as_bytes() && &middle[column..column + 2] == " ".as_bytes() && &bottom[column..column + 2] == "/\\".as_bytes() { return Some((Command::Write, column + 2)); } } if (column + 10) <= top.len() { if &top[column..column + 10] == " /\\ /\\ ".as_bytes() && &middle[column..column + 10] == " / \\/ \\ ".as_bytes() && &bottom[column..column + 10] == "/ \\".as_bytes() { return Some((Command::Read, column + 10)); } } None } fn rows(source: &[u8]) -> Result<(&[u8], &[u8], &[u8]), ParseError> { let mut index = 0; while index < source.len() && source[index] != NEWLINE { index += 1; } let first_index = index; index += 1; while index < source.len() && source[index] != NEWLINE { index += 1; } let second_index = index; index += 1; while index < source.len() && source[index] != NEWLINE { index += 1; } let third_index = index; if index < source.len() { Ok(( &source[0..first_index], &source[first_index + 1..second_index], &source[second_index + 1..third_index], )) } else { Err(ParseError::NotEnoughRows) } } #[derive(Debug, PartialEq)] pub enum ParseError { Unknown, NotEnoughRows, DifferentNumberOfRows, UnknownMountainRange(usize), } #[cfg(test)] mod tests { use super::super::brnfck::Command; use super::*; #[test] fn should_parse_empty_source() { let source: &[u8] = "\n\n\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 0); } else { assert!(false); } } #[test] fn should_parse_increment_pointer() { let source: &[u8] = " /\\ \n / \\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::IncrementPointer]) } else { assert!(false); } } #[test] fn should_parse_decrement_pointer() { let source: &[u8] = " /\\/\\ \n / \\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::DecrementPointer]) } else { assert!(false); } } #[test] fn should_parse_increment() { let source: &[u8] = " \n /\\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Increment]) } else { assert!(false); } } #[test] fn should_parse_decrement() { let source: &[u8] = " \n /\\/\\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Decrement]) } else { assert!(false); } } #[test] fn should_parse_jump_ahead() { let source: &[u8] = " /\\ \n / \\/\\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::JumpAhead]) } else { assert!(false); } } #[test] fn should_parse_jump_back() { let source: &[u8] = " /\\ \n /\\/ \\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::JumpBack]) } else { assert!(false); } } #[test] fn should_parse_write() { let source: &[u8] = " \n \n/\\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Write]) } else { assert!(false); } } #[test] fn should_parse_read() { let source: &[u8] = " /\\ /\\ \n / \\/ \\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Read]) } else { assert!(false); } } #[test] fn should_parse_program() { let source: &[u8] = " \n /\\ /\\/\\ \n/ \\/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 2); assert_eq!(instructions, vec![Command::Increment, Command::Decrement]) } else { assert!(false); } } #[test] fn should_throw_when_number_of_columns_do_not_agree() { let source: &[u8] = " \n\n\n".as_bytes(); if let Err(problem) = parse(source) { assert_eq!(problem, ParseError::DifferentNumberOfRows); } else { assert!(false); } } #[test] fn should_throw_when_there_are_to_few_rows() { let source: &[u8] = " \n\n".as_bytes(); if let Err(problem) = parse(source) { assert_eq!(problem, ParseError::NotEnoughRows); } else { assert!(false); } } }
use super::brnfck::Command; const NEWLINE: u8 = 10u8; pub fn parse(source: &[u8]) -> Result<Vec<Command>, ParseError> { rows(source).and_then(|(top, middle, bottom)| { if top.len() != middle.len() || middle.len() != bottom.len() { return Err(ParseError::DifferentNumberOfRows); } let mut program = vec![]; let mut column = 0; while column < top.len() { if let Some((command, next_column)) = peek(column, top, middle, bottom) { column = next_column; program.push(command); } else { return Err(ParseError::UnknownMountainRange(column)); } } Ok(program) }) } fn peek(column: usize, top: &[u8], middle: &[u8], bottom: &[u8]) -> Option<(Command, usize)> { if (column + 6) <= top.len() { if &top[column..column + 6] == " /\\ ".as_bytes() && &middle[column..column + 6] == " / \\ ".as_bytes() && &bottom[column..column + 6] == "/ \\".as_bytes() { return Some((Command::IncrementPointer, column + 6)); } } if (column + 8) <= top.len() { if &top[column..column + 8] == " /\\/\\ ".as_bytes() && &middle[column..column + 8] == " / \\ ".as_bytes() && &bottom[column..column + 8] == "/ \\".as_bytes() { return Some((Command::DecrementPointer, column + 8)); } } if (column + 4) <= top.len() { if &top[column..column + 4] == " ".as_bytes() && &middle[column..column + 4] == " /\\ ".as_bytes() && &bottom[column..column + 4] == "/ \\".as_bytes() { return Some((Command::Increment, column + 4)); } } if (column + 6) <= top.len() { if &top[column..column + 6] == " ".as_bytes() && &middle[column..column + 6] == " /\\/\\ ".as_bytes() && &bottom[column..column + 6] == "/ \\".as_bytes() { return Some((Command::Decrement, column + 6)); } } if (column + 8) <= top.len() { if &top[column..column + 8] == " /\\ ".as_bytes() && &middle[column..column + 8] == " / \\/\\ ".as_bytes() && &bottom[column..column + 8] == "/ \\".as_bytes() { return Some((Command::JumpAhead, column + 8)); } } if (column + 8) <= top.len() { if &top[column..column + 8] == " /\\ ".as_bytes() && &middle[column..column + 8] == " /\\/ \\ ".as_bytes() && &bottom[column..column + 8] == "/ \\".as_bytes() { return Some((Command::JumpBack, column + 8)); } } if (column + 2) <= top.len() { if &top[column..column + 2] == " ".as_bytes() && &middle[column..column + 2] == " ".as_bytes() && &bottom[column..column + 2] == "/\\".as_bytes() { return Some((Command::Write, column + 2)); } } if (column + 10) <= top.len() { if &top[column..column + 10] == " /\\ /\\ ".as_bytes() && &middle[column..column + 10] == " / \\/ \\ ".as_bytes() && &bottom[column..column + 10] == "/ \\".as_bytes() { return Some((Command::Read, column + 10)); } } None } fn rows(source: &[u8]) -> Result<(&[u8], &[u8], &[u8]), ParseError> { let mut index = 0; while index < source.len() && source[index] != NEWLINE { index += 1; } let first_index = index; index += 1; while index < source.len() && source[index] != NEWLINE { index += 1; } let second_index = index; index += 1; while index < source.len() && source[index] != NEWLINE { index += 1; } let third_index = index; if index < source.len() { Ok(( &source[0..first_index], &source[first_index + 1..second_index], &source[second_index + 1..third_index], )) } else { Err(ParseError::NotEnoughRows) } } #[derive(Debug, PartialEq)] pub enum ParseError { Unknown, NotEnoughRows, DifferentNumberOfRows, UnknownMountainRange(usize), } #[cfg(test)] mod tests { use super::super::brnfck::Command; use super::*; #[test] fn should_parse_empty_source() { let source: &[u8] = "\n\n\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 0); } else { assert!(false); } } #[test] fn should_parse_increment_pointer() { let source: &[u8] = " /\\ \n / \\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::IncrementPointer]) } else { assert!(false); } } #[test] fn should_parse_decrement_pointer() { let source: &[u8] = " /\\/\\ \n / \\ \n/ \\\n".as_bytes();
#[test] fn should_parse_increment() { let source: &[u8] = " \n /\\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Increment]) } else { assert!(false); } } #[test] fn should_parse_decrement() { let source: &[u8] = " \n /\\/\\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Decrement]) } else { assert!(false); } } #[test] fn should_parse_jump_ahead() { let source: &[u8] = " /\\ \n / \\/\\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::JumpAhead]) } else { assert!(false); } } #[test] fn should_parse_jump_back() { let source: &[u8] = " /\\ \n /\\/ \\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::JumpBack]) } else { assert!(false); } } #[test] fn should_parse_write() { let source: &[u8] = " \n \n/\\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Write]) } else { assert!(false); } } #[test] fn should_parse_read() { let source: &[u8] = " /\\ /\\ \n / \\/ \\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Read]) } else { assert!(false); } } #[test] fn should_parse_program() { let source: &[u8] = " \n /\\ /\\/\\ \n/ \\/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 2); assert_eq!(instructions, vec![Command::Increment, Command::Decrement]) } else { assert!(false); } } #[test] fn should_throw_when_number_of_columns_do_not_agree() { let source: &[u8] = " \n\n\n".as_bytes(); if let Err(problem) = parse(source) { assert_eq!(problem, ParseError::DifferentNumberOfRows); } else { assert!(false); } } #[test] fn should_throw_when_there_are_to_few_rows() { let source: &[u8] = " \n\n".as_bytes(); if let Err(problem) = parse(source) { assert_eq!(problem, ParseError::NotEnoughRows); } else { assert!(false); } } }
if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::DecrementPointer]) } else { assert!(false); } }
function_block-function_prefix_line
[ { "content": "pub fn program_from(characters: &[u8]) -> Vec<Command> {\n\n let mut program = Vec::new();\n\n let mut index = 0;\n\n let mut last_character = 0;\n\n while index < characters.len() {\n\n let mut difference = characters[index] as i16 - last_character as i16;\n\n let comman...
Rust
impl/rust/lisla_lang/src/tree/mod.rs
shohei909/Lisla
9267d0792d6d4f633dec1c079d2a39bc5e4719c1
use tag::*; use std::fmt::Debug; use from::error::*; use from::*; use ::error::*; use leaf::*; #[derive(Debug, Clone, Eq, PartialEq)] pub enum ArrayTree<LeafType:Leaf> { Array(ArrayBranch<WithTag<ArrayTree<LeafType>>>), Leaf(LeafType), } impl FromArrayTree for ArrayTree<StringLeaf> { type Parameters = (); #[allow(unused_variables)] fn from_array_tree( config:&FromArrayTreeConfig, tree:WithTag<ArrayTree<StringLeaf>>, parameters: (), errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<WithTag<ArrayTree<StringLeaf>>, ()> { Result::Ok(tree) } #[allow(unused_variables)] fn from_array_tree_array( config:&FromArrayTreeConfig, array:ArrayBranch<WithTag<ArrayTree<StringLeaf>>>, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> Result<WithTag<Self>, ()> { Result::Ok( WithTag { data: ArrayTree::Array(array), tag, } ) } #[allow(unused_variables)] fn from_array_tree_string( config:&FromArrayTreeConfig, leaf:StringLeaf, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> Result<WithTag<Self>, ()> { Result::Ok( WithTag { data: ArrayTree::Leaf(leaf), tag, } ) } #[allow(unused_variables)] fn match_array_tree_array( config:&FromArrayTreeConfig, array:ArrayBranch<WithTag<ArrayTree<StringLeaf>>>, tag:Tag, parameters: Self::Parameters, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> bool { true } #[allow(unused_variables)] fn match_array_tree_string( config:&FromArrayTreeConfig, leaf:StringLeaf, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> bool { false } } impl<LeafType:Leaf> From<ArrayBranch<WithTag<ArrayTree<LeafType>>>> for ArrayTree<LeafType> { fn from(data:ArrayBranch<WithTag<ArrayTree<LeafType>>>) -> Self { ArrayTree::Array(data) } } impl<LeafType:Leaf> ArrayTree<LeafType> { pub fn to_branch(self) -> Option<ArrayBranch<WithTag<ArrayTree<LeafType>>>> { match self { ArrayTree::Array(branch) => Option::Some(branch), ArrayTree::Leaf(_) => Option::None, } } pub fn to_leaf(self) -> Option<LeafType> { match self { ArrayTree::Array(_) => Option::None, ArrayTree::Leaf(leaf) => Option::Some(leaf), } } } pub trait Tree<LeafType> {} impl<LeafType:Leaf> Tree<LeafType> for ArrayTree<LeafType> {} #[derive(Debug, Clone, Eq, PartialEq)] pub struct ArrayBranch<TreeType:Debug + Clone> { pub vec: Vec<TreeType>, } impl<TreeType:Debug + Clone> ArrayBranch<TreeType> { #[allow(unused_variables)] pub fn shift( &mut self, config: &FromArrayTreeConfig, tag: &Tag, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<TreeType, ()> { if self.vec.len() == 0 { let range = tag.content_range.clone(); errors.push(FromArrayTreeError::from(NotEnoughArgumentsError{ range })); Result::Err(()) } else { Result::Ok( self.vec.remove(0) ) } } #[allow(unused_variables)] pub fn split_off( &mut self, config: &FromArrayTreeConfig, len:usize, tag: &Tag, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<Self, ()> { if self.vec.len() < len { let range = tag.content_range.clone(); errors.push(FromArrayTreeError::from(NotEnoughArgumentsError{ range })); Result::Err(()) } else { Result::Ok( Self { vec: self.vec.split_off(len) } ) } } pub fn split_off_rest( &mut self, config: &FromArrayTreeConfig, tag: &Tag, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<Self, ()> { let len = self.vec.len(); self.split_off(config, len, tag, errors) } #[allow(unused_variables)] pub fn finish( self, config: &FromArrayTreeConfig, tag: &Tag, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<(), ()> { if self.vec.len() == 0 { Result::Ok(()) } else { let range = tag.content_range.clone(); errors.push(FromArrayTreeError::from(TooManyArgumentsError{ range })); Result::Err(()) } } } impl<T:Debug + Clone + FromArrayTree> FromArrayTree for ArrayBranch<WithTag<T>> { type Parameters = T::Parameters; fn from_array_tree_array( config:&FromArrayTreeConfig, array:ArrayBranch<WithTag<ArrayTree<StringLeaf>>>, tag:Tag, parameters: T::Parameters, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<WithTag<ArrayBranch<WithTag<T>>>, ()> { let mut vec = Vec::new(); for element in array.vec { match FromArrayTree::from_array_tree( config, element, parameters.clone(), errors ) { Result::Ok(data) => { vec.push(data); } Result::Err(()) => {} } if config.continuous_error_limit < errors.len() { return Result::Err(()); } } Result::Ok( WithTag { data: ArrayBranch { vec }, tag } ) } #[allow(unused_variables)] fn from_array_tree_string( config:&FromArrayTreeConfig, leaf:StringLeaf, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> Result<WithTag<Self>, ()> { errors.push( FromArrayTreeError::from( CantBeStringError { range: tag.content_range } ) ); Result::Err(()) } #[allow(unused_variables)] fn match_array_tree_array( config:&FromArrayTreeConfig, array:ArrayBranch<WithTag<ArrayTree<StringLeaf>>>, tag:Tag, parameters: T::Parameters, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> bool { true } #[allow(unused_variables)] fn match_array_tree_string( config:&FromArrayTreeConfig, leaf:StringLeaf, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> bool { false } }
use tag::*; use std::fmt::Debug; use from::error::*; use from::*; use ::error::*; use leaf::*; #[derive(Debug, Clone, Eq, PartialEq)] pub enum ArrayTree<LeafType:Leaf> { Array(ArrayBranch<WithTag<ArrayTree<LeafType>>>), Leaf(LeafType), } impl FromArrayTree for ArrayTree<StringLeaf> { type Parameters = (); #[allow(unused_variables)] fn from_array_tree( config:&FromArrayTreeConfig, tree:WithTag<ArrayTree<StringLeaf>>, parameters: (), errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<WithTag<ArrayTree<StringLeaf>>, ()> { Result::Ok(tree) } #[allow(unused_variables)] fn from_array_tree_array( config:&FromArrayTreeConfig, array:ArrayBranch<WithTag<ArrayTree<StringLeaf>>>, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> Result<WithTag<Self>, ()> { Result::Ok( WithTag { data: ArrayTree::Array(array), tag, } ) } #[allow(unused_variables)] fn from_array_tree_string( config:&FromArrayTreeConfig, leaf:StringLeaf, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> Result<WithTag<Self>, ()> { Result::Ok( WithTag { data: ArrayTree::Leaf(leaf), tag, } ) } #[allow(unused_variables)] fn match_array_tree_array( config:&FromArrayTreeConfig, array:ArrayBranch<WithTag<ArrayTree<StringLeaf>>>, tag:Tag, parameters: Self::Parameters, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> bool { true } #[allow(unused_variables)] fn match_array_tree_string( config:&FromArrayTreeConfig, leaf:StringLeaf, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> bool { false } } impl<LeafType:Leaf> From<ArrayBranch<WithTag<ArrayTree<LeafType>>>> for Arr
errors.push(FromArrayTreeError::from(NotEnoughArgumentsError{ range })); Result::Err(()) } else { Result::Ok( Self { vec: self.vec.split_off(len) } ) } } pub fn split_off_rest( &mut self, config: &FromArrayTreeConfig, tag: &Tag, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<Self, ()> { let len = self.vec.len(); self.split_off(config, len, tag, errors) } #[allow(unused_variables)] pub fn finish( self, config: &FromArrayTreeConfig, tag: &Tag, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<(), ()> { if self.vec.len() == 0 { Result::Ok(()) } else { let range = tag.content_range.clone(); errors.push(FromArrayTreeError::from(TooManyArgumentsError{ range })); Result::Err(()) } } } impl<T:Debug + Clone + FromArrayTree> FromArrayTree for ArrayBranch<WithTag<T>> { type Parameters = T::Parameters; fn from_array_tree_array( config:&FromArrayTreeConfig, array:ArrayBranch<WithTag<ArrayTree<StringLeaf>>>, tag:Tag, parameters: T::Parameters, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<WithTag<ArrayBranch<WithTag<T>>>, ()> { let mut vec = Vec::new(); for element in array.vec { match FromArrayTree::from_array_tree( config, element, parameters.clone(), errors ) { Result::Ok(data) => { vec.push(data); } Result::Err(()) => {} } if config.continuous_error_limit < errors.len() { return Result::Err(()); } } Result::Ok( WithTag { data: ArrayBranch { vec }, tag } ) } #[allow(unused_variables)] fn from_array_tree_string( config:&FromArrayTreeConfig, leaf:StringLeaf, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> Result<WithTag<Self>, ()> { errors.push( FromArrayTreeError::from( CantBeStringError { range: tag.content_range } ) ); Result::Err(()) } #[allow(unused_variables)] fn match_array_tree_array( config:&FromArrayTreeConfig, array:ArrayBranch<WithTag<ArrayTree<StringLeaf>>>, tag:Tag, parameters: T::Parameters, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> bool { true } #[allow(unused_variables)] fn match_array_tree_string( config:&FromArrayTreeConfig, leaf:StringLeaf, tag:Tag, parameters: Self::Parameters, errors:&mut ErrorWrite<FromArrayTreeError> ) -> bool { false } }
ayTree<LeafType> { fn from(data:ArrayBranch<WithTag<ArrayTree<LeafType>>>) -> Self { ArrayTree::Array(data) } } impl<LeafType:Leaf> ArrayTree<LeafType> { pub fn to_branch(self) -> Option<ArrayBranch<WithTag<ArrayTree<LeafType>>>> { match self { ArrayTree::Array(branch) => Option::Some(branch), ArrayTree::Leaf(_) => Option::None, } } pub fn to_leaf(self) -> Option<LeafType> { match self { ArrayTree::Array(_) => Option::None, ArrayTree::Leaf(leaf) => Option::Some(leaf), } } } pub trait Tree<LeafType> {} impl<LeafType:Leaf> Tree<LeafType> for ArrayTree<LeafType> {} #[derive(Debug, Clone, Eq, PartialEq)] pub struct ArrayBranch<TreeType:Debug + Clone> { pub vec: Vec<TreeType>, } impl<TreeType:Debug + Clone> ArrayBranch<TreeType> { #[allow(unused_variables)] pub fn shift( &mut self, config: &FromArrayTreeConfig, tag: &Tag, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<TreeType, ()> { if self.vec.len() == 0 { let range = tag.content_range.clone(); errors.push(FromArrayTreeError::from(NotEnoughArgumentsError{ range })); Result::Err(()) } else { Result::Ok( self.vec.remove(0) ) } } #[allow(unused_variables)] pub fn split_off( &mut self, config: &FromArrayTreeConfig, len:usize, tag: &Tag, errors: &mut ErrorWrite<FromArrayTreeError>, ) -> Result<Self, ()> { if self.vec.len() < len { let range = tag.content_range.clone();
random
[ { "content": "pub trait Leaf : Debug + Clone + Eq + PartialEq {\n\n}\n", "file_path": "impl/rust/lisla_lang/src/leaf/mod.rs", "rank": 0, "score": 241863.12455578276 }, { "content": "pub fn equals(lisla: &WithTag<ArrayTree<StringLeaf>>, json: &Value, path: &str, stack: &mut Vec<usize>) {\n\n ...
Rust
sulis_state/src/animation/ranged_attack_animation.rs
ThyWoof/sulis
e89eda94a1a72228224e1926d307aa4c9228bdcb
use std::cell::RefCell; use std::rc::Rc; use crate::{animation::Anim, entity_attack_handler::weapon_attack, AreaFeedbackText}; use crate::{script::ScriptEntitySet, EntityState, GameState, ScriptCallback}; use sulis_core::image::Image; use sulis_core::io::{DrawList, GraphicsRenderer}; use sulis_core::ui::animation_state; use sulis_core::util::{Offset, Rect, Scale}; pub(in crate::animation) fn update( attacker: &Rc<RefCell<EntityState>>, model: &mut RangedAttackAnimModel, frac: f32, ) { if frac > 1.0 { if !model.has_attacked { let cb_def_targets = ScriptEntitySet::new(&model.defender, &[Some(Rc::clone(attacker))]); let cb_att_targets = ScriptEntitySet::new(attacker, &[Some(Rc::clone(&model.defender))]); for cb in model.callbacks.iter() { cb.before_attack(&cb_def_targets); } let area_state = GameState::area_state(); let (defender_cbs, attacker_cbs) = { let mgr = GameState::turn_manager(); let mgr = mgr.borrow(); ( model.defender.borrow().callbacks(&mgr), attacker.borrow().callbacks(&mgr), ) }; attacker_cbs .iter() .for_each(|cb| cb.before_attack(&cb_att_targets)); defender_cbs .iter() .for_each(|cb| cb.before_defense(&cb_def_targets)); model.has_attacked = true; let result = weapon_attack(attacker, &model.defender); for entry in result { let (hit_kind, hit_flags, damage) = entry; let feedback = AreaFeedbackText::with_damage( &model.defender.borrow(), &area_state.borrow(), hit_kind, hit_flags, &damage, ); area_state.borrow_mut().add_feedback_text(feedback); for cb in model.callbacks.iter() { cb.after_attack(&cb_def_targets, hit_kind, damage.clone()); } attacker_cbs .iter() .for_each(|cb| cb.after_attack(&cb_att_targets, hit_kind, damage.clone())); defender_cbs .iter() .for_each(|cb| cb.after_defense(&cb_def_targets, hit_kind, damage.clone())); } } } else { model.cur_pos = ( frac * model.vec.0 + model.start_pos.0, frac * model.vec.1 + model.start_pos.1, ); } } pub(in crate::animation) fn cleanup(owner: &Rc<RefCell<EntityState>>) { if !GameState::is_combat_active() { let area_state = GameState::get_area_state(&owner.borrow().location.area_id).unwrap(); let mgr = GameState::turn_manager(); mgr.borrow_mut() .check_ai_activation(owner, &mut area_state.borrow_mut()); } } pub(in crate::animation) fn draw( model: &RangedAttackAnimModel, renderer: &mut dyn GraphicsRenderer, offset: Offset, scale: Scale, millis: u32, ) { if let Some(ref projectile) = model.projectile { let rect = Rect { x: model.cur_pos.0 + offset.x, y: model.cur_pos.1 + offset.y, w: projectile.get_width_f32(), h: projectile.get_height_f32(), }; let mut draw_list = DrawList::empty_sprite(); projectile.append_to_draw_list(&mut draw_list, &animation_state::NORMAL, rect, millis); draw_list.set_scale(scale); draw_list.rotate(model.angle); renderer.draw(draw_list); } } pub fn new( attacker: &Rc<RefCell<EntityState>>, defender: &Rc<RefCell<EntityState>>, callbacks: Vec<Box<dyn ScriptCallback>>, duration_millis: u32, ) -> Anim { let mut start_pos = ( (attacker.borrow().location.x + attacker.borrow().size.width / 2) as f32, (attacker.borrow().location.y + attacker.borrow().size.height / 2) as f32, ); let x = (defender.borrow().location.x + defender.borrow().size.width / 2) as f32 - start_pos.0; let y = (defender.borrow().location.y + defender.borrow().size.height / 2) as f32 - start_pos.1; let dist = (x * x + y * y).sqrt(); let projectile = attacker.borrow().actor.stats.get_ranged_projectile(); if let Some(ref projectile) = projectile { start_pos.0 -= projectile.get_width_f32() / 2.0; start_pos.1 -= projectile.get_height_f32() / 2.0; } let angle = y.atan2(x); let model = RangedAttackAnimModel { defender: Rc::clone(defender), angle, vec: (x, y), start_pos, cur_pos: (0.0, 0.0), has_attacked: false, projectile, callbacks, }; let millis = (duration_millis as f32 * dist) as u32; Anim::new_ranged_attack(attacker, millis, model) } pub(in crate::animation) struct RangedAttackAnimModel { defender: Rc<RefCell<EntityState>>, angle: f32, vec: (f32, f32), start_pos: (f32, f32), cur_pos: (f32, f32), pub(in crate::animation) has_attacked: bool, projectile: Option<Rc<dyn Image>>, callbacks: Vec<Box<dyn ScriptCallback>>, }
use std::cell::RefCell; use std::rc::Rc; use crate::{animation::Anim, entity_attack_handler::weapon_attack, AreaFeedbackText}; use crate::{script::ScriptEntitySet, EntityState, GameState, ScriptCallback}; use sulis_core::image::Image; use sulis_core::io::{DrawList, GraphicsRenderer}; use sulis_core::ui::animation_state; use sulis_core::util::{Offset, Rect, Scale}; pub(in crate::animation) fn update( attacker: &Rc<RefCell<EntityState>>, model: &mut RangedAttackAnimModel, frac: f32, ) { if frac > 1.0 { if !model.has_attacked { let cb_def_targets = ScriptEntitySet::new(&model.defender, &[Some(Rc::clone(attacker))]); let cb_att_targets = ScriptEntitySet::new(attacker, &[Some(Rc::clone(&model.defender))]); for cb in model.callbacks.iter() { cb.before_attack(&cb_def_targets); } let area_state = GameState::area_state(); let (defender_cbs, attacker_cbs) = { let mgr = GameState::turn_manager(); let mgr = mgr.borrow(); ( model.defender.borrow().callbacks(&mgr), attacker.borrow().callbacks(&mgr), ) }; attacker_cbs .iter() .for_each(|cb| cb.before_attack(&cb_att_targets)); defender_cbs .iter() .for_each(|cb| cb.before_defense(&cb_def_targets)); model.has_attacked = true; let result = weapon_attack(attacker, &model.defender); for entry in result { let (hit_kind, hit_flags, damage) = entry; let feedback = AreaFeedbackText::with_damage( &model.defender.borrow(), &area_state.borrow(), hit_kind, hit_flags, &damage, ); area_state.borrow_mut().add_feedback_text(feedback); for cb in model.callbacks.iter() { cb.after_attack(&cb_def_targets, hit_kind, damage.clone()); } attacker_cbs .iter() .for_each(|cb| cb.after_attack(&cb_att_targets, hit_kind, damage.clone())); defender_cbs .iter() .for_each(|cb| cb.after_defense(&cb_def_targets, hit_kind, damage.clone())); } } } else { model.cur_pos = ( frac * model.vec.0 + model.start_pos.0, frac * model.vec.1 + model.start_pos.1, ); } } pub(in crate::animation) fn cleanup(owner: &Rc<RefCell<EntityState>>) {
} pub(in crate::animation) fn draw( model: &RangedAttackAnimModel, renderer: &mut dyn GraphicsRenderer, offset: Offset, scale: Scale, millis: u32, ) { if let Some(ref projectile) = model.projectile { let rect = Rect { x: model.cur_pos.0 + offset.x, y: model.cur_pos.1 + offset.y, w: projectile.get_width_f32(), h: projectile.get_height_f32(), }; let mut draw_list = DrawList::empty_sprite(); projectile.append_to_draw_list(&mut draw_list, &animation_state::NORMAL, rect, millis); draw_list.set_scale(scale); draw_list.rotate(model.angle); renderer.draw(draw_list); } } pub fn new( attacker: &Rc<RefCell<EntityState>>, defender: &Rc<RefCell<EntityState>>, callbacks: Vec<Box<dyn ScriptCallback>>, duration_millis: u32, ) -> Anim { let mut start_pos = ( (attacker.borrow().location.x + attacker.borrow().size.width / 2) as f32, (attacker.borrow().location.y + attacker.borrow().size.height / 2) as f32, ); let x = (defender.borrow().location.x + defender.borrow().size.width / 2) as f32 - start_pos.0; let y = (defender.borrow().location.y + defender.borrow().size.height / 2) as f32 - start_pos.1; let dist = (x * x + y * y).sqrt(); let projectile = attacker.borrow().actor.stats.get_ranged_projectile(); if let Some(ref projectile) = projectile { start_pos.0 -= projectile.get_width_f32() / 2.0; start_pos.1 -= projectile.get_height_f32() / 2.0; } let angle = y.atan2(x); let model = RangedAttackAnimModel { defender: Rc::clone(defender), angle, vec: (x, y), start_pos, cur_pos: (0.0, 0.0), has_attacked: false, projectile, callbacks, }; let millis = (duration_millis as f32 * dist) as u32; Anim::new_ranged_attack(attacker, millis, model) } pub(in crate::animation) struct RangedAttackAnimModel { defender: Rc<RefCell<EntityState>>, angle: f32, vec: (f32, f32), start_pos: (f32, f32), cur_pos: (f32, f32), pub(in crate::animation) has_attacked: bool, projectile: Option<Rc<dyn Image>>, callbacks: Vec<Box<dyn ScriptCallback>>, }
if !GameState::is_combat_active() { let area_state = GameState::get_area_state(&owner.borrow().location.area_id).unwrap(); let mgr = GameState::turn_manager(); mgr.borrow_mut() .check_ai_activation(owner, &mut area_state.borrow_mut()); }
if_condition
[]
Rust
rs/crypto/internal/crypto_service_provider/src/server/local_csp_server/basic_sig/tests.rs
LaudateCorpus1/ic
e05b8568bcef4147b5999d2c489f875afde2f8bb
use crate::api::CspSigner; use crate::imported_test_utils::ed25519::csp_testvec; use crate::secret_key_store::test_utils::TempSecretKeyStore; use crate::secret_key_store::SecretKeyStore; use crate::server::api::{ BasicSignatureCspServer, CspBasicSignatureError, CspBasicSignatureKeygenError, }; use crate::server::local_csp_server::LocalCspServer; use crate::Csp; use ic_crypto_internal_test_vectors::ed25519::Ed25519TestVector::RFC8032_ED25519_SHA_ABC; use ic_types::crypto::{AlgorithmId, KeyId}; use ic_types::NumberOfNodes; use rand::{thread_rng, Rng, SeedableRng}; use rand_chacha::ChaChaRng; use strum::IntoEnumIterator; #[test] fn should_generate_key_ok() { let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(thread_rng().gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; assert!(csp_server.gen_key_pair(AlgorithmId::Ed25519).is_ok()); } #[test] fn should_fail_to_generate_key_for_wrong_algorithm_id() { let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(thread_rng().gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; for algorithm_id in AlgorithmId::iter() { if algorithm_id != AlgorithmId::Ed25519 { assert_eq!( csp_server.gen_key_pair(algorithm_id).unwrap_err(), CspBasicSignatureKeygenError::UnsupportedAlgorithm { algorithm: algorithm_id, } ); } } } #[test] fn should_correctly_sign_compared_to_testvec() { let mut rng = thread_rng(); let key_id = rng.gen::<[u8; 32]>(); let (sk, _pk, msg, sig) = csp_testvec(RFC8032_ED25519_SHA_ABC); let csp_server = { let mut key_store = TempSecretKeyStore::new(); key_store .insert(KeyId::from(key_id), sk, None) .expect("failed to insert key into SKS"); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; assert_eq!( csp_server .sign(AlgorithmId::Ed25519, &msg, KeyId::from(key_id)) .expect("failed to create signature"), sig ); } #[test] fn should_sign_ok_with_generated_key() { let mut rng = thread_rng(); let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; let (key_id, _csp_pub_key) = csp_server .gen_key_pair(AlgorithmId::Ed25519) .expect("failed to generate keys"); let msg_len: usize = rng.gen_range(0, 1024); let msg: Vec<u8> = (0..msg_len).map(|_| rng.gen::<u8>()).collect(); assert!(csp_server.sign(AlgorithmId::Ed25519, &msg, key_id).is_ok()); } #[test] fn should_sign_verifiably_with_generated_key() { let mut rng = thread_rng(); let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; let (key_id, csp_pub_key) = csp_server .gen_key_pair(AlgorithmId::Ed25519) .expect("failed to generate keys"); let msg_len: usize = rng.gen_range(0, 1024); let msg: Vec<u8> = (0..msg_len).map(|_| rng.gen::<u8>()).collect(); let sig = csp_server .sign(AlgorithmId::Ed25519, &msg, key_id) .expect("failed to generate signature"); let verifier = { let dummy_key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); Csp::of(csprng, dummy_key_store) }; assert!(verifier .verify(&sig, &msg, AlgorithmId::Ed25519, csp_pub_key) .is_ok()); } #[test] fn should_fail_to_sign_with_unsupported_algorithm_id() { let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(thread_rng().gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; let (key_id, _csp_pub_key) = csp_server .gen_key_pair(AlgorithmId::Ed25519) .expect("failed to generate keys"); let msg = [31; 41]; for algorithm_id in AlgorithmId::iter() { if algorithm_id != AlgorithmId::Ed25519 { assert_eq!( csp_server.sign(algorithm_id, &msg, key_id).unwrap_err(), CspBasicSignatureError::UnsupportedAlgorithm { algorithm: algorithm_id, } ); } } } #[test] fn should_fail_to_sign_if_secret_key_in_store_has_wrong_type() { use crate::server::api::ThresholdSignatureCspServer; let mut rng = thread_rng(); let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; let threshold = NumberOfNodes::from(1); let (_pub_coeffs, key_ids) = csp_server .threshold_keygen_for_test(AlgorithmId::ThresBls12_381, threshold, &[true]) .expect("failed to generate threshold sig keys"); let key_id = key_ids[0].expect("threshold sig key not generated"); let msg_len: usize = rng.gen_range(0, 1024); let msg: Vec<u8> = (0..msg_len).map(|_| rng.gen::<u8>()).collect(); let result = csp_server.sign(AlgorithmId::Ed25519, &msg, key_id); assert_eq!( result.unwrap_err(), CspBasicSignatureError::WrongSecretKeyType { algorithm: AlgorithmId::ThresBls12_381 } ); }
use crate::api::CspSigner; use crate::imported_test_utils::ed25519::csp_testvec; use crate::secret_key_store::test_utils::TempSecretKeyStore; use crate::secret_key_store::SecretKeyStore; use crate::server::api::{ BasicSignatureCspServer, CspBasicSignatureError, CspBasicSignatureKeygenError, }; use crate::server::local_csp_server::LocalCspServer; use crate::Csp; use ic_crypto_internal_test_vectors::ed25519::Ed25519TestVector::RFC8032_ED25519_SHA_ABC; use ic_types::crypto::{AlgorithmId, KeyId}; use ic_types::NumberOfNodes; use rand::{thread_rng, Rng, SeedableRng}; use rand_chacha::ChaChaRng; use strum::IntoEnumIterator; #[test]
#[test] fn should_fail_to_generate_key_for_wrong_algorithm_id() { let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(thread_rng().gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; for algorithm_id in AlgorithmId::iter() { if algorithm_id != AlgorithmId::Ed25519 { assert_eq!( csp_server.gen_key_pair(algorithm_id).unwrap_err(), CspBasicSignatureKeygenError::UnsupportedAlgorithm { algorithm: algorithm_id, } ); } } } #[test] fn should_correctly_sign_compared_to_testvec() { let mut rng = thread_rng(); let key_id = rng.gen::<[u8; 32]>(); let (sk, _pk, msg, sig) = csp_testvec(RFC8032_ED25519_SHA_ABC); let csp_server = { let mut key_store = TempSecretKeyStore::new(); key_store .insert(KeyId::from(key_id), sk, None) .expect("failed to insert key into SKS"); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; assert_eq!( csp_server .sign(AlgorithmId::Ed25519, &msg, KeyId::from(key_id)) .expect("failed to create signature"), sig ); } #[test] fn should_sign_ok_with_generated_key() { let mut rng = thread_rng(); let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; let (key_id, _csp_pub_key) = csp_server .gen_key_pair(AlgorithmId::Ed25519) .expect("failed to generate keys"); let msg_len: usize = rng.gen_range(0, 1024); let msg: Vec<u8> = (0..msg_len).map(|_| rng.gen::<u8>()).collect(); assert!(csp_server.sign(AlgorithmId::Ed25519, &msg, key_id).is_ok()); } #[test] fn should_sign_verifiably_with_generated_key() { let mut rng = thread_rng(); let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; let (key_id, csp_pub_key) = csp_server .gen_key_pair(AlgorithmId::Ed25519) .expect("failed to generate keys"); let msg_len: usize = rng.gen_range(0, 1024); let msg: Vec<u8> = (0..msg_len).map(|_| rng.gen::<u8>()).collect(); let sig = csp_server .sign(AlgorithmId::Ed25519, &msg, key_id) .expect("failed to generate signature"); let verifier = { let dummy_key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); Csp::of(csprng, dummy_key_store) }; assert!(verifier .verify(&sig, &msg, AlgorithmId::Ed25519, csp_pub_key) .is_ok()); } #[test] fn should_fail_to_sign_with_unsupported_algorithm_id() { let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(thread_rng().gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; let (key_id, _csp_pub_key) = csp_server .gen_key_pair(AlgorithmId::Ed25519) .expect("failed to generate keys"); let msg = [31; 41]; for algorithm_id in AlgorithmId::iter() { if algorithm_id != AlgorithmId::Ed25519 { assert_eq!( csp_server.sign(algorithm_id, &msg, key_id).unwrap_err(), CspBasicSignatureError::UnsupportedAlgorithm { algorithm: algorithm_id, } ); } } } #[test] fn should_fail_to_sign_if_secret_key_in_store_has_wrong_type() { use crate::server::api::ThresholdSignatureCspServer; let mut rng = thread_rng(); let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(rng.gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; let threshold = NumberOfNodes::from(1); let (_pub_coeffs, key_ids) = csp_server .threshold_keygen_for_test(AlgorithmId::ThresBls12_381, threshold, &[true]) .expect("failed to generate threshold sig keys"); let key_id = key_ids[0].expect("threshold sig key not generated"); let msg_len: usize = rng.gen_range(0, 1024); let msg: Vec<u8> = (0..msg_len).map(|_| rng.gen::<u8>()).collect(); let result = csp_server.sign(AlgorithmId::Ed25519, &msg, key_id); assert_eq!( result.unwrap_err(), CspBasicSignatureError::WrongSecretKeyType { algorithm: AlgorithmId::ThresBls12_381 } ); }
fn should_generate_key_ok() { let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(thread_rng().gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; assert!(csp_server.gen_key_pair(AlgorithmId::Ed25519).is_ok()); }
function_block-full_function
[ { "content": "/// Generate a random `IDkgId`.\n\n///\n\n/// Note: There is a proptest strategy for `IDkgId` which is useful in many\n\n/// circumstances but cumbersome in others. Please use the appropriate method\n\n/// for each circumstance.\n\npub fn random_dkg_id<R: Rng>(rng: &mut R) -> IDkgId {\n\n let ...
Rust
src/sim/render/lighting.rs
FreddyWordingham/arctk
05842d8a5842653179acaaf2a7de843ed9293b82
use crate::{ geom::Ray, math::{rand_circle_point, rand_hemisphere_point, Dir3}, phys::Crossing, sim::render::{Attribute, Input}, }; use rand::{rngs::ThreadRng, Rng}; use std::f64::consts::PI; #[inline] #[must_use] pub fn light(input: &Input, ray: &Ray, norm: &Dir3) -> f64 { let light_dir = Dir3::new_normalize(input.shader.sun_pos() - ray.pos()); let view_dir = Dir3::new_normalize(input.cam.pos() - ray.pos()); let ref_dir = Crossing::calc_ref_dir(ray.dir(), norm); let [ambient, mut diffuse, mut specular] = input.shader.light(); diffuse *= norm.dot(&light_dir); specular *= view_dir .dot(&ref_dir) .max(0.0) .powi(input.shader.spec_pow()); ambient + diffuse + specular } #[inline] #[must_use] pub fn shadow(input: &Input, rng: &mut ThreadRng, ray: &Ray, norm: &Dir3) -> f64 { let bump_dist = input.sett.bump_dist(); let sun_dir = Dir3::new_normalize(input.shader.sun_pos() - ray.pos()); let mut light_ray = Ray::new(*ray.pos(), *norm); light_ray.travel(bump_dist); *light_ray.dir_mut() = sun_dir; let solar = if let Some((samples, rad)) = input.shader.soft_shadow_samples() { let offset = rng.gen_range(0.0..(2.0 * PI)); let mut total = 0.0; for n in 0..samples { let (r, theta) = rand_circle_point(n, samples); let mut soft_ray = light_ray.clone(); soft_ray.rotate(r * rad, theta + offset); total += occlusion(input, soft_ray, input.shader.occ_dist()[1]); } total / f64::from(samples) } else { occlusion(input, light_ray, input.shader.occ_dist()[1]) }; if let Some((samples, power)) = input.shader.ambient_shadow_samples() { let offset = rng.gen_range(0.0..(2.0 * PI)); let mut total = 0.0; let mut norm_ray = Ray::new(*ray.pos(), *norm); norm_ray.travel(bump_dist); for n in 0..samples { let (phi, theta) = rand_hemisphere_point(n, samples); let mut ambient_ray = norm_ray.clone(); ambient_ray.rotate(phi, theta + offset); total += occlusion(input, ambient_ray, input.shader.occ_dist()[1]); } let ambient = (total / f64::from(samples)).powi(power); return ambient.mul_add(input.shader.shadow()[0], solar * input.shader.shadow()[1]); }; solar } #[inline] #[must_use] pub fn occlusion(input: &Input, mut ray: Ray, mut dist: f64) -> f64 { debug_assert!(dist > 0.0); let bump_dist = input.sett.bump_dist(); let loop_limit = input.sett.loop_limit(); let min_weight = input.sett.min_weight(); let mut vis = 1.0; let mut num_loops = 0; while let Some(hit) = input.tree.scan(ray.clone(), bump_dist, dist) { if num_loops >= loop_limit { println!("[WARN] : Terminating shadower: loop limit reached."); return 0.0; } num_loops += 1; dist -= hit.dist(); if dist < 0.0 { return vis; } if vis < min_weight { return 0.0; } match *hit.tag() { Attribute::Opaque(..) | Attribute::Switchable(..) => { return vis / dist.mul_add(input.shader.fall_off(), 1.0); } Attribute::Mirror(.., abs_frac) => { ray.travel(dist); vis *= 1.0 - abs_frac; *ray.dir_mut() = Crossing::calc_ref_dir(ray.dir(), hit.side().norm()); ray.travel(bump_dist); } Attribute::Transparent(.., abs_frac) => { ray.travel(dist + bump_dist); vis *= 1.0 - abs_frac; } Attribute::Refractive(.., abs_frac, [_inside, _outside]) => { ray.travel(dist + bump_dist); vis *= 1.0 - abs_frac; } Attribute::Luminous(.., bright_mult) => { return (vis * bright_mult) / dist.mul_add(input.shader.fall_off(), 1.0); } } } vis }
use crate::{ geom::Ray, math::{rand_circle_point, rand_hemisphere_point, Dir3}, phys::Crossing, sim::render::{Attribute, Input}, }; use rand::{rngs::ThreadRng, Rng}; use std::f64::consts::PI; #[inline] #[must_use] pub fn light(input: &Input, ray: &Ray, norm: &Dir3) -> f64 { let light_dir = Dir3::new_normalize(input.shader.sun_pos() - ray.pos()); let view_dir = Dir3::new_normalize(input.cam.pos() - ray.pos()); let ref_dir = Crossing::calc_ref_dir(ray.dir(), norm); let [ambient, mut diffuse, mut specular] = input.shader.light();
#[inline] #[must_use] pub fn shadow(input: &Input, rng: &mut ThreadRng, ray: &Ray, norm: &Dir3) -> f64 { let bump_dist = input.sett.bump_dist(); let sun_dir = Dir3::new_normalize(input.shader.sun_pos() - ray.pos()); let mut light_ray = Ray::new(*ray.pos(), *norm); light_ray.travel(bump_dist); *light_ray.dir_mut() = sun_dir; let solar = if let Some((samples, rad)) = input.shader.soft_shadow_samples() { let offset = rng.gen_range(0.0..(2.0 * PI)); let mut total = 0.0; for n in 0..samples { let (r, theta) = rand_circle_point(n, samples); let mut soft_ray = light_ray.clone(); soft_ray.rotate(r * rad, theta + offset); total += occlusion(input, soft_ray, input.shader.occ_dist()[1]); } total / f64::from(samples) } else { occlusion(input, light_ray, input.shader.occ_dist()[1]) }; if let Some((samples, power)) = input.shader.ambient_shadow_samples() { let offset = rng.gen_range(0.0..(2.0 * PI)); let mut total = 0.0; let mut norm_ray = Ray::new(*ray.pos(), *norm); norm_ray.travel(bump_dist); for n in 0..samples { let (phi, theta) = rand_hemisphere_point(n, samples); let mut ambient_ray = norm_ray.clone(); ambient_ray.rotate(phi, theta + offset); total += occlusion(input, ambient_ray, input.shader.occ_dist()[1]); } let ambient = (total / f64::from(samples)).powi(power); return ambient.mul_add(input.shader.shadow()[0], solar * input.shader.shadow()[1]); }; solar } #[inline] #[must_use] pub fn occlusion(input: &Input, mut ray: Ray, mut dist: f64) -> f64 { debug_assert!(dist > 0.0); let bump_dist = input.sett.bump_dist(); let loop_limit = input.sett.loop_limit(); let min_weight = input.sett.min_weight(); let mut vis = 1.0; let mut num_loops = 0; while let Some(hit) = input.tree.scan(ray.clone(), bump_dist, dist) { if num_loops >= loop_limit { println!("[WARN] : Terminating shadower: loop limit reached."); return 0.0; } num_loops += 1; dist -= hit.dist(); if dist < 0.0 { return vis; } if vis < min_weight { return 0.0; } match *hit.tag() { Attribute::Opaque(..) | Attribute::Switchable(..) => { return vis / dist.mul_add(input.shader.fall_off(), 1.0); } Attribute::Mirror(.., abs_frac) => { ray.travel(dist); vis *= 1.0 - abs_frac; *ray.dir_mut() = Crossing::calc_ref_dir(ray.dir(), hit.side().norm()); ray.travel(bump_dist); } Attribute::Transparent(.., abs_frac) => { ray.travel(dist + bump_dist); vis *= 1.0 - abs_frac; } Attribute::Refractive(.., abs_frac, [_inside, _outside]) => { ray.travel(dist + bump_dist); vis *= 1.0 - abs_frac; } Attribute::Luminous(.., bright_mult) => { return (vis * bright_mult) / dist.mul_add(input.shader.fall_off(), 1.0); } } } vis }
diffuse *= norm.dot(&light_dir); specular *= view_dir .dot(&ref_dir) .max(0.0) .powi(input.shader.spec_pow()); ambient + diffuse + specular }
function_block-function_prefix_line
[ { "content": "#[inline]\n\n#[must_use]\n\npub fn sample_normal<R: Rng>(rng: &mut R) -> f64 {\n\n let a = (-2.0 * rng.gen_range(0.0_f64..1.0).ln()).sqrt();\n\n let theta = rng.gen_range(0.0..(2.0 * PI));\n\n\n\n // Z = Some(a * theta.sin()); // Using mutable static will lead to data race; we waste the t...
Rust
pseudos/src/main.rs
yokljo/pseudos
a16a66bd4a0edc48100e3d5e285ef897b8699375
use std::cmp::Ordering; use libpseudos::dos_event_handler::{DosEventHandler, DosInterruptResult, KeyModType, KeyPressInfo, MachineType, PortStates}; use libpseudos::dos_file_system::StandardDosFileSystem; use libpseudos::exe_loader::MzHeader; use xachtsechs::machine8086::Machine8086; use xachtsechs::types::{Reg, RegHalf, StepResult}; use sdl2::image::{LoadTexture, INIT_PNG}; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::rect::Rect; use sdl2::render::{WindowCanvas, Texture}; use sdl2::audio::AudioSpecDesired; use std::time::{SystemTime, UNIX_EPOCH}; use std::path::Path; const SCANCODE_LETTERS: &[u8] = b"qwertyuiopasdfghjklzxcvbnm"; fn scancode_to_key_info(keycode: Keycode, shifted: bool) -> Option<KeyPressInfo> { let key_index = keycode as u8; let (scan_code, ascii_char, shifted_ascii_char) = match keycode { _ if (b'a' ..= b'z').contains(&(keycode as u8)) => { let lower_ascii_char = SCANCODE_LETTERS.iter().position(|c| *c == key_index).unwrap() as u8 + 0x10; (lower_ascii_char, key_index, key_index + 0x20) } Keycode::Num0 => (0x0b, 0x30, 0x29), Keycode::Num1 => (0x02, 0x31, 0x21), Keycode::Num2 => (0x03, 0x32, 0x40), Keycode::Num3 => (0x04, 0x33, 0x23), Keycode::Num4 => (0x05, 0x34, 0x24), Keycode::Num5 => (0x06, 0x35, 0x25), Keycode::Num6 => (0x07, 0x36, 0x5e), Keycode::Num7 => (0x08, 0x37, 0x26), Keycode::Num8 => (0x09, 0x38, 0x2a), Keycode::Num9 => (0x0a, 0x39, 0x28), Keycode::Backspace => (0x0e, 0x08, 0x08), Keycode::Delete => (0x53, 0x00, 0x2e), Keycode::Insert => (0x52, 0x00, 0x30), Keycode::Slash => (0x35, 0x2f, 0x3f), Keycode::Down => (0x50, 0, 0x32), Keycode::Up => (0x48, 0, 0x38), Keycode::Left => (0x4b, 0, 0x34), Keycode::Right => (0x4d, 0, 0x36), Keycode::Return => (0x1c, 0x0d, 0x0d), Keycode::Escape => (0x01, 0x1b, 0x1b), Keycode::Space => (0x39, 0x20, 0x20), Keycode::Tab => (0x0f, 0x09, 0), Keycode::PageUp => (0x49, 0, 0x39), Keycode::PageDown => (0x51, 0, 0x33), _ if (Keycode::F1 as u8 ..= Keycode::F12 as u8).contains(&(keycode as u8)) => { (0x3b + (keycode as u8 - Keycode::F1 as u8), 0, 0) } _ => return None }; Some(KeyPressInfo{scan_code, ascii_char: if shifted { shifted_ascii_char } else { ascii_char }}) } fn get_ms_from_duration(duration: std::time::Duration) -> usize { (duration.as_secs() * 1000) as usize + duration.subsec_millis() as usize } pub fn vga_colour_to_rgb(colour: u8) -> (u8, u8, u8) { match colour { 0x0 => (0x00, 0x00, 0x00), 0x1 => (0x00, 0x00, 0xAA), 0x2 => (0x00, 0xAA, 0x00), 0x3 => (0x00, 0xAA, 0xAA), 0x4 => (0xAA, 0x00, 0x00), 0x5 => (0xAA, 0x00, 0xAA), 0x6 => (0xAA, 0x55, 0x00), 0x7 => (0xAA, 0xAA, 0xAA), 0x8 => (0x55, 0x55, 0x55), 0x9 => (0x55, 0x55, 0xFF), 0xA => (0x55, 0xFF, 0x55), 0xB => (0x55, 0xFF, 0xFF), 0xC => (0xFF, 0x55, 0x55), 0xD => (0xFF, 0x55, 0xFF), 0xE => (0xFF, 0xFF, 0x55), 0xF => (0xFF, 0xFF, 0xFF), _ => (0, 0, 0) } } struct DosConsole { machine: Machine8086, dos_event_handler: DosEventHandler, current_run_time_ms: usize, } impl DosConsole { fn draw_screen(&mut self, canvas: &mut WindowCanvas, dosfont_tex: &mut Texture, redraw_all: bool) { let screen_mem = &self.machine.memory[0xb8000..0xb8000+0x1000]; let screen_width = 80; let screen_height = 25; for y in 0 .. screen_height { for x in 0 .. screen_width { let char_index = (x + (y * screen_width)) * 2; let ref char_code = screen_mem[char_index]; let ref colour = screen_mem[char_index + 1]; let colour_fore = colour & 0x0f; let mut colour_back = (colour & 0xf0) >> 4; let mut blinking = false; if colour_back >= 8 { colour_back -= 8; blinking = true; } let fore_rgb = vga_colour_to_rgb(colour_fore); let back_rgb = vga_colour_to_rgb(colour_back); let char_rect = Rect::new(8 * (*char_code as i32), 0, 8, 14); let dest_rect = Rect::new(8 * (x as i32), 14 * (y as i32), 8, 14); canvas.set_draw_color(sdl2::pixels::Color::RGB(back_rgb.0, back_rgb.1, back_rgb.2)); canvas.fill_rect(dest_rect).ok(); if !blinking || self.current_run_time_ms % 450 < 225 { dosfont_tex.set_color_mod(fore_rgb.0, fore_rgb.1, fore_rgb.2); canvas.copy(&dosfont_tex, Some(char_rect), Some(dest_rect)).expect("Render failed"); } } } } fn update_keymod(&mut self, keymod: sdl2::keyboard::Mod) { self.dos_event_handler.set_key_mod(KeyModType::Shift, keymod.contains(sdl2::keyboard::LSHIFTMOD) || keymod.contains(sdl2::keyboard::RSHIFTMOD)); self.dos_event_handler.set_key_mod(KeyModType::Ctrl, keymod.contains(sdl2::keyboard::LCTRLMOD) || keymod.contains(sdl2::keyboard::RCTRLMOD)); self.dos_event_handler.set_key_mod(KeyModType::Alt, keymod.contains(sdl2::keyboard::LALTMOD) || keymod.contains(sdl2::keyboard::RALTMOD)); } fn run(&mut self) { let mut step_count = 0; let scale = 2; let sdl_context = sdl2::init().unwrap(); let render_width = 640; let render_height = 350; let sdl_video = sdl_context.video().unwrap(); let _sdl_image = sdl2::image::init(INIT_PNG).unwrap(); let window = sdl_video.window("PseuDOS", render_width * scale, render_height * scale) .position_centered() .build() .unwrap(); let (window_width, window_height) = window.size(); let mut canvas = window.into_canvas().software().build().unwrap(); let texture_creator = canvas.texture_creator(); let dosfont_file = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/res/dosfont.png")); let mut dosfont_tex = texture_creator.load_texture(dosfont_file).unwrap(); let mut running = true; canvas.set_scale(scale as f32, scale as f32).ok(); canvas.set_viewport(Rect::new(((window_width / scale) as i32 / 2 - render_width as i32 / 2) as i32, ((window_height / scale) as i32 / 2 - render_height as i32 / 2) as i32, render_width, render_height)); let start_time_ms = get_ms_from_duration(SystemTime::now().duration_since(UNIX_EPOCH).unwrap()); let mut last_time_ms = start_time_ms; self.draw_screen(&mut canvas, &mut dosfont_tex, true); while running { for event in sdl_context.event_pump().unwrap().poll_iter() { match event { Event::Quit{..} => { running = false; } Event::Window{..} => { self.draw_screen(&mut canvas, &mut dosfont_tex, true); } Event::KeyDown{keycode: keycode_opt, keymod, ..} => { self.update_keymod(keymod); let shifted = keymod.contains(sdl2::keyboard::LSHIFTMOD) || keymod.contains(sdl2::keyboard::RSHIFTMOD); if let Some(keycode) = keycode_opt { if let Some(key_info) = scancode_to_key_info(keycode, shifted) { self.dos_event_handler.key_press_queue.push_back(key_info); } } } _ => {} } } self.machine.interrupt_on_next_step(0x08); self.dos_event_handler.seconds_since_start += 54.9451/1000.; self.dos_event_handler.set_cga_vertial_retrace(true); let num_opcodes_to_exec = 4000; for _ in 0..num_opcodes_to_exec { match self.machine.step(&mut self.dos_event_handler) { Ok(StepResult::Interrupt) => { match self.dos_event_handler.result { DosInterruptResult::ShouldReturn => { self.machine.return_from_interrupt(); } DosInterruptResult::ShouldReturnAndWaitForEvents => { self.machine.return_from_interrupt(); break; } DosInterruptResult::ShouldBlockForKeypress => { break; } } } Err(err) => { eprintln!("Step error: {}", err); return; } _ => {} } step_count += 1; } /*if self.machine.number_of_parsed_instructions > 2000000 { //println!("MEM: {:?}", &machine.memory[0xb8000..0xb8000+0x1000]); /*use std::io::Write; println!("ds: {}", self.machine.get_reg_u16(Reg::DS)); let mut file = std::fs::File::create("memdmp.dat").unwrap(); file.write_all(&self.machine.memory);*/ let ds = self.machine.get_reg_u16(Reg::DS) as u32; /*for i in 0..16 { let addr = (ds<<4)+((i<<9)+0x8d0a); let length = self.machine.peek_u16(addr) as u32; let mut arrstr = "[".to_string(); //println!("length: {}", length); for sound_index in 0..length { let sound_addr = addr + ((sound_index * 2) + 2); let entry = self.machine.peek_u16(sound_addr); arrstr += &format!("{}, ", entry); //println!("> {}", entry); } arrstr += "]"; println!("{}", arrstr); }*/ for i in (0..256*2).step_by(2) { let addr = (ds<<4)+(i+0x89f4); let num = self.machine.peek_u16(addr); println!("{}: {}", i/2, num); } panic!(); }*/ self.draw_screen(&mut canvas, &mut dosfont_tex, false); self.current_run_time_ms += 5; canvas.present(); } } } fn main() { let mut file = std::fs::File::open("./junk/dos/ZZT.EXE").unwrap(); let exe_header = MzHeader::parse(&mut file).unwrap(); println!("{:#?}", exe_header); let mut machine = Machine8086::new(1024*1024*1); exe_header.load_into_machine(&mut machine, &mut file); let mut event_handler = DosEventHandler { machine_type: MachineType::EGA, video_mode: MachineType::EGA.lookup_video_mode(3).unwrap(), port_states: PortStates::new(), file_system: Box::new(StandardDosFileSystem::new("./junk/dos".into())), disk_trasnsfer_address: 0, seconds_since_start: 0., key_mod: 0, result: DosInterruptResult::ShouldReturn, key_press_queue: std::collections::VecDeque::new(), }; event_handler.init_machine(&mut machine); let mut console = DosConsole { machine, dos_event_handler: event_handler, current_run_time_ms: 0, }; console.run(); }
use std::cmp::Ordering; use libpseudos::dos_event_handler::{DosEventHandler, DosInterruptResult, KeyModType, KeyPressInfo, MachineType, PortStates}; use libpseudos::dos_file_system::StandardDosFileSystem; use libpseudos::exe_loader::MzHeader; use xachtsechs::machine8086::Machine8086; use xachtsechs::types::{Reg, RegHalf, StepResult}; use sdl2::image::{LoadTexture, INIT_PNG}; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::rect::Rect; use sdl2::render::{WindowCanvas, Texture}; use sdl2::audio::AudioSpecDesired; use std::time::{SystemTime, UNIX_EPOCH}; use std::path::Path; const SCANCODE_LETTERS: &[u8] = b"qwertyuiopasdfghjklzxcvbnm"; fn scancode_to_key_info(keycode: Keycode, shifted: bool) -> Option<KeyPressInfo> { let key_index = keycode as u8; let (scan_code, ascii_char, shifted_ascii_char) = match keycode { _ if (b'a' ..= b'z').contains(&(keycode as u8)) => { let lower_ascii_char = SCANCODE_LETTERS.iter().position(|c| *c == key_index).unwrap() as u8 + 0x10; (lower_ascii_char, key_index, key_index + 0x20) } Keycode::Num0 => (0x0b, 0x30, 0x29), Keycode::Num1 => (0x02, 0x31, 0x21), Keycode::Num2 => (0x03, 0x32, 0x40), Keycode::Num3 => (0x04, 0x33, 0x23), Keycode::Num4 => (0x05, 0x34, 0x24), Keycode::Num5 => (0x06, 0x35, 0x25), Keycode::Num6 => (0x07, 0x36, 0x5e), Keycode::Num7 => (0x08, 0x37, 0x26), Keycode::Num8 => (0x09, 0x38, 0x2a), Keycode::Num9 => (0x0a, 0x39, 0x28), Keycode::Backspace => (0x0e, 0x08, 0x08), Keycode::Delete => (0x53, 0x00, 0x2e), Keycode::Insert => (0x52, 0x00, 0x30), Keycode::Slash => (0x35, 0x2f, 0x3f), Keycode::Down => (0x50, 0, 0x32), Keycode::Up => (0x48, 0, 0x38), Keycode::Left => (0x4b, 0, 0x34), Keycode::Right => (0x4d, 0, 0x36), Keycode::Return => (0x1c, 0x0d, 0x0d), Keycode::Escape => (0x01, 0x1b, 0x1b), Keycode::Space => (0x39, 0x20, 0x20), Keycode::Tab => (0x0f, 0x09, 0), Keycode::PageUp => (0x49, 0, 0x39), Keycode::PageDown => (0x51, 0, 0x33), _ if (Keycode::F1 as u8 ..= Keycode::F12 as u8).contains(&(keycode as u8)) => { (0x3b + (keycode as u8 - Keycode::F1 as u8), 0, 0) } _ => return None }; Some(KeyPressInfo{scan_code, ascii_char: if shifted { shifted_ascii_char } else { ascii_char }}) } fn get_ms_from_duration(duration: std::time::Duration) -> usize { (duration.as_secs() * 1000) as usize + duration.subsec_millis() as usize } pub fn vga_colour_to_rgb(colour: u8) -> (u8, u8, u8) { match colour { 0x0 => (0x00, 0x00, 0x00), 0x1 => (0x00, 0x00, 0xAA), 0x2 => (0x00, 0xAA, 0x00), 0x3 => (0x00, 0xAA, 0xAA), 0x4 => (0xAA, 0x00, 0x00), 0x5 => (0xAA, 0x00, 0xAA), 0x6 => (0xAA, 0x55, 0x00), 0x7 => (0xAA, 0xAA, 0xAA), 0x8 => (0x55, 0x55, 0x55), 0x9 => (0x55, 0x55, 0xFF), 0xA => (0x55, 0xFF, 0x55), 0xB => (0x55, 0xFF, 0xFF), 0xC => (0xFF, 0x55, 0x55), 0xD => (0xFF, 0x55, 0xFF), 0xE => (0xFF, 0xFF, 0x55), 0xF => (0xFF, 0xFF, 0xFF), _ => (0, 0, 0) } } struct DosConsole { machine: Machine8086, dos_event_handler: DosEventHandler, current_run_time_ms: usize, } impl DosConsole { fn draw_screen(&mut self, canvas: &mut WindowCanvas, dosfont_tex: &mut Texture, redraw_all: bool) { let screen_mem = &self.machine.memory[0xb8000..0xb8000+0x1000]; let screen_width = 80; let screen_height = 25; for y in 0 .. screen_height { for x in 0 .. screen_width { let char_index = (x + (y * screen_width)) * 2; let ref char_code = screen_mem[char_index]; let ref colour = screen_mem[char_index + 1]; let colour_fore = colour & 0x0f; let mut colour_back = (colour & 0xf0) >> 4; let mut blinking = false; if colour_back >= 8 { colour_back -= 8; blinking = true; } let fore_rgb = vga_colour_to_rgb(colour_fore); let back_rgb = vga_colour_to_rgb(colour_back); let char_rect = Rect::new(8 * (*char_code as i32), 0, 8, 14); let dest_rect = Rect::new(8 * (x as i32), 14 * (y as i32), 8, 14); canvas.set_draw_color(sdl2::pixels::Color::RGB(back_rgb.0, back_rgb.1, back_rgb.2)); canvas.fill_rect(dest_rect).ok();
} } } fn update_keymod(&mut self, keymod: sdl2::keyboard::Mod) { self.dos_event_handler.set_key_mod(KeyModType::Shift, keymod.contains(sdl2::keyboard::LSHIFTMOD) || keymod.contains(sdl2::keyboard::RSHIFTMOD)); self.dos_event_handler.set_key_mod(KeyModType::Ctrl, keymod.contains(sdl2::keyboard::LCTRLMOD) || keymod.contains(sdl2::keyboard::RCTRLMOD)); self.dos_event_handler.set_key_mod(KeyModType::Alt, keymod.contains(sdl2::keyboard::LALTMOD) || keymod.contains(sdl2::keyboard::RALTMOD)); } fn run(&mut self) { let mut step_count = 0; let scale = 2; let sdl_context = sdl2::init().unwrap(); let render_width = 640; let render_height = 350; let sdl_video = sdl_context.video().unwrap(); let _sdl_image = sdl2::image::init(INIT_PNG).unwrap(); let window = sdl_video.window("PseuDOS", render_width * scale, render_height * scale) .position_centered() .build() .unwrap(); let (window_width, window_height) = window.size(); let mut canvas = window.into_canvas().software().build().unwrap(); let texture_creator = canvas.texture_creator(); let dosfont_file = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/res/dosfont.png")); let mut dosfont_tex = texture_creator.load_texture(dosfont_file).unwrap(); let mut running = true; canvas.set_scale(scale as f32, scale as f32).ok(); canvas.set_viewport(Rect::new(((window_width / scale) as i32 / 2 - render_width as i32 / 2) as i32, ((window_height / scale) as i32 / 2 - render_height as i32 / 2) as i32, render_width, render_height)); let start_time_ms = get_ms_from_duration(SystemTime::now().duration_since(UNIX_EPOCH).unwrap()); let mut last_time_ms = start_time_ms; self.draw_screen(&mut canvas, &mut dosfont_tex, true); while running { for event in sdl_context.event_pump().unwrap().poll_iter() { match event { Event::Quit{..} => { running = false; } Event::Window{..} => { self.draw_screen(&mut canvas, &mut dosfont_tex, true); } Event::KeyDown{keycode: keycode_opt, keymod, ..} => { self.update_keymod(keymod); let shifted = keymod.contains(sdl2::keyboard::LSHIFTMOD) || keymod.contains(sdl2::keyboard::RSHIFTMOD); if let Some(keycode) = keycode_opt { if let Some(key_info) = scancode_to_key_info(keycode, shifted) { self.dos_event_handler.key_press_queue.push_back(key_info); } } } _ => {} } } self.machine.interrupt_on_next_step(0x08); self.dos_event_handler.seconds_since_start += 54.9451/1000.; self.dos_event_handler.set_cga_vertial_retrace(true); let num_opcodes_to_exec = 4000; for _ in 0..num_opcodes_to_exec { match self.machine.step(&mut self.dos_event_handler) { Ok(StepResult::Interrupt) => { match self.dos_event_handler.result { DosInterruptResult::ShouldReturn => { self.machine.return_from_interrupt(); } DosInterruptResult::ShouldReturnAndWaitForEvents => { self.machine.return_from_interrupt(); break; } DosInterruptResult::ShouldBlockForKeypress => { break; } } } Err(err) => { eprintln!("Step error: {}", err); return; } _ => {} } step_count += 1; } /*if self.machine.number_of_parsed_instructions > 2000000 { //println!("MEM: {:?}", &machine.memory[0xb8000..0xb8000+0x1000]); /*use std::io::Write; println!("ds: {}", self.machine.get_reg_u16(Reg::DS)); let mut file = std::fs::File::create("memdmp.dat").unwrap(); file.write_all(&self.machine.memory);*/ let ds = self.machine.get_reg_u16(Reg::DS) as u32; /*for i in 0..16 { let addr = (ds<<4)+((i<<9)+0x8d0a); let length = self.machine.peek_u16(addr) as u32; let mut arrstr = "[".to_string(); //println!("length: {}", length); for sound_index in 0..length { let sound_addr = addr + ((sound_index * 2) + 2); let entry = self.machine.peek_u16(sound_addr); arrstr += &format!("{}, ", entry); //println!("> {}", entry); } arrstr += "]"; println!("{}", arrstr); }*/ for i in (0..256*2).step_by(2) { let addr = (ds<<4)+(i+0x89f4); let num = self.machine.peek_u16(addr); println!("{}: {}", i/2, num); } panic!(); }*/ self.draw_screen(&mut canvas, &mut dosfont_tex, false); self.current_run_time_ms += 5; canvas.present(); } } } fn main() { let mut file = std::fs::File::open("./junk/dos/ZZT.EXE").unwrap(); let exe_header = MzHeader::parse(&mut file).unwrap(); println!("{:#?}", exe_header); let mut machine = Machine8086::new(1024*1024*1); exe_header.load_into_machine(&mut machine, &mut file); let mut event_handler = DosEventHandler { machine_type: MachineType::EGA, video_mode: MachineType::EGA.lookup_video_mode(3).unwrap(), port_states: PortStates::new(), file_system: Box::new(StandardDosFileSystem::new("./junk/dos".into())), disk_trasnsfer_address: 0, seconds_since_start: 0., key_mod: 0, result: DosInterruptResult::ShouldReturn, key_press_queue: std::collections::VecDeque::new(), }; event_handler.init_machine(&mut machine); let mut console = DosConsole { machine, dos_event_handler: event_handler, current_run_time_ms: 0, }; console.run(); }
if !blinking || self.current_run_time_ms % 450 < 225 { dosfont_tex.set_color_mod(fore_rgb.0, fore_rgb.1, fore_rgb.2); canvas.copy(&dosfont_tex, Some(char_rect), Some(dest_rect)).expect("Render failed"); }
if_condition
[ { "content": "// http://www.bioscentral.com/misc/bda.htm\n\npub fn initialise_bios_data_area(machine: &mut Machine8086) {\n\n\t// The BIOS Data Area starts at the start of the 0x40 segment.\n\n\t// Equipment\n\n\tmachine.set_data_u16(&BIOS_EQUIPMENT, 0x0061);\n\n\t// Memory size in KB\n\n\tmachine.set_data_u16(...
Rust
src/lib.rs
cdisselkoen/llvm-ir-analysis
f690c660070fe881a33d055cd30d5f4c352c69f5
mod call_graph; mod control_dep_graph; mod control_flow_graph; mod dominator_tree; mod functions_by_type; pub use crate::call_graph::CallGraph; pub use crate::control_dep_graph::ControlDependenceGraph; pub use crate::control_flow_graph::{CFGNode, ControlFlowGraph}; pub use crate::dominator_tree::{DominatorTree, PostDominatorTree}; pub use crate::functions_by_type::FunctionsByType; use llvm_ir::{Function, Module}; use log::debug; use std::cell::{Ref, RefCell}; use std::collections::HashMap; pub struct ModuleAnalysis<'m> { module: &'m Module, call_graph: SimpleCache<CallGraph<'m>>, functions_by_type: SimpleCache<FunctionsByType<'m>>, fn_analyses: HashMap<&'m str, FunctionAnalysis<'m>>, } impl<'m> ModuleAnalysis<'m> { pub fn new(module: &'m Module) -> Self { Self { module, call_graph: SimpleCache::new(), functions_by_type: SimpleCache::new(), fn_analyses: module.functions.iter() .map(|f| (f.name.as_str(), FunctionAnalysis::new(f))) .collect(), } } pub fn module(&self) -> &'m Module { self.module } pub fn call_graph(&self) -> Ref<CallGraph<'m>> { self.call_graph.get_or_insert_with(|| { let functions_by_type = self.functions_by_type(); debug!("computing single-module call graph"); CallGraph::new(std::iter::once(self.module), &functions_by_type) }) } pub fn functions_by_type(&self) -> Ref<FunctionsByType<'m>> { self.functions_by_type.get_or_insert_with(|| { debug!("computing single-module functions-by-type"); FunctionsByType::new(std::iter::once(self.module)) }) } pub fn fn_analysis<'s>(&'s self, func_name: &str) -> &'s FunctionAnalysis<'m> { self.fn_analyses.get(func_name) .unwrap_or_else(|| panic!("Function named {:?} not found in the Module", func_name)) } } pub struct CrossModuleAnalysis<'m> { modules: Vec<&'m Module>, call_graph: SimpleCache<CallGraph<'m>>, functions_by_type: SimpleCache<FunctionsByType<'m>>, module_analyses: HashMap<&'m str, ModuleAnalysis<'m>>, } impl<'m> CrossModuleAnalysis<'m> { pub fn new(modules: impl IntoIterator<Item = &'m Module>) -> Self { let modules: Vec<&'m Module> = modules.into_iter().collect(); let module_analyses = modules .iter() .copied() .map(|m| (m.name.as_str(), ModuleAnalysis::new(m))) .collect(); Self { modules, call_graph: SimpleCache::new(), functions_by_type: SimpleCache::new(), module_analyses, } } pub fn modules<'s>(&'s self) -> impl Iterator<Item = &'m Module> + 's { self.modules.iter().copied() } pub fn functions<'s>(&'s self) -> impl Iterator<Item = &'m Function> + 's { self.modules().map(|m| m.functions.iter()).flatten() } pub fn call_graph(&self) -> Ref<CallGraph<'m>> { self.call_graph.get_or_insert_with(|| { let functions_by_type = self.functions_by_type(); debug!("computing multi-module call graph"); CallGraph::new(self.modules(), &functions_by_type) }) } pub fn functions_by_type(&self) -> Ref<FunctionsByType<'m>> { self.functions_by_type.get_or_insert_with(|| { debug!("computing multi-module functions-by-type"); FunctionsByType::new(self.modules()) }) } pub fn module_analysis<'s>(&'s self, mod_name: &str) -> &'s ModuleAnalysis<'m> { self.module_analyses.get(mod_name) .unwrap_or_else(|| panic!("Module named {:?} not found in the CrossModuleAnalysis", mod_name)) } pub fn get_func_by_name(&self, func_name: &str) -> Option<(&'m Function, &'m Module)> { let mut retval = None; for &module in &self.modules { if let Some(func) = module.get_func_by_name(func_name) { match retval { None => retval = Some((func, module)), Some((_, retmod)) => panic!("Multiple functions found with name {:?}: one in module {:?}, another in module {:?}", func_name, &retmod.name, &module.name), } } } retval } } pub struct FunctionAnalysis<'m> { function: &'m Function, control_flow_graph: SimpleCache<ControlFlowGraph<'m>>, dominator_tree: SimpleCache<DominatorTree<'m>>, postdominator_tree: SimpleCache<PostDominatorTree<'m>>, control_dep_graph: SimpleCache<ControlDependenceGraph<'m>>, } impl<'m> FunctionAnalysis<'m> { pub fn new(function: &'m Function) -> Self { Self { function, control_flow_graph: SimpleCache::new(), dominator_tree: SimpleCache::new(), postdominator_tree: SimpleCache::new(), control_dep_graph: SimpleCache::new(), } } pub fn control_flow_graph(&self) -> Ref<ControlFlowGraph<'m>> { self.control_flow_graph.get_or_insert_with(|| { debug!("computing control flow graph for {}", &self.function.name); ControlFlowGraph::new(self.function) }) } pub fn dominator_tree(&self) -> Ref<DominatorTree<'m>> { self.dominator_tree.get_or_insert_with(|| { let cfg = self.control_flow_graph(); debug!("computing dominator tree for {}", &self.function.name); DominatorTree::new(&cfg) }) } pub fn postdominator_tree(&self) -> Ref<PostDominatorTree<'m>> { self.postdominator_tree.get_or_insert_with(|| { let cfg = self.control_flow_graph(); debug!("computing postdominator tree for {}", &self.function.name); PostDominatorTree::new(&cfg) }) } pub fn control_dependence_graph(&self) -> Ref<ControlDependenceGraph<'m>> { self.control_dep_graph.get_or_insert_with(|| { let cfg = self.control_flow_graph(); let postdomtree = self.postdominator_tree(); debug!("computing control dependence graph for {}", &self.function.name); ControlDependenceGraph::new(&cfg, &postdomtree) }) } } struct SimpleCache<T> { data: RefCell<Option<T>>, } impl<T> SimpleCache<T> { fn new() -> Self { Self { data: RefCell::new(None), } } fn get_or_insert_with(&self, f: impl FnOnce() -> T) -> Ref<T> { let need_mutable_borrow = self.data.borrow().is_none(); if need_mutable_borrow { let old_val = self.data.borrow_mut().replace(f()); debug_assert!(old_val.is_none()); } Ref::map(self.data.borrow(), |o| { o.as_ref().expect("should be populated now") }) } }
mod call_graph; mod control_dep_graph; mod control_flow_graph; mod dominator_tree; mod functions_by_type; pub use crate::call_graph::CallGraph; pub use crate::control_dep_graph::ControlDependenceGraph; pub use crate::control_flow_graph::{CFGNode, ControlFlowGraph}; pub use crate::dominator_tree::{DominatorTree, PostDominatorTree}; pub use crate::functions_by_type::FunctionsByType; use llvm_ir::{Function, Module}; use log::debug; use std::cell::{Ref, RefCell}; use std::collections::HashMap; pub struct ModuleAnalysis<'m> { module: &'m Module, call_graph: SimpleCache<CallGraph<'m>>, functions_by_type: SimpleCache<FunctionsByType<'m>>, fn_analyses: HashMap<&'m str, FunctionAnalysis<'m>>, } impl<'m> ModuleAnalysis<'m> { pub fn new(module: &'m Module) -> Self { Self { module, call_graph: SimpleCache::new(), functions_by_type: SimpleCache::new(), fn_analyses: module.functions.iter() .map(|f| (f.name.as_str(), FunctionAnalysis::new(f))) .collect(), } } pub fn module(&self) -> &'m Module { self.module }
pub fn functions_by_type(&self) -> Ref<FunctionsByType<'m>> { self.functions_by_type.get_or_insert_with(|| { debug!("computing single-module functions-by-type"); FunctionsByType::new(std::iter::once(self.module)) }) } pub fn fn_analysis<'s>(&'s self, func_name: &str) -> &'s FunctionAnalysis<'m> { self.fn_analyses.get(func_name) .unwrap_or_else(|| panic!("Function named {:?} not found in the Module", func_name)) } } pub struct CrossModuleAnalysis<'m> { modules: Vec<&'m Module>, call_graph: SimpleCache<CallGraph<'m>>, functions_by_type: SimpleCache<FunctionsByType<'m>>, module_analyses: HashMap<&'m str, ModuleAnalysis<'m>>, } impl<'m> CrossModuleAnalysis<'m> { pub fn new(modules: impl IntoIterator<Item = &'m Module>) -> Self { let modules: Vec<&'m Module> = modules.into_iter().collect(); let module_analyses = modules .iter() .copied() .map(|m| (m.name.as_str(), ModuleAnalysis::new(m))) .collect(); Self { modules, call_graph: SimpleCache::new(), functions_by_type: SimpleCache::new(), module_analyses, } } pub fn modules<'s>(&'s self) -> impl Iterator<Item = &'m Module> + 's { self.modules.iter().copied() } pub fn functions<'s>(&'s self) -> impl Iterator<Item = &'m Function> + 's { self.modules().map(|m| m.functions.iter()).flatten() } pub fn call_graph(&self) -> Ref<CallGraph<'m>> { self.call_graph.get_or_insert_with(|| { let functions_by_type = self.functions_by_type(); debug!("computing multi-module call graph"); CallGraph::new(self.modules(), &functions_by_type) }) } pub fn functions_by_type(&self) -> Ref<FunctionsByType<'m>> { self.functions_by_type.get_or_insert_with(|| { debug!("computing multi-module functions-by-type"); FunctionsByType::new(self.modules()) }) } pub fn module_analysis<'s>(&'s self, mod_name: &str) -> &'s ModuleAnalysis<'m> { self.module_analyses.get(mod_name) .unwrap_or_else(|| panic!("Module named {:?} not found in the CrossModuleAnalysis", mod_name)) } pub fn get_func_by_name(&self, func_name: &str) -> Option<(&'m Function, &'m Module)> { let mut retval = None; for &module in &self.modules { if let Some(func) = module.get_func_by_name(func_name) { match retval { None => retval = Some((func, module)), Some((_, retmod)) => panic!("Multiple functions found with name {:?}: one in module {:?}, another in module {:?}", func_name, &retmod.name, &module.name), } } } retval } } pub struct FunctionAnalysis<'m> { function: &'m Function, control_flow_graph: SimpleCache<ControlFlowGraph<'m>>, dominator_tree: SimpleCache<DominatorTree<'m>>, postdominator_tree: SimpleCache<PostDominatorTree<'m>>, control_dep_graph: SimpleCache<ControlDependenceGraph<'m>>, } impl<'m> FunctionAnalysis<'m> { pub fn new(function: &'m Function) -> Self { Self { function, control_flow_graph: SimpleCache::new(), dominator_tree: SimpleCache::new(), postdominator_tree: SimpleCache::new(), control_dep_graph: SimpleCache::new(), } } pub fn control_flow_graph(&self) -> Ref<ControlFlowGraph<'m>> { self.control_flow_graph.get_or_insert_with(|| { debug!("computing control flow graph for {}", &self.function.name); ControlFlowGraph::new(self.function) }) } pub fn dominator_tree(&self) -> Ref<DominatorTree<'m>> { self.dominator_tree.get_or_insert_with(|| { let cfg = self.control_flow_graph(); debug!("computing dominator tree for {}", &self.function.name); DominatorTree::new(&cfg) }) } pub fn postdominator_tree(&self) -> Ref<PostDominatorTree<'m>> { self.postdominator_tree.get_or_insert_with(|| { let cfg = self.control_flow_graph(); debug!("computing postdominator tree for {}", &self.function.name); PostDominatorTree::new(&cfg) }) } pub fn control_dependence_graph(&self) -> Ref<ControlDependenceGraph<'m>> { self.control_dep_graph.get_or_insert_with(|| { let cfg = self.control_flow_graph(); let postdomtree = self.postdominator_tree(); debug!("computing control dependence graph for {}", &self.function.name); ControlDependenceGraph::new(&cfg, &postdomtree) }) } } struct SimpleCache<T> { data: RefCell<Option<T>>, } impl<T> SimpleCache<T> { fn new() -> Self { Self { data: RefCell::new(None), } } fn get_or_insert_with(&self, f: impl FnOnce() -> T) -> Ref<T> { let need_mutable_borrow = self.data.borrow().is_none(); if need_mutable_borrow { let old_val = self.data.borrow_mut().replace(f()); debug_assert!(old_val.is_none()); } Ref::map(self.data.borrow(), |o| { o.as_ref().expect("should be populated now") }) } }
pub fn call_graph(&self) -> Ref<CallGraph<'m>> { self.call_graph.get_or_insert_with(|| { let functions_by_type = self.functions_by_type(); debug!("computing single-module call graph"); CallGraph::new(std::iter::once(self.module), &functions_by_type) }) }
function_block-full_function
[ { "content": "pub fn may_panic(a: i32) -> i32 {\n\n if a > 2 {\n\n panic!(\"a > 2\");\n\n } else {\n\n return 1;\n\n }\n\n}\n", "file_path": "tests/bcfiles/panic.rs", "rank": 0, "score": 69531.15541423167 }, { "content": "#[test]\n\nfn call_graph() {\n\n init_loggin...
Rust
thcon/src/app/konsole.rs
theme-controller/thcon
646b8dac38994acff31cd90aae6fafa80bad168a
use crate::config::Config as ThconConfig; use crate::operation::Operation; use crate::AppConfig; use crate::Disableable; use crate::{ themeable::{ConfigError, ConfigState}, Themeable, }; use std::time::Duration; use anyhow::{Context, Result}; use dbus::blocking::Connection; use log::{debug, trace}; use serde::Deserialize; use xml::reader::{EventReader, XmlEvent}; #[derive(Debug, Deserialize, Disableable, AppConfig)] pub struct _Config { light: String, dark: String, #[serde(default)] disabled: bool, } pub struct Konsole { dbus: Connection, } impl Default for Konsole { fn default() -> Self { Self { dbus: Connection::new_session().unwrap(), } } } impl Konsole { fn get_services(&self) -> Result<Vec<String>> { let proxy = self .dbus .with_proxy("org.freedesktop.DBus", "/", Duration::from_millis(2500)); let (names,): (Vec<String>,) = proxy .method_call("org.freedesktop.DBus", "ListNames", ()) .context("Unable to retrieve konsole windows from DBus")?; let konsoles: Vec<String> = names .into_iter() .filter(|name| name.as_str().starts_with("org.kde.konsole-")) .collect(); trace!( "Found {} {}", konsoles.len(), if konsoles.len() == 1 { "service" } else { "services" }, ); Ok(konsoles) } fn get_session_ids(&self, service_id: &str) -> Result<Vec<String>> { let proxy = self .dbus .with_proxy(service_id, "/Sessions", Duration::from_millis(2500)); let (xml,): (String,) = proxy .method_call("org.freedesktop.DBus.Introspectable", "Introspect", ()) .with_context(|| { format!( "Unable to get konsole session ids for DBus service '{}'", service_id ) })?; let parser = EventReader::from_str(&xml); let mut depth = 0; let mut session_ids: Vec<String> = vec![]; for e in parser { match e { Ok(XmlEvent::StartElement { name, attributes, .. }) => { if depth == 1 && name.local_name == "node" { session_ids.extend(attributes.into_iter().filter_map(|attr| { if attr.name.local_name == "name" { Some(attr.value) } else { None } })); } depth += 1; } Ok(XmlEvent::EndElement { .. }) => depth -= 1, Err(e) => { return Err(e.into()); } _ => {} } } trace!( "Found {} {} in service {}", session_ids.len(), if session_ids.len() == 1 { "session" } else { "sessions" }, service_id ); Ok(session_ids) } fn set_profile_name( &self, service_id: &str, session_id: &str, profile_name: &str, ) -> Result<()> { let proxy = self.dbus.with_proxy( service_id, format!("/Sessions/{}", session_id), Duration::from_millis(2500), ); let _: () = proxy.method_call("org.kde.konsole.Session", "setProfile", (profile_name,))?; Ok(()) } fn set_default_profile(&self, service_id: &str, profile_name: &str) -> Result<()> { let proxy = self .dbus .with_proxy(service_id, "/Windows", Duration::from_millis(2500)); let (xml,): (String,) = proxy .method_call("org.freedesktop.DBus.Introspectable", "Introspect", ()) .with_context(|| { format!("Unable to retreive window for DBus service '{}", service_id) })?; let parser = EventReader::from_str(&xml); let mut depth = 0; let mut window_id: Option<String> = None; for e in parser { match e { Ok(XmlEvent::StartElement { name, attributes, .. }) => { if depth == 1 && name.local_name == "node" { window_id = attributes.into_iter().find_map(|attr| { if attr.name.local_name == "name" { Some(attr.value) } else { None } }); } depth += 1; } Ok(XmlEvent::EndElement { .. }) => depth -= 1, Err(e) => { return Err(e.into()); } _ => {} } } if let Some(window_id) = window_id { trace!("Found first window ID {}", window_id); let proxy = self.dbus.with_proxy( service_id, format!("/Windows/{}", window_id), Duration::from_millis(2500), ); proxy .method_call( "org.kde.konsole.Window", "setDefaultProfile", (profile_name,), ) .context("asdfasdf")?; } else { trace!("Found no Konsole windows; can't set default profile."); } Ok(()) } } impl Themeable for Konsole { fn config_state(&self, config: &ThconConfig) -> ConfigState { ConfigState::with_manual_config(config.konsole.as_ref().map(|c| c.inner.as_ref())) } fn switch(&self, config: &ThconConfig, operation: &Operation) -> Result<()> { let config = match self.config_state(config) { ConfigState::NoDefault => { return Err(ConfigError::RequiresManualConfig("konsole").into()) } ConfigState::Default => unreachable!(), ConfigState::Disabled => return Ok(()), ConfigState::Enabled => config.konsole.as_ref().unwrap().unwrap_inner_left(), }; let mut total_sessions = 0; let services: Vec<(String, Vec<String>)> = self .get_services()? .into_iter() .map(|service| { let session_ids = self.get_session_ids(&service).unwrap(); total_sessions += session_ids.len(); (service, session_ids) }) .collect(); let theme = match operation { Operation::Darken => &config.dark, Operation::Lighten => &config.light, }; if services.len() == 1 { debug!( "Found {} {}", total_sessions, if total_sessions == 1 { "session" } else { "sessions" }, ); } else { debug!( "Found {} {} across {} services", total_sessions, if total_sessions == 1 { "session" } else { "sessions" }, services.len(), ); } for (service_id, session_ids) in services.iter() { for session_id in session_ids.iter() { self.set_profile_name(service_id, session_id, theme)?; } } if let Some((session, _)) = services.get(0) { self.set_default_profile(session, theme)?; } Ok(()) } }
use crate::config::Config as ThconConfig; use crate::operation::Operation; use crate::AppConfig; use crate::Disableable; use crate::{ themeable::{ConfigError, ConfigState}, Themeable, }; use std::time::Duration; use anyhow::{Context, Result}; use dbus::blocking::Connection; use log::{debug, trace}; use serde::Deserialize; use xml::reader::{EventReader, XmlEvent}; #[derive(Debug, Deserialize, Disableable, AppConfig)] pub struct _Config { light: String, dark: String, #[serde(default)] disabled: bool, } pub struct Konsole { dbus: Connection, } impl Default for Konsole { fn default() -> Self { Self { dbus: Connection::new_session().unwrap(), } } } impl Konsole { fn get_services(&self) -> Result<Vec<String>> { let proxy = self .dbus .with_proxy("org.freedesktop.DBus", "/", Duration::from_millis(2500)); let (names,): (Vec<String>,) = proxy .method_call("org.freedesktop.DBus", "ListNames", ()) .context("Unable to retrieve konsole windows from DBus")?; let konsoles: Vec<String> = names .into_iter() .filter(|name| name.as_str().starts_with("org.kde.konsole-")) .collect(); trace!( "Found {} {}", konsoles.len(), if konsoles.len() == 1 { "service" } else { "services" }, ); Ok(konsoles) }
fn set_profile_name( &self, service_id: &str, session_id: &str, profile_name: &str, ) -> Result<()> { let proxy = self.dbus.with_proxy( service_id, format!("/Sessions/{}", session_id), Duration::from_millis(2500), ); let _: () = proxy.method_call("org.kde.konsole.Session", "setProfile", (profile_name,))?; Ok(()) } fn set_default_profile(&self, service_id: &str, profile_name: &str) -> Result<()> { let proxy = self .dbus .with_proxy(service_id, "/Windows", Duration::from_millis(2500)); let (xml,): (String,) = proxy .method_call("org.freedesktop.DBus.Introspectable", "Introspect", ()) .with_context(|| { format!("Unable to retreive window for DBus service '{}", service_id) })?; let parser = EventReader::from_str(&xml); let mut depth = 0; let mut window_id: Option<String> = None; for e in parser { match e { Ok(XmlEvent::StartElement { name, attributes, .. }) => { if depth == 1 && name.local_name == "node" { window_id = attributes.into_iter().find_map(|attr| { if attr.name.local_name == "name" { Some(attr.value) } else { None } }); } depth += 1; } Ok(XmlEvent::EndElement { .. }) => depth -= 1, Err(e) => { return Err(e.into()); } _ => {} } } if let Some(window_id) = window_id { trace!("Found first window ID {}", window_id); let proxy = self.dbus.with_proxy( service_id, format!("/Windows/{}", window_id), Duration::from_millis(2500), ); proxy .method_call( "org.kde.konsole.Window", "setDefaultProfile", (profile_name,), ) .context("asdfasdf")?; } else { trace!("Found no Konsole windows; can't set default profile."); } Ok(()) } } impl Themeable for Konsole { fn config_state(&self, config: &ThconConfig) -> ConfigState { ConfigState::with_manual_config(config.konsole.as_ref().map(|c| c.inner.as_ref())) } fn switch(&self, config: &ThconConfig, operation: &Operation) -> Result<()> { let config = match self.config_state(config) { ConfigState::NoDefault => { return Err(ConfigError::RequiresManualConfig("konsole").into()) } ConfigState::Default => unreachable!(), ConfigState::Disabled => return Ok(()), ConfigState::Enabled => config.konsole.as_ref().unwrap().unwrap_inner_left(), }; let mut total_sessions = 0; let services: Vec<(String, Vec<String>)> = self .get_services()? .into_iter() .map(|service| { let session_ids = self.get_session_ids(&service).unwrap(); total_sessions += session_ids.len(); (service, session_ids) }) .collect(); let theme = match operation { Operation::Darken => &config.dark, Operation::Lighten => &config.light, }; if services.len() == 1 { debug!( "Found {} {}", total_sessions, if total_sessions == 1 { "session" } else { "sessions" }, ); } else { debug!( "Found {} {} across {} services", total_sessions, if total_sessions == 1 { "session" } else { "sessions" }, services.len(), ); } for (service_id, session_ids) in services.iter() { for session_id in session_ids.iter() { self.set_profile_name(service_id, session_id, theme)?; } } if let Some((session, _)) = services.get(0) { self.set_default_profile(session, theme)?; } Ok(()) } }
fn get_session_ids(&self, service_id: &str) -> Result<Vec<String>> { let proxy = self .dbus .with_proxy(service_id, "/Sessions", Duration::from_millis(2500)); let (xml,): (String,) = proxy .method_call("org.freedesktop.DBus.Introspectable", "Introspect", ()) .with_context(|| { format!( "Unable to get konsole session ids for DBus service '{}'", service_id ) })?; let parser = EventReader::from_str(&xml); let mut depth = 0; let mut session_ids: Vec<String> = vec![]; for e in parser { match e { Ok(XmlEvent::StartElement { name, attributes, .. }) => { if depth == 1 && name.local_name == "node" { session_ids.extend(attributes.into_iter().filter_map(|attr| { if attr.name.local_name == "name" { Some(attr.value) } else { None } })); } depth += 1; } Ok(XmlEvent::EndElement { .. }) => depth -= 1, Err(e) => { return Err(e.into()); } _ => {} } } trace!( "Found {} {} in service {}", session_ids.len(), if session_ids.len() == 1 { "session" } else { "sessions" }, service_id ); Ok(session_ids) }
function_block-full_function
[ { "content": "pub fn get(name: &str) -> Option<Box<dyn Themeable>> {\n\n match name {\n\n #[cfg(dbus)]\n\n \"konsole\" => Some(Box::new(Konsole::default())),\n\n #[cfg(dbus)]\n\n \"gnome-shell\" => Some(Box::new(GnomeShell {})),\n\n #[cfg(dbus)]\n\n \"gnome-terminal\...
Rust
src/kvm.rs
yodalee/rrxv6
bf3b076b28e8fbb5de00e63748b5e27a829d6634
use lazy_static::lazy_static; use spin::Mutex; use rv64::csr::satp::{Satp, SatpMode}; use rv64::asm::sfence_vma; use crate::vm::page_table::{PageTable, PageTableLevel}; use crate::vm::addr::{VirtAddr, PhysAddr}; use crate::vm::page_flag::PteFlag; use crate::riscv::{PAGESIZE, MAXVA}; use crate::memorylayout::{UART0, PLIC_BASE, TRAMPOLINE, KERNELBASE, PHYSTOP}; use crate::kalloc::kalloc; lazy_static! { static ref KERNELPAGE: Mutex<u64> = Mutex::new(0); } pub fn init_kvm() { extern "C" { static _trampoline: usize; static _etext: usize; } let ptrampoline: u64 = unsafe { &_trampoline as *const usize as u64 }; let petext: u64 = unsafe { &_etext as *const usize as u64 }; let root_page: &mut PageTable = unsafe { &mut *(kalloc() as *mut PageTable) }; let mut root_page_lock = KERNELPAGE.lock(); *root_page_lock = root_page as *const _ as u64; drop(root_page_lock); kvmmap(VirtAddr::new(UART0), PhysAddr::new(UART0), PAGESIZE, PteFlag::PTE_READ | PteFlag::PTE_WRITE); kvmmap(VirtAddr::new(PLIC_BASE), PhysAddr::new(PLIC_BASE), 0x400000, PteFlag::PTE_READ | PteFlag::PTE_WRITE); kvmmap(VirtAddr::new(KERNELBASE), PhysAddr::new(KERNELBASE), petext - KERNELBASE, PteFlag::PTE_READ | PteFlag::PTE_EXEC); kvmmap(VirtAddr::new(petext), PhysAddr::new(petext), PHYSTOP as u64 - petext, PteFlag::PTE_READ | PteFlag::PTE_WRITE); kvmmap(VirtAddr::new(TRAMPOLINE), PhysAddr::new(ptrampoline), PAGESIZE, PteFlag::PTE_READ | PteFlag::PTE_EXEC); } pub fn init_page() { let mut satp = Satp::from_bits(0); let ptr = unsafe { get_root_page() }; satp.set_mode(SatpMode::ModeSv39); satp.set_addr(ptr as *const _ as u64); satp.write(); sfence_vma(); } pub unsafe fn get_root_page() -> &'static mut PageTable { let addr = *KERNELPAGE.lock(); let ptr: *mut PageTable = addr as *mut PageTable; &mut *ptr } fn kvmmap(va: VirtAddr, pa: PhysAddr, size: u64, perm: PteFlag) { match map_pages(va, pa, size, perm) { Ok(_) => {}, Err(e) => panic!("mappages error: {}", e), } } fn map_pages(va: VirtAddr, mut pa: PhysAddr, size: u64, perm: PteFlag) -> Result<(), &'static str> { let page_table = unsafe { get_root_page() }; let va_start = va.align_down(); let va_end = VirtAddr::new_truncate(va.as_u64() + size - 1).align_down(); let mut page_addr = va_start; loop { map_page(page_table, page_addr, pa, perm, PageTableLevel::Two)?; if page_addr == va_end { break; } page_addr += PAGESIZE; pa += PAGESIZE; } Ok(()) } fn map_page(page_table: &mut PageTable, va: VirtAddr, pa: PhysAddr, perm: PteFlag, level: PageTableLevel) -> Result<(), &'static str> { if va >= VirtAddr::new(MAXVA) { return Err("map_page: virtual address over MAX address") } let index = va.get_index(level); let pte = &mut page_table[index]; match level.next_level() { None => { if pte.is_unused() { pte.set_addr(pa.as_pte(), perm | PteFlag::PTE_VALID); Ok(()) } else { Err("map_page: remap") } }, Some(next_level) => { if pte.is_unused() { let ptr = kalloc(); if ptr == 0 as *mut u8 { return Err("kalloc failed in map_page"); } let addr = PhysAddr::new(ptr as *const _ as u64); pte.set_addr(addr.as_pte(), PteFlag::PTE_VALID); } let next_table = unsafe { &mut *(pte.addr() as *mut PageTable) }; map_page(next_table, va, pa, perm, next_level) } } }
use lazy_static::lazy_static; use spin::Mutex; use rv64::csr::satp::{Satp, SatpMode}; use rv64::asm::sfence_vma; use crate::vm::page_table::{PageTable, PageTableLevel}; use crate::vm::addr::{VirtAddr, PhysAddr}; use crate::vm::page_flag::PteFlag; use crate::riscv::{PAGESIZE, MAXVA}; use crate::memorylayout::{UART0, PLIC_BASE, TRAMPOLINE, KERNELBASE, PHYSTOP}; use crate::kalloc::kalloc; lazy_static! { static ref KERNELPAGE: Mutex<u64> = Mutex::new(0); } pub fn init_kvm() { extern "C" { static _trampoline: usize; static _etext: usize; } let ptrampoline: u64 = unsafe { &_trampoline as *const usize as u64 }; let petext: u64 = unsafe { &_etext as *const usize as u64 }; let root_page: &mut PageTable = unsafe { &mut *(kalloc() as *mut PageTable) }; let mut root_page_lock = KERNELPAGE.lock(); *root_page_lock = root_page as *const _ as u64; drop(root_page_lock); kvmmap(VirtAddr::new(UART0), PhysAddr::new(UART0), PAGESIZE, PteFlag::PTE_READ | PteFlag::PTE_WRITE); kvmmap(VirtAddr::new(PLIC_BASE), PhysAddr::new(PLIC_BASE), 0x400000, PteFlag::PTE_READ | PteFlag::PTE_WRITE); kvmmap(VirtAddr::new(KERNELBASE), PhysAddr::new(KERNELBASE), petext - KERNELBASE, PteFlag::PTE_READ | PteFlag::PTE_EXEC); kvmmap(VirtAddr::new(petext), PhysAddr::new(petext), PHYSTOP as u64 - petext, PteFlag::PTE_READ | PteFlag::PTE_WRITE); kvmmap(VirtAddr::new(TRAMPOLINE), PhysAddr::new(ptrampoline), PAGESIZE, PteFlag::PTE_READ | PteFlag::PTE_EXEC); } pub fn init_page() { let mut satp = Satp::from_bits(0); let ptr = unsafe { get_root_page() }; satp.set_mode(SatpMode::ModeSv39); satp.set_addr(ptr as *const _ as u64); satp.write(); sfence_vma(); } pub unsafe fn get_root_page() -> &'static mut PageTable { let addr = *KERNELPAGE.lock(); let ptr: *mut PageTable = addr as *mut PageTable; &mut *ptr } fn kvmmap(va: VirtAddr, pa: PhysAddr, size: u64, perm: PteFlag) { match map_pages(va, pa, size, perm) { Ok(_) => {}, Err(e) => panic!("mappages error: {}", e), } } fn map_pages(va: VirtAddr, mut pa: PhysAddr, size: u64, perm: PteFlag) -> Result<(), &'static str> { let page_table = unsafe { get_root_page() }; let va_start = va.align_down(); let va_end = VirtAddr::new_truncate(va.as_u64() + size - 1).align_down(); let mut page_addr = va_start; loop { map_page(page_table, page_addr, pa, perm, PageTableLevel::Two)?; if page_addr == va_end { break; } page_addr += PAGESIZE; pa += PAGESIZE; } Ok(()) } fn map_page(page_table: &mut PageTable, va: VirtAddr, pa: PhysAddr, perm: PteFlag, level: PageTableLevel) -> Result<(), &'static str> { if va >= VirtAddr::new(MAXVA) { return Err("map_page: virtual address over MAX address") } let index = va.get_index(level); let pte = &mut page_table[index]; match level.next_level() { None => { if pte.is_unused() { pte.set_addr(pa.as_pte(), perm | PteFlag::PTE_VALID); Ok(()) } else { Err("map_page: remap") } }, Some(next_level) => { if pte.is_unused() { let ptr = kalloc();
if ptr == 0 as *mut u8 { return Err("kalloc failed in map_page"); } let addr = PhysAddr::new(ptr as *const _ as u64); pte.set_addr(addr.as_pte(), PteFlag::PTE_VALID); } let next_table = unsafe { &mut *(pte.addr() as *mut PageTable) }; map_page(next_table, va, pa, perm, next_level) } } }
function_block-function_prefix_line
[ { "content": "/// Allocate one 4096-byte page of physical memory.\n\n/// Returns a pointer that the kernel can use.\n\n/// Returns 0 if the memory cannot be allocated.\n\npub fn kalloc() -> *mut u8 {\n\n unsafe {\n\n let layout = Layout::from_size_align(PAGESIZE as usize, 4096).unwrap();\n\n le...
Rust
src/lib.rs
duallsistemas/libduallnet
e7dd019c8fa2d98d1ecb41e28bd1b68c5ad880ae
#[cfg(target_os = "windows")] extern crate winapi; use std::io::{Error, ErrorKind}; use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; use std::time::Duration; #[cfg(target_os = "windows")] use winapi::shared::minwindef::DWORD; #[cfg(target_os = "windows")] use winapi::shared::winerror::{WSAEAFNOSUPPORT, WSAETIMEDOUT}; use libc::{c_char, c_int, size_t}; use mac_address::get_mac_address; use sntp_request::{SntpRequest, SntpUnixTimeResult}; mod utils; #[no_mangle] pub unsafe extern "C" fn dn_version() -> *const c_char { concat!(env!("CARGO_PKG_VERSION"), '\0').as_ptr() as *const c_char } #[no_mangle] pub unsafe extern "C" fn dn_lookup_host( hostname: *const c_char, prefer_ipv4: bool, ip: *mut c_char, size: size_t, ) -> c_int { if hostname.is_null() || ip.is_null() || size <= 0 { return -1; } match vec![from_c_str!(hostname).unwrap(), "0"] .join(":") .to_socket_addrs() { Ok(addrs) => { for addr in addrs { if prefer_ipv4 && !addr.is_ipv4() { continue; } let mut resolved_ip = addr.to_string(); resolved_ip.truncate(resolved_ip.len() - ":0".len()); let dest_ip = to_c_str!(resolved_ip).unwrap(); copy_c_str!(dest_ip, ip, size); return 0; } -2 } Err(_) => -3, } } #[no_mangle] pub unsafe extern "C" fn dn_connection_health(ip: *const c_char, port: u16, timeout: u64) -> c_int { if ip.is_null() || port <= 0 { return -1; } match format!("{}:{}", from_c_str!(ip).unwrap(), port).parse::<SocketAddr>() { Ok(addr) => match TcpStream::connect_timeout(&addr, Duration::from_millis(timeout)) { Ok(_) => 0, Err(error) => { if error.kind() == ErrorKind::TimedOut { return -2; } -3 } }, Err(_) => -4, } } #[no_mangle] pub unsafe extern "C" fn dn_mac_address(mac_addr: *mut c_char, size: size_t) -> c_int { if mac_addr.is_null() || size <= 0 { return -1; } match get_mac_address() { Ok(Some(ma)) => { let addr = to_c_str!(ma.to_string()).unwrap(); copy_c_str!(addr, mac_addr, size); 0 } Ok(None) => -2, Err(_) => -3, } } #[no_mangle] pub unsafe extern "C" fn dn_sntp_request( addr: *const c_char, timeout: u64, timestamp: *mut i64, ) -> c_int { if timestamp.is_null() { return -1; } let sntp = SntpRequest::new(); if (timeout > 0) && !sntp.set_timeout(Duration::from_millis(timeout)).is_ok() { return -1; } let result: SntpUnixTimeResult; if addr.is_null() { result = sntp.get_unix_time(); } else { result = sntp.get_unix_time_by_addr(from_c_str!(addr).unwrap()); } if sntp.is_kiss_of_death() { return -3; } match result { Ok(ts) => { *timestamp = ts; 0 } Err(error) => { if Error::last_os_error().kind() == ErrorKind::InvalidInput { return -3; } #[cfg(target_os = "windows")] match Error::last_os_error().raw_os_error().unwrap_or(0) as DWORD { WSAETIMEDOUT => return -2, WSAEAFNOSUPPORT => return -3, _ => -4, }; match error.kind() { ErrorKind::TimedOut => -2, ErrorKind::InvalidInput => -3, _ => -4, } } } } #[cfg(test)] mod tests { use super::*; use std::thread; #[test] fn version() { unsafe { assert_eq!( from_c_str!(dn_version()).unwrap(), env!("CARGO_PKG_VERSION") ); } } #[test] fn lookup_host() { unsafe { let ip: [c_char; 45] = [0; 45]; assert_eq!( dn_lookup_host(std::ptr::null(), true, ip.as_ptr() as *mut c_char, ip.len()), -1 ); assert_eq!( dn_lookup_host( to_c_str!("::1").unwrap().as_ptr(), true, std::ptr::null_mut(), ip.len() ), -1 ); assert_eq!( dn_lookup_host( to_c_str!("::1").unwrap().as_ptr(), true, ip.as_ptr() as *mut c_char, 0 ), -1 ); assert_eq!( dn_lookup_host( to_c_str!("::1").unwrap().as_ptr(), true, ip.as_ptr() as *mut c_char, ip.len() ), -2 ); assert_eq!( dn_lookup_host( to_c_str!("abc123").unwrap().as_ptr(), false, ip.as_ptr() as *mut c_char, ip.len() ), -3 ); assert_eq!( dn_lookup_host( to_c_str!("localhost").unwrap().as_ptr(), true, ip.as_ptr() as *mut c_char, ip.len(), ), 0 ); let len = length!(ip.as_ptr()); assert_eq!(len, 9); assert_eq!( compare!( ip.as_ptr(), to_c_str!("127.0.0.1").unwrap().as_ptr(), len + 1 ), 0 ); assert_eq!( dn_lookup_host( to_c_str!("localhost").unwrap().as_ptr(), false, ip.as_ptr() as *mut c_char, ip.len(), ), 0 ); let len = length!(ip.as_ptr()); assert_eq!(len, 5); assert_eq!( compare!(ip.as_ptr(), to_c_str!("[::1]").unwrap().as_ptr(), len + 1), 0 ); } } #[test] fn connection_health() { unsafe { assert_eq!(dn_connection_health(std::ptr::null_mut(), 123, 3000), -1); assert_eq!( dn_connection_health(to_c_str!("127.0.0.1").unwrap().as_ptr(), 0, 3000), -1 ); assert_eq!( dn_connection_health(to_c_str!("54.94.220.237").unwrap().as_ptr(), 443, 3000), 0 ); } } #[test] fn mac_address() { unsafe { let mac_addr: [c_char; 18] = [0; 18]; assert_eq!(dn_mac_address(std::ptr::null_mut(), mac_addr.len()), -1); assert_eq!(dn_mac_address(mac_addr.as_ptr() as *mut c_char, 0), -1); dn_mac_address(mac_addr.as_ptr() as *mut c_char, mac_addr.len()); let len = length!(mac_addr.as_ptr()); assert_eq!(len, 17); let mac = format!("{}", get_mac_address().unwrap().unwrap()); assert_eq!( compare!(mac_addr.as_ptr(), to_c_str!(mac).unwrap().as_ptr(), len + 1), 0 ); } } #[test] fn sntp_request() { unsafe { let addr = to_c_str!("pool.ntp.org:123").unwrap().as_ptr(); let mut ts: i64 = 0; assert_eq!(dn_sntp_request(addr, 0, std::ptr::null_mut()), -1); assert_eq!( dn_sntp_request(to_c_str!("pool.ntp.org").unwrap().as_ptr(), 100, &mut ts), -3 ); assert_eq!( dn_sntp_request(to_c_str!(":123").unwrap().as_ptr(), 100, &mut ts), -3 ); assert_eq!( dn_sntp_request( to_c_str!("pool.ntp.org:321").unwrap().as_ptr(), 100, &mut ts ), if cfg!(target_os = "windows") { -2 } else { -4 } ); let mut ts1: i64 = 0; let mut ts2: i64 = 0; assert_eq!( dn_sntp_request( to_c_str!("time.google.com:123").unwrap().as_ptr(), 0, &mut ts1 ), 0 ); thread::sleep(Duration::from_secs(1)); assert_eq!( dn_sntp_request( to_c_str!("time.cloudflare.com:123").unwrap().as_ptr(), 0, &mut ts2 ), 0 ); assert!(ts2 > ts1); } } }
#[cfg(target_os = "windows")] extern crate winapi; use std::io::{Error, ErrorKind}; use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; use std::time::Duration; #[cfg(target_os = "windows")] use winapi::shared::minwindef::DWORD; #[cfg(target_os = "windows")] use winapi::shared::winerror::{WSAEAFNOSUPPORT, WSAETIMEDOUT}; use libc::{c_char, c_int, size_t}; use mac_address::get_mac_address; use sntp_request::{SntpRequest, SntpUnixTimeResult}; mod utils; #[no_mangle] pub unsafe extern "C" fn dn_version() -> *const c_char { concat!(env!("CARGO_PKG_VERSION"), '\0').as_ptr() as *const c_char } #[no_mangle] pub unsafe extern "C" fn dn_lookup_host( hostname: *const c_char, prefer_ipv4: bool, ip: *mut c_char, size: size_t, ) -> c_int { if hostname.is_null() || ip.is_null() || size <= 0 { return -1; } match vec![from_c_str!(hostname).unwrap(), "0"] .join(":") .to_socket_addrs() { Ok(addrs) => { for addr in addrs { if prefer_ipv4 && !addr.is_ipv4() { continue; } let mut resolved_ip = addr.to_string(); resolved_ip.truncate(resolved_ip.len() - ":0".len()); let dest_ip = to_c_str!(resolved_ip).unwrap(); copy_c_str!(dest_ip, ip, size); return 0; } -2 } Err(_) => -3, } } #[no_mangle] pub unsafe extern "C" fn dn_connection_health(ip: *const c_char, port: u16, timeout: u64) -> c_int { if ip.is_null() || port <= 0 { return -1; } match format!("{}:{}", from_c_str!(ip).unwrap(), port).parse::<SocketAddr>() { Ok(addr) => match TcpStream::connect_timeout(&addr, Duration::from_millis(timeout)) { Ok(_) => 0, Err(error) => { if error.kind() == ErrorKind::TimedOut { return -2; } -3 } }, Err(_) => -4, } } #[no_mangle] pub unsafe extern "C" fn dn_mac_address(mac_addr: *mut c_char, size: size_t) -> c_int { if mac_addr.is_null() || size <= 0 { return -1; } match get_mac_address() { Ok(Some(ma)) => { let addr = to_c_str!(ma.to_string()).unwrap(); copy_c_str!(addr, mac_addr, size); 0 } Ok(None) => -2, Err(_) => -3, } } #[no_mangle]
#[cfg(test)] mod tests { use super::*; use std::thread; #[test] fn version() { unsafe { assert_eq!( from_c_str!(dn_version()).unwrap(), env!("CARGO_PKG_VERSION") ); } } #[test] fn lookup_host() { unsafe { let ip: [c_char; 45] = [0; 45]; assert_eq!( dn_lookup_host(std::ptr::null(), true, ip.as_ptr() as *mut c_char, ip.len()), -1 ); assert_eq!( dn_lookup_host( to_c_str!("::1").unwrap().as_ptr(), true, std::ptr::null_mut(), ip.len() ), -1 ); assert_eq!( dn_lookup_host( to_c_str!("::1").unwrap().as_ptr(), true, ip.as_ptr() as *mut c_char, 0 ), -1 ); assert_eq!( dn_lookup_host( to_c_str!("::1").unwrap().as_ptr(), true, ip.as_ptr() as *mut c_char, ip.len() ), -2 ); assert_eq!( dn_lookup_host( to_c_str!("abc123").unwrap().as_ptr(), false, ip.as_ptr() as *mut c_char, ip.len() ), -3 ); assert_eq!( dn_lookup_host( to_c_str!("localhost").unwrap().as_ptr(), true, ip.as_ptr() as *mut c_char, ip.len(), ), 0 ); let len = length!(ip.as_ptr()); assert_eq!(len, 9); assert_eq!( compare!( ip.as_ptr(), to_c_str!("127.0.0.1").unwrap().as_ptr(), len + 1 ), 0 ); assert_eq!( dn_lookup_host( to_c_str!("localhost").unwrap().as_ptr(), false, ip.as_ptr() as *mut c_char, ip.len(), ), 0 ); let len = length!(ip.as_ptr()); assert_eq!(len, 5); assert_eq!( compare!(ip.as_ptr(), to_c_str!("[::1]").unwrap().as_ptr(), len + 1), 0 ); } } #[test] fn connection_health() { unsafe { assert_eq!(dn_connection_health(std::ptr::null_mut(), 123, 3000), -1); assert_eq!( dn_connection_health(to_c_str!("127.0.0.1").unwrap().as_ptr(), 0, 3000), -1 ); assert_eq!( dn_connection_health(to_c_str!("54.94.220.237").unwrap().as_ptr(), 443, 3000), 0 ); } } #[test] fn mac_address() { unsafe { let mac_addr: [c_char; 18] = [0; 18]; assert_eq!(dn_mac_address(std::ptr::null_mut(), mac_addr.len()), -1); assert_eq!(dn_mac_address(mac_addr.as_ptr() as *mut c_char, 0), -1); dn_mac_address(mac_addr.as_ptr() as *mut c_char, mac_addr.len()); let len = length!(mac_addr.as_ptr()); assert_eq!(len, 17); let mac = format!("{}", get_mac_address().unwrap().unwrap()); assert_eq!( compare!(mac_addr.as_ptr(), to_c_str!(mac).unwrap().as_ptr(), len + 1), 0 ); } } #[test] fn sntp_request() { unsafe { let addr = to_c_str!("pool.ntp.org:123").unwrap().as_ptr(); let mut ts: i64 = 0; assert_eq!(dn_sntp_request(addr, 0, std::ptr::null_mut()), -1); assert_eq!( dn_sntp_request(to_c_str!("pool.ntp.org").unwrap().as_ptr(), 100, &mut ts), -3 ); assert_eq!( dn_sntp_request(to_c_str!(":123").unwrap().as_ptr(), 100, &mut ts), -3 ); assert_eq!( dn_sntp_request( to_c_str!("pool.ntp.org:321").unwrap().as_ptr(), 100, &mut ts ), if cfg!(target_os = "windows") { -2 } else { -4 } ); let mut ts1: i64 = 0; let mut ts2: i64 = 0; assert_eq!( dn_sntp_request( to_c_str!("time.google.com:123").unwrap().as_ptr(), 0, &mut ts1 ), 0 ); thread::sleep(Duration::from_secs(1)); assert_eq!( dn_sntp_request( to_c_str!("time.cloudflare.com:123").unwrap().as_ptr(), 0, &mut ts2 ), 0 ); assert!(ts2 > ts1); } } }
pub unsafe extern "C" fn dn_sntp_request( addr: *const c_char, timeout: u64, timestamp: *mut i64, ) -> c_int { if timestamp.is_null() { return -1; } let sntp = SntpRequest::new(); if (timeout > 0) && !sntp.set_timeout(Duration::from_millis(timeout)).is_ok() { return -1; } let result: SntpUnixTimeResult; if addr.is_null() { result = sntp.get_unix_time(); } else { result = sntp.get_unix_time_by_addr(from_c_str!(addr).unwrap()); } if sntp.is_kiss_of_death() { return -3; } match result { Ok(ts) => { *timestamp = ts; 0 } Err(error) => { if Error::last_os_error().kind() == ErrorKind::InvalidInput { return -3; } #[cfg(target_os = "windows")] match Error::last_os_error().raw_os_error().unwrap_or(0) as DWORD { WSAETIMEDOUT => return -2, WSAEAFNOSUPPORT => return -3, _ => -4, }; match error.kind() { ErrorKind::TimedOut => -2, ErrorKind::InvalidInput => -3, _ => -4, } } } }
function_block-full_function
[ { "content": " let buf = $src.to_bytes_with_nul();\n\n let mut buf_size = $size;\n\n if buf_size > buf.len() {\n\n buf_size = buf.len()\n\n }\n\n copy!(buf.as_ptr(), $dest, buf_size);\n\n };\n\n}\n\n\n\n#[doc(hidden)]\n\n#[macro_export]\n\nmacro_rules! compare {\...
Rust
src/main.rs
scru128/gen_test
3590ba236f29b8323b6b5ba93c0bcc2b703df4cf
use std::env::args; use std::io; use std::io::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; const STATS_INTERVAL: u64 = 10 * 1000; fn main() { if let Some(arg) = args().nth(1) { let usage = "Usage: any-command-that-prints-identifiers-infinitely | scru128-test"; if arg == "-h" || arg == "--help" { println!("{}", usage); } else { eprintln!("{}", usage); eprintln!("Error: unknown argument: {}", arg); } return; } let stdin = io::stdin(); let mut reader = stdin.lock(); let mut buffer = String::with_capacity(32); println!( "Reading IDs from stdin and will show stats every {} seconds. Press Ctrl-C to quit.", STATS_INTERVAL / 1000 ); let mut st = Status::default(); let mut prev = Identifier::default(); while reader.read_line(&mut buffer).unwrap() > 0 { let line = buffer .strip_suffix('\n') .map_or(buffer.as_str(), |x| x.strip_suffix('\r').unwrap_or(x)); let opt = Identifier::new(line); buffer.clear(); if opt.is_some() { st.n_processed += 1; } else { eprintln!("Error: invalid string representation"); st.n_errors += 1; continue; } let e = opt.unwrap(); if e.str_value <= prev.str_value { eprintln!("Error: string representation not monotonically ordered"); st.n_errors += 1; continue; } if e.int_value <= prev.int_value { eprintln!("Error: integer representation not monotonically ordered"); st.n_errors += 1; continue; } if e.timestamp < prev.timestamp { eprintln!("Error: clock went backwards"); st.n_errors += 1; continue; } else if e.timestamp == prev.timestamp && e.counter_hi < prev.counter_hi { eprintln!("Error: counter_hi went backwards within same timestamp"); st.n_errors += 1; continue; } else if e.timestamp == prev.timestamp && e.counter_hi == prev.counter_hi && e.counter_lo <= prev.counter_lo { eprintln!( "Error: counter_lo not monotonically ordered within same timestamp and counter_hi" ); st.n_errors += 1; continue; } if st.ts_first == 0 { st.ts_first = e.timestamp; } st.ts_last = e.timestamp; count_set_bits_by_pos(&mut st.n_ones_by_bit_entropy, e.entropy); if e.counter_lo != prev.counter_lo + 1 && !(e.counter_lo == 0 && prev.counter_lo == 0xff_ffff) { if st.ts_last_counter_lo_update > 0 { st.n_counter_lo_update += 1; st.sum_intervals_counter_lo_update += e.timestamp - st.ts_last_counter_lo_update; } st.ts_last_counter_lo_update = e.timestamp; count_set_bits_by_pos(&mut st.n_ones_by_bit_counter_lo, e.counter_lo); } if e.counter_hi == prev.counter_hi + 1 && e.timestamp == prev.timestamp && e.counter_lo == 0 && prev.counter_lo == 0xff_ffff { st.n_counter_hi_increment += 1; } else if e.counter_hi != prev.counter_hi { if st.ts_last_counter_hi_update > 0 { st.n_counter_hi_update += 1; st.sum_intervals_counter_hi_update += e.timestamp - st.ts_last_counter_hi_update; } st.ts_last_counter_hi_update = e.timestamp; count_set_bits_by_pos(&mut st.n_ones_by_bit_counter_hi, e.counter_hi); } if e.timestamp > st.ts_last_stats_print + STATS_INTERVAL { if st.ts_last_stats_print > 0 { st.print().unwrap(); } st.ts_last_stats_print = e.timestamp; } prev = e; } if st.n_processed > 0 { st.print().unwrap(); } else { eprintln!("Error: no valid ID processed"); } } #[derive(Debug, Default)] struct Status { n_processed: usize, n_errors: usize, ts_first: u64, ts_last: u64, n_ones_by_bit_entropy: [usize; 32], n_counter_lo_update: usize, ts_last_counter_lo_update: u64, sum_intervals_counter_lo_update: u64, n_ones_by_bit_counter_lo: [usize; 24], n_counter_hi_increment: usize, n_counter_hi_update: usize, ts_last_counter_hi_update: u64, sum_intervals_counter_hi_update: u64, n_ones_by_bit_counter_hi: [usize; 24], ts_last_stats_print: u64, } impl Status { fn print(&self) -> Result<(), io::Error> { let time_elapsed = self.ts_last - self.ts_first; let mut buf = io::BufWriter::new(io::stdout()); writeln!(buf)?; writeln!(buf, "{:<52} {:>8} {:>12}", "STAT", "EXPECTED", "ACTUAL")?; writeln!( buf, "{:<52} {:>8} {:>12.1}", "Seconds from first input ID to last (sec)", "NA", time_elapsed as f64 / 1000.0 )?; writeln!( buf, "{:<52} {:>8} {:>12}", "Number of valid IDs processed", "NA", self.n_processed )?; writeln!( buf, "{:<52} {:>8} {:>12}", "Number of invalid IDs skipped", 0, self.n_errors )?; writeln!( buf, "{:<52} {:>8} {:>12.3}", "Mean number of IDs per millisecond", "NA", self.n_processed as f64 / time_elapsed as f64 )?; writeln!( buf, "{:<52} {:>8} {:>12.3}", "Current time less timestamp of last ID (sec)", "~0", get_current_time() - (self.ts_last as f64) / 1000.0 )?; writeln!( buf, "{:<52} {:>8} {:>12}", "Number of counter_hi increments", "Few", self.n_counter_hi_increment )?; writeln!( buf, "{:<52} {:>8} {:>12.3}", "Mean interval of counter_hi updates (msec)", "~1000", self.sum_intervals_counter_hi_update as f64 / self.n_counter_hi_update as f64 )?; writeln!( buf, "{:<52} {:>8} {:>12.3}", "Mean interval of counter_lo updates (msec)", "~1", self.sum_intervals_counter_lo_update as f64 / self.n_counter_lo_update as f64 )?; writeln!( buf, "{:<52} {:>8} {:>12}", "1/0 ratio by bit of counter_hi at reset (min-max)", "~0.500", summarize_n_set_bits_by_pos( &self.n_ones_by_bit_counter_hi, self.n_counter_hi_update + 1 ) )?; writeln!( buf, "{:<52} {:>8} {:>12}", "1/0 ratio by bit of counter_lo at reset (min-max)", "~0.500", summarize_n_set_bits_by_pos( &self.n_ones_by_bit_counter_lo, self.n_counter_lo_update + 1 ) )?; writeln!( buf, "{:<52} {:>8} {:>12}", "1/0 ratio by bit of entropy (min-max)", "~0.500", summarize_n_set_bits_by_pos(&self.n_ones_by_bit_entropy, self.n_processed) )?; Ok(()) } } #[derive(Clone, Eq, PartialEq, Hash, Debug, Default)] struct Identifier { str_value: [u8; 25], int_value: u128, timestamp: u64, counter_hi: u32, counter_lo: u32, entropy: u32, } impl Identifier { fn new(str_value: &str) -> Option<Self> { const DECODE_MAP: [u8; 256] = [ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ]; if str_value.len() != 25 { return None; } let mut fixed_str = [0; 25]; let bs = str_value.as_bytes(); let mut int_value = 0u128; for i in 0..25 { fixed_str[i] = bs[i]; let n = DECODE_MAP[bs[i] as usize] as u128; if n == 0xff { return None; } int_value = int_value.checked_mul(36)?.checked_add(n)?; } Some(Self { str_value: fixed_str, int_value, timestamp: (int_value >> 80) as u64, counter_hi: ((int_value >> 56) & 0xff_ffff) as u32, counter_lo: ((int_value >> 32) & 0xff_ffff) as u32, entropy: (int_value & 0xffff_ffff) as u32, }) } } fn get_current_time() -> f64 { SystemTime::now() .duration_since(UNIX_EPOCH) .expect("clock may have gone backwards") .as_secs_f64() } #[allow(unused_mut)] fn count_set_bits_by_pos(counts: &mut [usize], mut n: u32) { #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] let mut n: usize = n as usize; for i in 0..counts.len() { counts[counts.len() - 1 - i] += (n & 1) as usize; n >>= 1; } } fn summarize_n_set_bits_by_pos(counts: &[usize], n_samples: usize) -> String { let mut min = 1.0; let mut max = 0.0; for e in counts { let p = *e as f64 / n_samples as f64; if p < min { min = p; } if p > max { max = p; } } format!("{:.3}-{:.3}", min, max) }
use std::env::args; use std::io; use std::io::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; const STATS_INTERVAL: u64 = 10 * 1000; fn main() { if let Some(arg) = args().nth(1) { let usage = "Usage: any-command-that-prints-identifiers-infinitely | scru128-test"; if arg == "-h" || arg == "--help" { println!("{}", usage); } else { eprintln!("{}", usage); eprintln!("Error: unknown argument: {}", arg); } return; } let stdin = io::stdin(); let mut reader = stdin.lock(); let mut buffer = String::with_capacity(32); println!( "Reading IDs from stdin and will show stats every {} seconds. Press Ctrl-C to quit.", STATS_INTERVAL / 1000 ); let mut st = Status::default(); let mut prev = Identifier::default(); while reader.read_line(&mut buffer).unwrap() > 0 { let line = buffer .strip_suffix('\n') .map_or(buffer.as_str(), |x| x.strip_suffix('\r').unwrap_or(x)); let opt = Identifier::new(line); buffer.clear(); if opt.is_some() { st.n_processed += 1; } else { eprintln!("Error: invalid string representation"); st.n_errors += 1; continue; } let e = opt.unwrap(); if e.str_value <= prev.str_value { eprintln!("Error: string representation not monotonically ordered"); st.n_errors += 1; continue; } if e.int_value <= prev.int_value { eprintln!("Error: integer representation not monotonically ordered"); st.n_errors += 1; continue; } if e.timestamp < prev.timestamp { eprintln!("Error: clock went backwards"); st.n_errors += 1; continue; } else if e.timestamp == prev.timestamp && e.counter_hi < prev.counter_hi { eprintln!("Error: counter_hi went backwards within same timestamp"); st.n_errors += 1; continue; } else if e.timestamp == prev.timestamp && e.counter_hi == prev.counter_hi && e.counter_lo <= prev.counter_lo { eprintln!( "Error: counter_lo not monotonically ordered within same timestamp and counter_hi" ); st.n_errors += 1; continue; } if st.ts_first == 0 { st.ts_first = e.timestamp; } st.ts_last = e.timestamp; count_set_bits_by_pos(&mut st.n_ones_by_bit_entropy, e.entropy); if e.counter_lo != prev.counter_lo + 1 && !(e.counter_lo == 0 && prev.counter_lo == 0xff_ffff) { if st.ts_last_counter_lo_update > 0 { st.n_counter_lo_update += 1; st.sum_intervals_counter_lo_update += e.timestamp - st.ts_last_counter_lo_update; } st.ts_last_counter_lo_update = e.timestamp; count_set_bits_by_pos(&mut st.n_ones_by_bit_counter_lo, e.counter_lo); } if e.counter_hi == prev.counter_hi + 1 && e.timestamp == prev.timestamp && e.counter_lo == 0 && prev.counter_lo == 0xff_ffff { st.n_counter_hi_increment += 1; } else if e.counter_hi != prev.counter_hi { if st.ts_last_counter_hi_update > 0 { st.n_counter_hi_update += 1; st.sum_intervals_counter_hi_update += e.timestamp - st.ts_last_counter_hi_update; } st.ts_last_counter_hi_update = e.timestamp; count_set_bits_by_pos(&mut st.n_ones_by_bit_counter_hi, e.counter_hi); } if e.timestamp > st.ts_last_stats_print + STATS_INTERVAL { if st.ts_last_stats_print > 0 { st.print().unwrap(); } st.ts_last_stats_print = e.timestamp; } prev = e; } if st.n_processed > 0 { st.print().unwrap(); } else { eprintln!("Error: no valid ID processed"); } } #[derive(Debug, Default)] struct Status { n_processed: usize, n_errors: usize, ts_first: u64, ts_last: u64, n_ones_by_bit_entropy: [usize; 32], n_counter_lo_update: usize, ts_last_counter_lo_update: u64, sum_intervals_counter_lo_update: u64, n_ones_by_bit_counter_lo: [usize; 24], n_counter_hi_increment: usize, n_counter_hi_update: usize, ts_last_counter_hi_update: u64, sum_intervals_counter_hi_update: u64, n_ones_by_bit_counter_hi: [usize; 24], ts_last_stats_print: u64, } impl Status { fn print(&self) -> Result<(), io::Error> { let time_elapsed = self.ts_last - self.ts_first; let mut buf = io::BufWriter::new(io::stdout()); writeln!(buf)?; writeln!(buf, "{:<52} {:>8} {:>12}", "STAT", "EXPECTED", "ACTUAL")?; writeln!( buf, "{:<52} {:>8} {:>12.1}", "Seconds from first input ID to last (sec)", "NA", time_elapsed as f64 / 1000.0 )?; writeln!( buf, "{:<52} {:>8} {:>12}", "Number of valid IDs processed", "NA", self.n_processed )?; writeln!( buf, "{:<52} {:>8} {:>12}", "Number of invalid IDs skipped", 0, self.n_errors )?; writeln!( buf, "{:<52} {:>8} {:>12.3}", "Mean number of IDs per millisecond", "NA", self.n_processed as f64 / time_elapsed as f64 )?; writeln!( buf, "{:<52} {:>8} {:>12.3}", "Current time less timestamp of last ID (sec)", "~0", get_current_time() - (self.ts_last as f64) / 1000.0 )?; writeln!( buf, "{:<52} {:>8} {:>12}", "Number of counter_hi increments", "Few", self.n_counter_hi_increment )?; writeln!( buf, "{:<52} {:>8} {:>12.3}", "Mean interval of counter_hi updates (msec)", "~1000", self.sum_intervals_counter_hi_update as f64 / self.n_counter_hi_update as f64 )?; writeln!( buf, "{:<52} {:>8} {:>12.3}", "Mean interval of counter_lo updates (msec)", "~1", self.sum_intervals_counter_lo_update as f64 / self.n_counter_lo_update as f64 )?; writeln!( buf, "{:<52} {:>8} {:>12}", "1/0 ratio by bit of counter_hi at reset (min-max)", "~0.500", summarize_n_set_bits_by_pos( &self.n_ones_by_bit_counter_hi, self.n_counter_hi_update + 1 ) )?; writeln!( buf, "{:<52} {:>8} {:>12}", "1/0 ratio by bit of counter_lo at reset (min-max)", "~0.500", summarize_n_set_bits_by_pos( &self.n_ones_by_bit_counter_lo, self.n_counter_lo_update + 1 ) )?; writeln!( buf, "{:<52} {:>8} {:>12}", "1/0 ratio by bit of entropy (min-max)", "~0.500", summarize_n_set_bits_by_pos(&self.n_ones_by_bit_entropy, self.n_processed) )?; Ok(()) } } #[derive(Clone, Eq, PartialEq, Hash, Debug, Default)] struct Identifier { str_value: [u8; 25], int_value: u128, timestamp: u64, counter_hi: u32, counter_lo: u32, entropy: u32, } impl Identifier { fn new(str_value: &str) -> Option<Self> { const DECODE_MAP: [u8; 256] = [ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0a, 0
timestamp: (int_value >> 80) as u64, counter_hi: ((int_value >> 56) & 0xff_ffff) as u32, counter_lo: ((int_value >> 32) & 0xff_ffff) as u32, entropy: (int_value & 0xffff_ffff) as u32, }) } } fn get_current_time() -> f64 { SystemTime::now() .duration_since(UNIX_EPOCH) .expect("clock may have gone backwards") .as_secs_f64() } #[allow(unused_mut)] fn count_set_bits_by_pos(counts: &mut [usize], mut n: u32) { #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] let mut n: usize = n as usize; for i in 0..counts.len() { counts[counts.len() - 1 - i] += (n & 1) as usize; n >>= 1; } } fn summarize_n_set_bits_by_pos(counts: &[usize], n_samples: usize) -> String { let mut min = 1.0; let mut max = 0.0; for e in counts { let p = *e as f64 / n_samples as f64; if p < min { min = p; } if p > max { max = p; } } format!("{:.3}-{:.3}", min, max) }
x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ]; if str_value.len() != 25 { return None; } let mut fixed_str = [0; 25]; let bs = str_value.as_bytes(); let mut int_value = 0u128; for i in 0..25 { fixed_str[i] = bs[i]; let n = DECODE_MAP[bs[i] as usize] as u128; if n == 0xff { return None; } int_value = int_value.checked_mul(36)?.checked_add(n)?; } Some(Self { str_value: fixed_str, int_value,
function_block-random_span
[ { "content": "# SCRU128 Generator Tester\n\n\n\n[![GitHub tag](https://img.shields.io/github/v/tag/scru128/gen_test)](https://github.com/scru128/gen_test)\n\n[![License](https://img.shields.io/github/license/scru128/gen_test)](https://github.com/scru128/gen_test/blob/main/LICENSE)\n\n\n\nA command-line SCRU128 ...
Rust
src/runner.rs
sile/hone
460e0bd51455fa479e8487fb54d6f9ba8d9a8cf3
use self::command::CommandRunner; use self::tempdir::TempDirs; use crate::event::{Event, EventReader, EventWriter}; use crate::metric::MetricInstance; use crate::param::{ParamInstance, ParamValue}; use crate::rpc; use crate::study::StudySpec; use crate::trial::{Observation, ObservationId, TrialId}; use crate::tuners::{Action, Tune, Tuner}; use crate::types::Scope; use std::io::{BufRead, Write}; use std::num::NonZeroUsize; use std::path::PathBuf; use std::time::{Duration, Instant}; mod command; mod loader; mod tempdir; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct StudyRunnerOpt { pub study: StudySpec, pub workers: NonZeroUsize, pub repeat: Option<usize>, } #[derive(Debug)] pub struct StudyRunner<W> { output: EventWriter<W>, runnings: Vec<CommandRunner>, next_obs_id: ObservationId, next_trial_id: TrialId, rpc_channel: rpc::Channel, tuner: Tuner, opt: StudyRunnerOpt, start_time: Instant, elapsed_offset: Duration, tempdirs: TempDirs, terminating: bool, } impl<W: Write> StudyRunner<W> { pub fn new(output: W, opt: StudyRunnerOpt) -> anyhow::Result<Self> { let tuner = opt.study.tuner.build()?; let rpc_channel = rpc::spawn_rpc_server()?; let mut output = EventWriter::new(output); output.write(Event::study_started())?; output.write(Event::study_defined(opt.study.clone()))?; Ok(Self { output, runnings: Vec::new(), rpc_channel, next_obs_id: ObservationId::new(0), next_trial_id: TrialId::new(0), tuner, opt, start_time: Instant::now(), tempdirs: TempDirs::new(), elapsed_offset: Duration::new(0, 0), terminating: false, }) } pub fn load_study<R: BufRead>(&mut self, reader: EventReader<R>) -> anyhow::Result<()> { let mut loader = self::loader::StudyLoader::new(self); loader.load(reader) } pub fn run(mut self) -> anyhow::Result<()> { self.start_time = Instant::now(); let mut finished_count = 0; let mut did_nothing; while self.opt.repeat.map_or(true, |n| finished_count < n) { did_nothing = true; while self.runnings.len() < self.opt.workers.get() && !self.terminating { let action = self.tuner.next_action(); let waiting = matches!(action, Some(Action::WaitObservations)); self.handle_action(action)?; if waiting { break; } else { did_nothing = false; } } while let Some(message) = self.rpc_channel.try_recv() { self.handle_message(message)?; did_nothing = false; } let mut i = 0; while i < self.runnings.len() { if self.runnings[i].is_exited()? { finished_count += 1; let obs = self.runnings.swap_remove(i).into_obs(); self.tell_finished_obs(obs, self.start_time.elapsed())?; did_nothing = false; } else { i += 1; } } if did_nothing { std::thread::sleep(Duration::from_millis(1)); } } Ok(()) } fn tell_finished_obs(&mut self, obs: Observation, elapsed: Duration) -> anyhow::Result<()> { self.tuner.tell(&obs)?; self.finish_obs(obs, elapsed)?; Ok(()) } fn start_obs(&mut self, obs: Observation) -> anyhow::Result<()> { self.output.write(Event::observation_started( obs.id, obs.trial_id, self.elapsed_offset + self.start_time.elapsed(), ))?; self.runnings.push(CommandRunner::spawn( &self.opt.study, obs, self.rpc_channel.server_addr, )?); Ok(()) } fn finish_obs(&mut self, obs: Observation, elapsed: Duration) -> anyhow::Result<()> { let elapsed = self.elapsed_offset + elapsed; self.tempdirs.remove_obs_tempdir(obs.id); self.output .write(Event::observation_finished(obs, elapsed))?; Ok(()) } fn start_trial(&mut self, trial_id: TrialId) -> anyhow::Result<()> { self.output.write(Event::trial_started(trial_id))?; Ok(()) } fn finish_trial(&mut self, trial_id: TrialId) -> anyhow::Result<()> { self.tempdirs.remove_trial_tempdir(trial_id); self.output.write(Event::trial_finished(trial_id))?; Ok(()) } fn handle_action(&mut self, action: Option<Action>) -> anyhow::Result<()> { match action { None => { let obs = Observation::new( self.next_obs_id.fetch_and_increment(), self.next_trial_id.fetch_and_increment(), ); self.start_trial(obs.trial_id)?; self.start_obs(obs)?; } Some(Action::ResumeTrial { trial_id }) => { let obs = Observation::new(self.next_obs_id.fetch_and_increment(), trial_id); self.start_obs(obs)?; } Some(Action::FinishTrial { trial_id }) => { self.finish_trial(trial_id)?; } Some(Action::WaitObservations) => {} Some(Action::QuitOptimization) => { self.terminating = true; for worker in &mut self.runnings { worker.kill()?; } } } Ok(()) } fn handle_message(&mut self, message: rpc::Message) -> anyhow::Result<()> { match message { rpc::Message::Ask { req, reply } => { let value = self.handle_ask(req)?; reply.send(value)?; } rpc::Message::Tell { req, reply } => { self.handle_tell(req)?; reply.send(())?; } rpc::Message::Mktemp { req, reply } => { let path = self.handle_mktemp(req)?; reply.send(path)?; } } Ok(()) } fn handle_mktemp(&mut self, req: rpc::MktempReq) -> anyhow::Result<PathBuf> { match req.scope { Scope::Study => self.tempdirs.create_study_tempdir(req.parent.as_ref()), Scope::Trial => { let trial_id = self .runnings .iter() .find(|o| o.obs().id == req.observation_id) .ok_or_else(|| { anyhow::anyhow!("unknown observation: {:?}", req.observation_id) })? .obs() .trial_id; self.tempdirs .create_trial_tempdir(trial_id, req.parent.as_ref()) } Scope::Observation => self .tempdirs .create_obs_tempdir(req.observation_id, req.parent.as_ref()), } } fn handle_ask(&mut self, req: rpc::AskReq) -> anyhow::Result<ParamValue> { let obs = self .runnings .iter_mut() .find(|o| o.obs().id == req.observation_id) .ok_or_else(|| anyhow::anyhow!("unknown observation_id {}", req.observation_id.get()))? .obs_mut(); if let Some(instance) = obs.params.get(&req.param_name) { Ok(instance.value.clone()) } else { let value = self.tuner.ask(obs, &req.param_name, &req.param_type)?; obs.params.insert( req.param_name, ParamInstance::new(req.param_type, value.clone()), ); Ok(value) } } fn handle_tell(&mut self, req: rpc::TellReq) -> anyhow::Result<()> { let obs = self .runnings .iter_mut() .find(|o| o.obs().id == req.observation_id) .ok_or_else(|| anyhow::anyhow!("unknown observation_id {}", req.observation_id.get()))? .obs_mut(); obs.metrics.insert( req.metric_name, MetricInstance::new(req.metric_type, req.metric_value), ); Ok(()) } }
use self::command::CommandRunner; use self::tempdir::TempDirs; use crate::event::{Event, EventReader, EventWriter}; use crate::metric::MetricInstance; use crate::param::{ParamInstance, ParamValue}; use crate::rpc; use crate::study::StudySpec; use crate::trial::{Observation, ObservationId, TrialId}; use crate::tuners::{Action, Tune, Tuner}; use crate::types::Scope; use std::io::{BufRead, Write}; use std::num::NonZeroUsize; use std::path::PathBuf; use std::time::{Duration, Instant}; mod command; mod loader; mod tempdir; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct StudyRunnerOpt { pub study: StudySpec, pub workers: NonZeroUsize, pub repeat: Option<usize>, } #[derive(Debug)] pub struct StudyRunner<W> { output: EventWriter<W>, runnings: Vec<CommandRunner>, next_obs_id: ObservationId, next_trial_id: TrialId, rpc_channel: rpc::Channel, tuner: Tuner, opt: StudyRunnerOpt, start_time: Instant, elapsed_offset: Duration, tempdirs: TempDirs, terminating: bool, } impl<W: Write> StudyRunner<W> { pub fn new(output: W, opt: StudyRunnerOpt) -> anyhow::Result<Self> { let tuner = opt.study.tuner.build()?; let rpc_channel = rpc::spawn_rpc_server()?; let mut output = EventWriter::new(output); output.write(Event::study_started())?; output.write(Event::study_defined(opt.study.clone()))?; Ok(Self { output, runnings: Vec::new(), rpc_channel, next_obs_id: ObservationId::new(0), next_trial_id: TrialId::new(0), tuner, opt, start_time: Instant::now(), tempdirs: TempDirs::new(), elapsed_offset: Duration::new(0, 0), terminating: false, }) } pub fn load_study<R: BufRead>(&mut self, reader: EventReader<R>) -> anyhow::Result<()> { let mut loader = self::loader::StudyLoader::new(self); loader.load(reader) } pub fn run(mut self) -> anyhow::Result<()> { self.start_time = Instant::now(); let mut finished_count = 0; let mut did_nothing; while self.opt.repeat.map_or(true, |n| finished_count < n) { did_nothing = true; while self.runnings.len() < self.opt.workers.get() && !self.terminating { let action = self.tuner.next_action(); let waiting = matches!(action, Some(Action::WaitObservations)); self.handle_action(action)?; if waiting { break; } else { did_nothing = false; } } while let Some(message) = self.rpc_channel.try_recv() { self.handle_message(message)?; did_nothing = false; } let mut i = 0; while i < self.runnings.len() { if self.runnings[i].is_exited()? { finished_count += 1; let obs = self.runnings.swap_remove(i).into_obs(); self.tell_finished_obs(obs, self.start_time.elapsed())?; did_nothing = false; } else { i += 1; } } if did_nothing { std::thread::sleep(Duration::from_millis(1)); } } Ok(()) } fn tell_finished_obs(&mut self, obs: Observation, elapsed: Duration) -> anyhow::Result<()> { self.tuner.tell(&obs)?; self.finish_obs(obs, elapsed)?; Ok(()) } fn start_obs(&mut self, obs: Observation) -> anyhow::Result<()> { self.output.write(Event::observation_started( obs.id, obs.trial_id, self.elapsed_offset + self.start_time.elapsed(), ))?; self.runnings.push(CommandRunner::spawn( &self.opt.study, obs, self.rpc_channel.server_addr, )?); Ok(()) } fn finish_obs(&mut self, obs: Observation, elapsed: Duration) -> anyhow::Result<()> { let elapsed = self.elapsed_offset + elapsed; self.tempdirs.remove_obs_tempdir(obs.id); self.output .write(Event::observation_finished(obs, elapsed))?; Ok(()) } fn start_trial(&mut self, trial_id: TrialId) -> anyhow::Result<()> { self.output.write(Event::trial_started(trial_id))?; Ok(()) } fn finish_trial(&mut self, trial_id: TrialId) -> anyhow::Result<()> { self.tempdirs.remove_trial_tempdir(trial_id); self.output.write(Event::trial_finished(trial_id))?; Ok(()) }
fn handle_message(&mut self, message: rpc::Message) -> anyhow::Result<()> { match message { rpc::Message::Ask { req, reply } => { let value = self.handle_ask(req)?; reply.send(value)?; } rpc::Message::Tell { req, reply } => { self.handle_tell(req)?; reply.send(())?; } rpc::Message::Mktemp { req, reply } => { let path = self.handle_mktemp(req)?; reply.send(path)?; } } Ok(()) } fn handle_mktemp(&mut self, req: rpc::MktempReq) -> anyhow::Result<PathBuf> { match req.scope { Scope::Study => self.tempdirs.create_study_tempdir(req.parent.as_ref()), Scope::Trial => { let trial_id = self .runnings .iter() .find(|o| o.obs().id == req.observation_id) .ok_or_else(|| { anyhow::anyhow!("unknown observation: {:?}", req.observation_id) })? .obs() .trial_id; self.tempdirs .create_trial_tempdir(trial_id, req.parent.as_ref()) } Scope::Observation => self .tempdirs .create_obs_tempdir(req.observation_id, req.parent.as_ref()), } } fn handle_ask(&mut self, req: rpc::AskReq) -> anyhow::Result<ParamValue> { let obs = self .runnings .iter_mut() .find(|o| o.obs().id == req.observation_id) .ok_or_else(|| anyhow::anyhow!("unknown observation_id {}", req.observation_id.get()))? .obs_mut(); if let Some(instance) = obs.params.get(&req.param_name) { Ok(instance.value.clone()) } else { let value = self.tuner.ask(obs, &req.param_name, &req.param_type)?; obs.params.insert( req.param_name, ParamInstance::new(req.param_type, value.clone()), ); Ok(value) } } fn handle_tell(&mut self, req: rpc::TellReq) -> anyhow::Result<()> { let obs = self .runnings .iter_mut() .find(|o| o.obs().id == req.observation_id) .ok_or_else(|| anyhow::anyhow!("unknown observation_id {}", req.observation_id.get()))? .obs_mut(); obs.metrics.insert( req.metric_name, MetricInstance::new(req.metric_type, req.metric_value), ); Ok(()) } }
fn handle_action(&mut self, action: Option<Action>) -> anyhow::Result<()> { match action { None => { let obs = Observation::new( self.next_obs_id.fetch_and_increment(), self.next_trial_id.fetch_and_increment(), ); self.start_trial(obs.trial_id)?; self.start_obs(obs)?; } Some(Action::ResumeTrial { trial_id }) => { let obs = Observation::new(self.next_obs_id.fetch_and_increment(), trial_id); self.start_obs(obs)?; } Some(Action::FinishTrial { trial_id }) => { self.finish_trial(trial_id)?; } Some(Action::WaitObservations) => {} Some(Action::QuitOptimization) => { self.terminating = true; for worker in &mut self.runnings { worker.kill()?; } } } Ok(()) }
function_block-full_function
[ { "content": "pub trait Tune {\n\n fn ask(\n\n &mut self,\n\n obs: &Observation,\n\n param_name: &ParamName,\n\n param_type: &ParamType,\n\n ) -> anyhow::Result<ParamValue>;\n\n\n\n fn tell(&mut self, obs: &Observation) -> anyhow::Result<()>;\n\n\n\n fn next_action(&mut s...
Rust
src/component/model/mmd/mod.rs
funmaker/Project39-ar
f61334c1409eb884fab67413374d0ad8e08a6a5e
use std::cell::RefCell; use std::mem::size_of; use std::sync::Arc; use num_traits::Zero; use simba::scalar::SubsetOf; use vulkano::buffer::{BufferUsage, DeviceLocalBuffer, TypedBufferAccess}; use vulkano::command_buffer::{AutoCommandBufferBuilder, PrimaryAutoCommandBuffer}; use vulkano::descriptor_set::{DescriptorSet, PersistentDescriptorSet}; use vulkano::device::DeviceOwned; use vulkano::DeviceSize; use vulkano::pipeline::PipelineBindPoint; pub mod test; mod bone; mod sub_mesh; mod shared; pub use crate::renderer::pipelines::mmd::{MORPH_GROUP_SIZE, Vertex}; use crate::renderer::Renderer; use crate::application::Entity; use crate::utils::AutoCommandBufferBuilderEx; use crate::component::{Component, ComponentBase, ComponentInner, ComponentError}; use crate::debug; use crate::math::{AMat4, Isometry3, IVec4, Vec4}; use super::ModelError; pub use bone::{Bone, BoneConnection}; pub use shared::{MMDModelShared, SubMeshDesc}; pub struct MMDModelState { pub bones: Vec<Bone>, pub morphs: Vec<f32>, bones_mats: Vec<AMat4>, morphs_vec: Vec<IVec4>, } #[derive(ComponentBase)] pub struct MMDModel { #[inner] inner: ComponentInner, pub state: RefCell<MMDModelState>, shared: Arc<MMDModelShared>, bones_ubo: Arc<DeviceLocalBuffer<[AMat4]>>, morphs_ubo: Arc<DeviceLocalBuffer<[IVec4]>>, offsets_ubo: Arc<DeviceLocalBuffer<[IVec4]>>, morphs_set: Arc<dyn DescriptorSet + Send + Sync>, model_set: Arc<dyn DescriptorSet + Send + Sync>, } #[allow(dead_code)] impl MMDModel { pub fn new(shared: Arc<MMDModelShared>, renderer: &mut Renderer) -> Result<MMDModel, ModelError> { let bone_count = shared.default_bones.len(); let bones = shared.default_bones.clone(); let bones_mats = Vec::with_capacity(bone_count); let bones_ubo = DeviceLocalBuffer::array(shared.vertices.device().clone(), (size_of::<AMat4>() * bone_count) as DeviceSize, BufferUsage { transfer_destination: true, storage_buffer: true, ..BufferUsage::none() }, Some(renderer.queue.family()))?; let morphs = vec![0.0; shared.morphs_sizes.len()]; let morphs_vec_count = (shared.morphs_sizes.len() + 1) / 2; let morphs_vec = Vec::with_capacity(morphs_vec_count); let morphs_ubo = DeviceLocalBuffer::array(shared.vertices.device().clone(), morphs_vec_count as DeviceSize, BufferUsage { transfer_destination: true, storage_buffer: true, ..BufferUsage::none() }, Some(renderer.queue.family()))?; let offsets_ubo = DeviceLocalBuffer::array(shared.vertices.device().clone(), shared.vertices.len(), BufferUsage { transfer_destination: true, storage_buffer: true, ..BufferUsage::none() }, Some(renderer.queue.family()))?; let compute_layout = shared.morphs_pipeline .layout() .descriptor_set_layouts() .get(0) .ok_or(ModelError::NoLayout)? .clone(); let morphs_set = { let mut set_builder = PersistentDescriptorSet::start(compute_layout); set_builder.add_buffer(morphs_ubo.clone())? .add_buffer(shared.morphs_offsets.clone())? .add_buffer(offsets_ubo.clone())?; Arc::new(set_builder.build()?) }; let model_set = { let mut set_builder = PersistentDescriptorSet::start(shared.commons_layout(renderer)?); set_builder.add_buffer(renderer.commons.clone())? .add_buffer(bones_ubo.clone())? .add_buffer(offsets_ubo.clone())?; Arc::new(set_builder.build()?) }; Ok(MMDModel { inner: ComponentInner::new(), state: RefCell::new(MMDModelState { bones, morphs, bones_mats, morphs_vec, }), shared, bones_ubo, morphs_ubo, morphs_set, offsets_ubo, model_set, }) } pub fn loaded(&self) -> bool { self.shared.fence.check() } fn draw_debug_bones(&self, model_matrix: Isometry3, bones: &[Bone], bones_mats: &[AMat4]) { for (id, bone) in bones.iter().enumerate() { if bone.display { let pos = model_matrix.transform_point(&bones_mats[id].transform_point(&bone.rest_pos())); debug::draw_point(&pos, 10.0, bone.color.clone()); debug::draw_text(&bone.name, &pos, debug::DebugOffset::bottom_right(8.0, 8.0), 32.0, bone.color.clone()); match &bone.connection { BoneConnection::None => {} BoneConnection::Bone(con) => { let cpos = model_matrix.transform_point(&bones_mats[*con].transform_point(&bones[*con].rest_pos())); debug::draw_line(pos, cpos, 3.0, bone.color.clone()); } BoneConnection::Offset(cpos) => { let cpos = model_matrix.transform_point(&bones_mats[id].transform_point(&(&bone.rest_pos() + cpos))); debug::draw_line(pos, cpos, 3.0, bone.color.clone()); } } } } } } impl Component for MMDModel { fn pre_render(&self, entity: &Entity, _renderer: &Renderer, builder: &mut AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>) -> Result<(), ComponentError> { let state = &mut *self.state.borrow_mut(); for bone in &state.bones { let transform = match bone.parent { None => { let transform: AMat4 = bone.anim_transform.to_superset(); &bone.local_transform * &transform }, Some(id) => &state.bones_mats[id] * &bone.local_transform * &bone.anim_transform, }; state.bones_mats.push(transform); } for (id, mat) in state.bones_mats.iter_mut().enumerate() { *mat = *mat * &state.bones[id].inv_model_transform; } if debug::get_flag_or_default("DebugBonesDraw") { self.draw_debug_bones(entity.state().position, &state.bones, &state.bones_mats); } let bone_buf = self.shared.bones_pool.chunk(state.bones_mats.drain(..))?; builder.copy_buffer(bone_buf, self.bones_ubo.clone())?; state.morphs_vec.clear(); let mut max_size = 0; let mut packing = false; for (id, scale) in state.morphs.iter().enumerate() { if scale.abs() > f32::EPSILON { if packing { if let Some(last) = state.morphs_vec.last_mut() { last.z = id as i32; last.w = scale.to_bits() as i32; } } else { state.morphs_vec.push(vector!(id as i32, scale.to_bits() as i32, 0, 0)); } packing = !packing; if self.shared.morphs_sizes[id] > max_size { max_size = self.shared.morphs_sizes[id]; } } } if state.morphs_vec.is_empty() { builder.fill_buffer(self.offsets_ubo.clone(), 0)?; } else { let groups = (max_size + MORPH_GROUP_SIZE - 1) / MORPH_GROUP_SIZE; let morph_buf = self.shared.morphs_pool.chunk(state.morphs_vec.iter().copied())?; builder.copy_buffer(morph_buf, self.morphs_ubo.clone())? .fill_buffer(self.offsets_ubo.clone(), 0)? .bind_pipeline_compute(self.shared.morphs_pipeline.clone()) .bind_descriptor_sets(PipelineBindPoint::Compute, self.shared.morphs_pipeline.layout().clone(), 0, self.morphs_set.clone()) .push_constants(self.shared.morphs_pipeline.layout().clone(), 0, self.shared.morphs_max_size as u32) .dispatch([groups as u32, state.morphs_vec.len() as u32 * 2, 1])?; } Ok(()) } fn render(&self, entity: &Entity, _renderer: &Renderer, builder: &mut AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>) -> Result<(), ComponentError> { if !self.loaded() { return Ok(()) } let model_matrix = entity.state().position.to_homogeneous(); builder.bind_vertex_buffers(0, self.shared.vertices.clone()) .bind_any_index_buffer(self.shared.indices.clone()); for sub_mesh in self.shared.sub_meshes.iter() { if let Some((pipeline, mesh_set)) = sub_mesh.edge.clone() { let pixel = (110.0_f32 / 360.0 * std::f32::consts::PI).tan() * 2.0 / 1440.0; let scale: f32 = pixel * sub_mesh.edge_scale; builder.bind_pipeline_graphics(pipeline.clone()) .bind_descriptor_sets(PipelineBindPoint::Graphics, pipeline.layout().clone(), 0, (self.model_set.clone(), mesh_set)) .push_constants(pipeline.layout().clone(), 0, (model_matrix.clone(), sub_mesh.edge_color, scale)) .draw_indexed(sub_mesh.range.len() as u32, 1, sub_mesh.range.start, 0, 0)?; } } for sub_mesh in self.shared.sub_meshes.iter() { let (pipeline, mesh_set) = sub_mesh.main.clone(); builder.bind_pipeline_graphics(pipeline.clone()) .bind_descriptor_sets(PipelineBindPoint::Graphics, pipeline.layout().clone(), 0, (self.model_set.clone(), mesh_set)) .push_constants(self.shared.sub_meshes.first().unwrap().main.0.layout().clone(), 0, (model_matrix.clone(), Vec4::zero(), 0.0_f32)) .draw_indexed(sub_mesh.range.len() as u32, 1, sub_mesh.range.start, 0, 0)?; } for sub_mesh in self.shared.sub_meshes.iter() { if let Some((pipeline, mesh_set)) = sub_mesh.transparent.clone() { builder.bind_pipeline_graphics(pipeline.clone()) .bind_descriptor_sets(PipelineBindPoint::Graphics, pipeline.layout().clone(), 0, (self.model_set.clone(), mesh_set)) .push_constants(self.shared.sub_meshes.first().unwrap().main.0.layout().clone(), 0, (model_matrix.clone(), Vec4::zero(), 0.0_f32)) .draw_indexed(sub_mesh.range.len() as u32, 1, sub_mesh.range.start, 0, 0)?; } } Ok(()) } }
use std::cell::RefCell; use std::mem::size_of; use std::sync::Arc; use num_traits::Zero; use simba::scalar::SubsetOf; use vulkano::buffer::{BufferUsage, DeviceLocalBuffer, TypedBufferAccess}; use vulkano::command_buffer::{AutoCommandBufferBuilder, PrimaryAutoCommandBuffer}; use vulkano::descriptor_set::{DescriptorSet, PersistentDescriptorSet}; use vulkano::device::DeviceOwned; use vulkano::DeviceSize; use vulkano::pipeline::PipelineBindPoint; pub mod test; mod bone; mod sub_mesh; mod shared; pub use crate::renderer::pipelines::mmd::{MORPH_GROUP_SIZE, Vertex}; use crate::renderer::Renderer; use crate::application::Entity; use crate::utils::AutoCommandBufferBuilderEx; use crate::component::{Component, ComponentBase, ComponentInner, ComponentError}; use crate::debug; use crate::math::{AMat4, Isometry3, IVec4, Vec4}; use super::ModelError; pub use bone::{Bone, BoneConnection}; pub use shared::{MMDModelShared, SubMeshDesc}; pub struct MMDModelState { pub bones: Vec<Bone>, pub morphs: Vec<f32>, bones_mats: Vec<AMat4>, morphs_vec: Vec<IVec4>, } #[derive(ComponentBase)] pub struct MMDModel { #[inner] inner: ComponentInner, pub state: RefCell<MMDModelState>, shared: Arc<MMDModelShared>, bones_ubo: Arc<DeviceLocalBuffer<[AMat4]>>, morphs_ubo: Arc<DeviceLocalBuffer<[IVec4]>>, offsets_ubo: Arc<DeviceLocalBuffer<[IVec4]>>, morphs_set: Arc<dyn DescriptorSet + Send + Sync>, model_set: Arc<dyn DescriptorSet + Send + Sync>, } #[allow(dead_code)] impl MMDModel { pub fn new(shared: Arc<MMDModelShared>, renderer: &mut Renderer) -> Result<MMDModel, ModelError> { let bone_count = shared.default_bones.len(); let bones = shared.default_bones.clone(); let bones_mats = Vec::with_capacity(bone_count); let bones_ubo = DeviceLocalBuffer::array(shared.vertices.device().clone(), (size_of::<AMat4>() * bone_count) as DeviceSize, BufferUsage { transfer_destination: true, storage_buffer: true, ..BufferUsage::none() }, Some(renderer.queue.family()))?; let morphs = vec![0.0; shared.morphs_sizes.len()]; let morphs_vec_count = (shared.morphs_sizes.len() + 1) / 2; let morphs_vec = Vec::with_capacity(morphs_vec_count); let morphs_ubo = DeviceLocalBuffer::array(shared.vertices.device().clone(), morphs_vec_count as DeviceSize, BufferUsage { transfer_destination: true, storage_buffer: true, ..BufferUsage::none() }, Some(renderer.queue.family()))?; let offsets_ubo = DeviceLocalBuffer::array(shared.vertices.device().clone(), shared.vertices.len(), BufferUsage { transfer_destination: true, storage_buffer: true, ..BufferUsage::none() }, Some(renderer.queue.family()))?; let compute_layout = shared.morphs_pipeline .layout() .descriptor_set_layouts() .get(0) .ok_or(ModelError::NoLayout)? .clone(); let morphs_set = { let mut set_builder = PersistentDescriptorSet::start(compute_layout); set_builder.add_buffer(morphs_ubo.clone())? .add_buffer(shared.morphs_offsets.clone())? .add_buffer(offsets_ubo.clone())?; Arc::new(set_builder.build()?) }; let model_set = { let mut set_builder = PersistentDescriptorSet::start(shared.commons_layout(renderer)?); set_builder.add_buffer(renderer.commons.clone())? .add_buffer(bones_ubo.clone())? .add_buffer(offsets_ubo.clone())?; Arc::new(set_builder.build()?) }; Ok(MMDModel { inner: ComponentInner::new(), state: RefCell::new(MMDModelState { bones, morphs, bones_mats, morphs_vec, }), shared, bones_ubo, morphs_ubo, morphs_set, offsets_ubo, model_set, }) } pub fn loaded(&self) -> bool { self.shared.fence.check() } fn draw_debug_bones(&self, model_matrix: Isometry3, bones: &[Bone], bones_mats: &[AMat4]) { for (id, bone) in bones.iter().enumerate() { if bone.display { let pos = model_matrix.transform_point(&bones_mats[id].transform_point(&bone.rest_pos())); debug::draw_point(&pos, 10.0, bone.color.clone()); debug::draw_text(&bone.name, &pos, debug::DebugOffset::bottom_right(8.0, 8.0), 32.0, bone.color.clone()); match &bone.connection { BoneConnection::None => {} BoneConnection::Bone(con) => { let cpos = model_matrix.transform_point(&bones_mats[*con].transform_point(&bones[*con].rest_pos())); debug::draw_line(pos, cpos, 3.0, bone.color.clone()); } BoneConnection::Offset(cpos) => { let cpos = model_matrix.transform_point(&bones_mats[id].transform_point(&(&bone.rest_pos() + cpos))); debug::draw_line(pos, cpos, 3.0, bone.color.clone()); } } } } } } impl Component for MMDModel { fn pre_render(&self, entity: &Entity, _renderer: &Renderer, builder: &mut AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>) -> Result<(), ComponentError> { let state = &mut *self.state.borrow_mut(); for bone in &state.bones { let transform = match bone.parent { None => { let transform: AMat4 = bone.anim_transform.to_superset(); &bone.local_transform * &transform }, Some(id) => &state.bones_mats[id] * &bone.local_transform * &bone.anim_transform, }; state.bones_mats.push(transform); } for (id, mat) in state.bones_mats.iter_mut().enumerate() { *mat = *mat * &state.bones[id].inv_model_transform; } if debug::get_flag_or_default("DebugBonesDraw") { self.draw_debug_bones(entity.state().position, &state.bones, &state.bones_mats); } let bone_buf = self.shared.bones_pool.chunk(state.bones_mats.drain(..))?; builder.copy_buffer(bone_buf, self.bones_ubo.clone())?; state.morphs_vec.clear(); let mut max_size = 0; let mut packing = false; for (id, scale) in state.morphs.iter().enumerate() { if scale.abs() > f32::EPSILON { if packing { if let Some(last) = state.morphs_vec.last_mut() { last.z = id as i32; last.w = scale.to_bits() as i32; } } else { state.morphs_vec.push(vector!(id as i32, scale.to_bits() as i32, 0, 0)); } packing = !packing; if self.shared.morphs_sizes[id] > max_size { max_size = self.shared.morphs_sizes[id]; } } } if state.morphs_vec.is_empty() { builder.fill_buffer(self.offsets_ubo.clone(), 0)?; } else { let groups = (max_size + MORPH_GROUP_SIZE - 1) / MORPH_GROUP_SIZE; let morph_buf = self.shared.morphs_pool.chunk(state.morphs_vec.iter().copied())?; builder.copy_buffer(morph_buf, self.morphs_ubo.clone())? .fill_buffer(self.offsets_ubo.clone(), 0)? .bind_pipeline_compute(self.shared.morphs_pipeline.clone()) .bind_descriptor_sets(PipelineBindPoint::Compute, self.shared.morphs_pipeline.layout().clone(), 0, self.morphs_set.clone()) .push_constants(self.shared.morphs_pipeline.layout().clone(), 0, self.shared.morphs_max_size as u32) .dispatch([groups as u32, state.morphs_vec.len() as u32 * 2, 1])?; } Ok(()) } fn render(&self, entity: &Entity, _renderer: &Renderer, builder: &mut AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>) -> Result<(), ComponentError> { if !self.loaded() { return Ok(()) } let model_matrix = entity.state().position.to_homogeneous(); builder.bind_vertex_buffers(0, self.shared.vertices.clone()) .bind_any_index_buffer(self.shared.indices.clone()); for sub_mesh in self.shared.sub_meshes.iter() { if let Some((pipeline, mesh_set)) = sub_mesh.edge.clone() { let pixel = (110.0_f32 / 360.0 * std::f32::consts::PI).tan() * 2.0 / 1440.0; let scale: f32 = pixel * sub_mesh.edge_scale; builder.bind_pipeline_graphics(pipeline.clone()) .bind_descriptor_sets(PipelineBindPoint::Graphics, pipeline.layout().clone(), 0, (self.model_set.clone(), mesh_set)) .push_constants(pipeline.layout().clone(), 0, (model_matrix.clone(), sub_mesh.edge_color, scale)) .draw_indexed(sub_mesh.range.len() as u32, 1, sub_mesh.range.start, 0, 0)?; } } for sub_mesh in self.shared.sub_meshes.iter() { let (pipeline, mesh_set) = sub_mesh.main.clone(); builder.bind_pipeline_graphics(pipeline.clone()) .bind_descriptor_sets(PipelineBindPoint::
(model_matrix.clone(), Vec4::zero(), 0.0_f32)) .draw_indexed(sub_mesh.range.len() as u32, 1, sub_mesh.range.start, 0, 0)?; } for sub_mesh in self.shared.sub_meshes.iter() { if let Some((pipeline, mesh_set)) = sub_mesh.transparent.clone() { builder.bind_pipeline_graphics(pipeline.clone()) .bind_descriptor_sets(PipelineBindPoint::Graphics, pipeline.layout().clone(), 0, (self.model_set.clone(), mesh_set)) .push_constants(self.shared.sub_meshes.first().unwrap().main.0.layout().clone(), 0, (model_matrix.clone(), Vec4::zero(), 0.0_f32)) .draw_indexed(sub_mesh.range.len() as u32, 1, sub_mesh.range.start, 0, 0)?; } } Ok(()) } }
Graphics, pipeline.layout().clone(), 0, (self.model_set.clone(), mesh_set)) .push_constants(self.shared.sub_meshes.first().unwrap().main.0.layout().clone(), 0,
random
[ { "content": "#[allow(dead_code)]\n\npub fn test_model(renderer: &mut Renderer) -> MMDModel {\n\n\tlet mut vertices = vec![];\n\n\tlet mut indices = vec![];\n\n\tlet bones_num = 1;\n\n\tlet height = 2.0;\n\n\t\n\n\tlet mut make_wall = |from: Vec3, to: Vec3, normal: Vec3, divs: usize, bones: usize| {\n\n\t\tlet ...
Rust
codegen/src/lib.rs
Atul9/canrun_rs
4e9c4dd3ddfdcf0f5666c2122614708e14f2eaa1
extern crate proc_macro; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::{parse_macro_input, Result, Token}; struct DomainDef { canrun_internal: bool, domain_visibility: syn::Visibility, domain_name: syn::Ident, domain_types: Vec<syn::Type>, } impl Parse for DomainDef { fn parse(input: ParseStream) -> Result<Self> { let domain_visibility = input.parse()?; let domain_name: syn::Ident = input.parse()?; let content; syn::braced!(content in input); let raw_types: Punctuated<syn::Type, Token![,]> = content.parse_terminated(syn::Type::parse)?; let domain_types: Vec<_> = raw_types.into_iter().collect(); Ok(DomainDef { canrun_internal: false, domain_visibility, domain_name, domain_types, }) } } impl quote::ToTokens for DomainDef { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let DomainDef { canrun_internal, domain_visibility, domain_name, domain_types, } = self; let canrun_mod = if *canrun_internal { format_ident!("crate") } else { format_ident!("canrun") }; let (fields, variants): (Vec<_>, Vec<_>) = (0..domain_types.len()) .map(|n| (format_ident!("t{}", n), format_ident!("T{}", n))) .unzip(); let value_name = format_ident!("{}Value", domain_name); let result = quote! { #[doc="A custom Domain generated by the domain! macro."] #[doc="TODO: Figure out how to interpolate something useful here"] #[derive(std::fmt::Debug)] #domain_visibility struct #domain_name { #(#fields: #canrun_mod::domains::DomainValues<#domain_types>),* } impl<'a> #canrun_mod::domains::Domain<'a> for #domain_name { type Value = #value_name; fn new() -> Self { #domain_name { #(#fields: #canrun_mod::domains::DomainValues::new(),)* } } fn unify_domain_values( state: #canrun_mod::state::State<'a, Self>, a: Self::Value, b: Self::Value, ) -> Option<#canrun_mod::state::State<Self>> { use #canrun_mod::value::{Val, IntoVal}; match (a, b) { #( (#value_name::#variants(a), #value_name::#variants(b)) => { state.unify::<#domain_types>(&a.into_val(), &b.into_val()) } ,)* _ => None, } } } #( impl<'a> #canrun_mod::domains::DomainType<'a, #domain_types> for #domain_name { fn values_as_ref( &self, ) -> &#canrun_mod::domains::DomainValues<#domain_types> { &self.#fields } fn values_as_mut( &mut self, ) -> &mut #canrun_mod::domains::DomainValues<#domain_types> { &mut self.#fields } fn into_domain_val(val: #canrun_mod::value::Val<#domain_types>) -> #value_name { #value_name::#variants(val) } } )* impl<'a> Clone for #domain_name { fn clone(&self) -> Self { #domain_name { #(#fields: self.#fields.clone()),* } } } #[doc(hidden)] #[derive(std::fmt::Debug)] #domain_visibility enum #value_name { #(#variants(#canrun_mod::value::Val<#domain_types>)),* } impl Clone for #value_name { fn clone(&self) -> Self { match self { #(#value_name::#variants(val) => #value_name::#variants(val.clone())),* } } } }; result.to_tokens(tokens); } } #[proc_macro] pub fn domain(item: TokenStream) -> TokenStream { let def = parse_macro_input!(item as DomainDef); quote!(#def).into() } #[proc_macro] #[doc(hidden)] pub fn canrun_internal_domain(item: TokenStream) -> TokenStream { let mut def = parse_macro_input!(item as DomainDef); def.canrun_internal = true; quote!(#def).into() }
extern crate proc_macro; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::{parse_macro_input, Result, Token}; struct DomainDef { canrun_internal: bool, domain_visibility: syn::Visibility, domain_name: syn::Ident, domain_types: Vec<syn::Type>, } impl Parse for DomainDef { fn parse(input: ParseStream) -> Result<Self> { let domain_visibility = input.parse()?; let domain_name: syn::Ident = input.parse()?; let content; syn::braced!(content in input); let raw_types: Punctuated<syn::Type, Token![,]> = content.parse_terminated(syn::Type::parse)?; let domain_types: Vec<_> = raw_types.into_iter().collect();
} } impl quote::ToTokens for DomainDef { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let DomainDef { canrun_internal, domain_visibility, domain_name, domain_types, } = self; let canrun_mod = if *canrun_internal { format_ident!("crate") } else { format_ident!("canrun") }; let (fields, variants): (Vec<_>, Vec<_>) = (0..domain_types.len()) .map(|n| (format_ident!("t{}", n), format_ident!("T{}", n))) .unzip(); let value_name = format_ident!("{}Value", domain_name); let result = quote! { #[doc="A custom Domain generated by the domain! macro."] #[doc="TODO: Figure out how to interpolate something useful here"] #[derive(std::fmt::Debug)] #domain_visibility struct #domain_name { #(#fields: #canrun_mod::domains::DomainValues<#domain_types>),* } impl<'a> #canrun_mod::domains::Domain<'a> for #domain_name { type Value = #value_name; fn new() -> Self { #domain_name { #(#fields: #canrun_mod::domains::DomainValues::new(),)* } } fn unify_domain_values( state: #canrun_mod::state::State<'a, Self>, a: Self::Value, b: Self::Value, ) -> Option<#canrun_mod::state::State<Self>> { use #canrun_mod::value::{Val, IntoVal}; match (a, b) { #( (#value_name::#variants(a), #value_name::#variants(b)) => { state.unify::<#domain_types>(&a.into_val(), &b.into_val()) } ,)* _ => None, } } } #( impl<'a> #canrun_mod::domains::DomainType<'a, #domain_types> for #domain_name { fn values_as_ref( &self, ) -> &#canrun_mod::domains::DomainValues<#domain_types> { &self.#fields } fn values_as_mut( &mut self, ) -> &mut #canrun_mod::domains::DomainValues<#domain_types> { &mut self.#fields } fn into_domain_val(val: #canrun_mod::value::Val<#domain_types>) -> #value_name { #value_name::#variants(val) } } )* impl<'a> Clone for #domain_name { fn clone(&self) -> Self { #domain_name { #(#fields: self.#fields.clone()),* } } } #[doc(hidden)] #[derive(std::fmt::Debug)] #domain_visibility enum #value_name { #(#variants(#canrun_mod::value::Val<#domain_types>)),* } impl Clone for #value_name { fn clone(&self) -> Self { match self { #(#value_name::#variants(val) => #value_name::#variants(val.clone())),* } } } }; result.to_tokens(tokens); } } #[proc_macro] pub fn domain(item: TokenStream) -> TokenStream { let def = parse_macro_input!(item as DomainDef); quote!(#def).into() } #[proc_macro] #[doc(hidden)] pub fn canrun_internal_domain(item: TokenStream) -> TokenStream { let mut def = parse_macro_input!(item as DomainDef); def.canrun_internal = true; quote!(#def).into() }
Ok(DomainDef { canrun_internal: false, domain_visibility, domain_name, domain_types, })
call_expression
[ { "content": "/// Resolve one [`Val`] or return an [`Err(VarWatch)`](VarWatch) in a\n\n/// [`Constraint`].\n\npub fn resolve_1<'a, A, D>(val: &Val<A>, state: &State<'a, D>) -> Result<Rc<A>, VarWatch>\n\nwhere\n\n A: Debug,\n\n D: DomainType<'a, A>,\n\n{\n\n let a = state.resolve_val(val);\n\n match ...
Rust
src/str_utils.rs
anekos/eitaro
21b0c4355c7c994b9175e205ee9e19fb026633ab
use heck::SnakeCase; use kana::wide2ascii; use regex::Regex; #[derive(Clone, Copy)] pub enum WordType { English, Katakana, } pub fn simple_words_pattern() -> Regex { Regex::new(r"[a-zA-Z]+").unwrap() } pub fn fix_word(s: &str) -> Option<String> { let s = wide2ascii(s); let s = s.to_lowercase().replace('ー', ""); if s.is_empty() { None } else { Some(s) } } pub fn scan_words(word_type: WordType, s: &str) -> Vec<String> { let mut result = vec![]; let mut in_word = false; let mut index = 0; let mut left = 0; let mut right = 0; let is_word_char = get_is_word_char(word_type); for c in s.chars() { let space = c == ' '; if in_word ^ (is_word_char(c) || (in_word && space)) { in_word = !in_word; if in_word { left = index; } else if left < right { extract_patterns(&s[left..right], &mut result); } } index += c.len_utf8(); if in_word && !space { right = index; } } if in_word && left < right { extract_patterns(&s[left..right], &mut result); } result } pub fn shorten(s: &str) -> Vec<&str> { let mut result = vec![]; let mut index = 0; let mut left = 0; let mut in_word = false; let mut first = true; for c in s.chars() { if in_word ^ (c != ' ') { in_word = !in_word; if in_word { if first { left = index; first = false; } } else if left < index { result.push(&s[left..index]); } } index += c.len_utf8(); } if in_word && left < index { result.push(&s[left..index]); } result.reverse(); result } pub fn uncase(s: &str) -> String { s.to_snake_case().replace('_', " ") } fn extract_patterns(s: &str, result: &mut Vec<String>) { if let Some(l) = s.find('(') { if let Some(r) = s.find(')') { extract_patterns(&format!("{}{}", &s[0..l], &s[r+1..]), result); extract_patterns(&format!("{}{}{}", &s[0..l], &s[l+1..r], &s[r+1..]), result); } else { extract_patterns(&s[0..l].to_owned(), result); } } else { result.push(s.to_owned()); } } fn get_is_word_char(word_type: WordType) -> fn(char) -> bool { match word_type { WordType::English => is_word_char_english, WordType::Katakana => is_word_char_katakana, } } fn is_word_char_english(c: char) -> bool { c.is_ascii() && c.is_alphanumeric() || c == '-' || c == '\'' || c == '(' || c == ')' } fn is_word_char_katakana(c: char) -> bool { !c.is_ascii() && c.is_alphabetic() } #[cfg(test)]#[test] fn test_scan_words() { use self::WordType::*; assert_eq!(scan_words(English, " foo キャット bar 猫"), vec!["foo", "bar"]); assert_eq!(scan_words(English, " foo キャット bar "), vec!["foo", "bar"]); assert_eq!(scan_words(English, " foo、キャット・bar=猫 "), vec!["foo", "bar"]); assert_eq!(scan_words(English, " foo-bar "), vec!["foo-bar"]); assert_eq!(scan_words(English, "【変化】動 drives | driving | drove | driven"), vec!["drives", "driving", "drove", "driven"]); assert_eq!(scan_words(English, "【変化】動 foo bar | food bar | foolish bar"), vec!["foo bar", "food bar", "foolish bar"]); assert_eq!(scan_words(English, "【変化】 複 affairs、【文節】..."), vec!["affairs"]); assert_eq!(scan_words(Katakana, "アカムパニ、アカンパニ、アコンパニ、"), vec!["アカムパニ", "アカンパニ", "アコンパニ"]); assert_eq!(scan_words(Katakana, " foo-bar "), Vec::<&str>::new()); assert_eq!(scan_words(English, " f(o)o キャット bar 猫"), vec!["fo", "foo", "bar"]); } #[cfg(test)]#[test] fn test_patterns() { fn ps(s: &str) -> Vec<String> { let mut result = vec![]; extract_patterns(s, &mut result); result } assert_eq!(ps("ana(a)l nathrakh"), vec!["anal nathrakh".to_owned(), "anaal nathrakh".to_owned()]); assert_eq!( ps("ab(c)de(f)g"), vec![ "abdeg".to_owned(), "abdefg".to_owned(), "abcdeg".to_owned(), "abcdefg".to_owned()]); } #[cfg(test)]#[test] fn test_shortens() { assert_eq!( shorten("the cat of hell"), vec![ "the cat of hell".to_owned(), "the cat of".to_owned(), "the cat".to_owned(), "the".to_owned() ]); assert_eq!( shorten(" the cat of hell"), vec![ "the cat of hell".to_owned(), "the cat of".to_owned(), "the cat".to_owned(), "the".to_owned() ]); assert_eq!( shorten(" the cat of hell "), vec![ "the cat of hell".to_owned(), "the cat of".to_owned(), "the cat".to_owned(), "the".to_owned() ]); assert_eq!( shorten(" the cat of hell "), vec![ "the cat of hell".to_owned(), "the cat of".to_owned(), "the cat".to_owned(), "the".to_owned() ]); }
use heck::SnakeCase; use kana::wide2ascii; use regex::Regex; #[derive(Clone, Copy)] pub enum WordType { English, Katakana, } pub fn simple_words_pattern() -> Regex { Regex::new(r"[a-zA-Z]+").unwrap() } pub fn fix_word(s: &str) -> Option<String> { let s = wide2ascii(s); let s = s.to_lowercase().replace('ー', ""); if s.is_empty() { None } else { Some(s) } } pub fn scan_words(word_type: WordType, s: &str) -> Vec<String> { let mut result = vec![]; let mut in_word = false; let mut index = 0; let mut left = 0; let mut right = 0; let is_word_char = get_is_word_char(word_type); for c in s.chars() { let space = c == ' '; if in_word ^ (is_word_char(c) || (in_word && space)) { in_word = !in_word; if in_word { left = index; } else if left < right { extract_patterns(&s[left..right], &mut result); } } index += c.len_utf8(); if in_word && !space { right = index; } } if in_word && left < right { extract_patterns(&s[left..right], &mut result); } result } pub fn shorten(s: &str) -> Vec<&str> { let mut result = vec![]; let mut index = 0; let mut left = 0; let mut in_word = false; let mut first = true; for c in s.chars() { if in_word ^ (c != ' ') { in_word = !in_word; if in_word { if first { left = index; first = false; } } else if left < index { result.push(&s[left..index]); } } index += c.len_utf8(); } if in_word && left < index { result.push(&s[left..index]); } result.reverse(); result } pub fn uncase(s: &str) -> String { s.to_snake_case().replace('_', " ") } fn extract_patterns(s: &str, result: &mut Vec<String>) { if let Some(l) = s.find('(') { if let Some(r) = s.find(')') { extract_patterns(&format!("{}{}", &s[0..l], &s[r+1..]), result); extract_patterns(&format!("{}{}{}", &s[0..l], &s[l+1..r], &s[r+1..]), result); } else { extract_patterns(&s[0..l].to_owned(), result); } } else { result.push(s.to_owned()); } } fn get_is_word_char(word_type: WordType) -> fn(char) -> bool { match word_type { WordType::English => is_word_char_english, WordType::Katakana => is_word_char_katakana, } } fn is_word_char_english(c: char) -> bool { c.is_ascii() && c.is_alphanumeric() || c == '-' || c == '\'' || c == '(' || c == ')' } fn is_word_char_katakana(c: char) -> bool { !c.is_ascii() && c.is_alphabetic() } #[cfg(test)]#[test] fn test_scan_words() { use self::WordType::*; assert_eq!(scan_words(English, " foo キャット bar 猫"), vec!["foo", "bar"]); assert_eq!(scan_words(English, "
sert_eq!(scan_words(Katakana, " foo-bar "), Vec::<&str>::new()); assert_eq!(scan_words(English, " f(o)o キャット bar 猫"), vec!["fo", "foo", "bar"]); } #[cfg(test)]#[test] fn test_patterns() { fn ps(s: &str) -> Vec<String> { let mut result = vec![]; extract_patterns(s, &mut result); result } assert_eq!(ps("ana(a)l nathrakh"), vec!["anal nathrakh".to_owned(), "anaal nathrakh".to_owned()]); assert_eq!( ps("ab(c)de(f)g"), vec![ "abdeg".to_owned(), "abdefg".to_owned(), "abcdeg".to_owned(), "abcdefg".to_owned()]); } #[cfg(test)]#[test] fn test_shortens() { assert_eq!( shorten("the cat of hell"), vec![ "the cat of hell".to_owned(), "the cat of".to_owned(), "the cat".to_owned(), "the".to_owned() ]); assert_eq!( shorten(" the cat of hell"), vec![ "the cat of hell".to_owned(), "the cat of".to_owned(), "the cat".to_owned(), "the".to_owned() ]); assert_eq!( shorten(" the cat of hell "), vec![ "the cat of hell".to_owned(), "the cat of".to_owned(), "the cat".to_owned(), "the".to_owned() ]); assert_eq!( shorten(" the cat of hell "), vec![ "the cat of hell".to_owned(), "the cat of".to_owned(), "the cat".to_owned(), "the".to_owned() ]); }
foo キャット bar "), vec!["foo", "bar"]); assert_eq!(scan_words(English, " foo、キャット・bar=猫 "), vec!["foo", "bar"]); assert_eq!(scan_words(English, " foo-bar "), vec!["foo-bar"]); assert_eq!(scan_words(English, "【変化】動 drives | driving | drove | driven"), vec!["drives", "driving", "drove", "driven"]); assert_eq!(scan_words(English, "【変化】動 foo bar | food bar | foolish bar"), vec!["foo bar", "food bar", "foolish bar"]); assert_eq!(scan_words(English, "【変化】 複 affairs、【文節】..."), vec!["affairs"]); assert_eq!(scan_words(Katakana, "アカムパニ、アカンパニ、アコンパニ、"), vec!["アカムパニ", "アカンパニ", "アコンパニ"]); as
random
[ { "content": "pub fn v2s(s: Vec<char>) -> String {\n\n let s: String = s.into_iter().collect();\n\n s.trim().to_owned()\n\n}\n", "file_path": "src/parser/utils.rs", "rank": 4, "score": 249985.30886171234 }, { "content": "fn extract_text(dictionary: &mut Dictionary, s: &str) -> AppResul...
Rust
src/day3.rs
arturh85/adventofcode-rust-2021
dddcdb3901fec5fce6d317c0b12ff79d44e4f3bf
use bitlab::*; #[aoc_generator(day3)] fn parse_input(input: &str) -> Vec<u32> { input .lines() .map(|line| u32::from_str_radix(line, 2).unwrap()) .collect() } #[aoc(day3, part1)] fn part1(input: &[u32]) -> u64 { gamma(input) as u64 * epsilon(input) as u64 } #[aoc(day3, part2)] fn part2(input: &[u32]) -> u64 { oxygen(input) as u64 * co2(input) as u64 } fn oxygen(input: &[u32]) -> u32 { let max = *input.iter().max().unwrap(); let start = significant_bitcount(max).unwrap(); let mut remaining = Vec::from(input); for i in start..32 { let (count_zeros, count_ones) = count_ones_zeros_at(&remaining, i); if count_ones >= count_zeros { remaining = remaining .into_iter() .filter(|v| v.get_bit(i).unwrap()) .collect(); } else { remaining = remaining .into_iter() .filter(|v| !v.get_bit(i).unwrap()) .collect(); } if remaining.len() == 1 { return remaining[0]; } } 0 } fn co2(input: &[u32]) -> u32 { let max = *input.iter().max().unwrap(); let start = significant_bitcount(max).unwrap(); let mut remaining = Vec::from(input); for i in start..32 { let (count_zeros, count_ones) = count_ones_zeros_at(&remaining, i); if count_zeros <= count_ones { remaining = remaining .into_iter() .filter(|v| !v.get_bit(i).unwrap()) .collect(); } else { remaining = remaining .into_iter() .filter(|v| v.get_bit(i).unwrap()) .collect(); } if remaining.len() == 1 { return remaining[0]; } } 0 } fn count_ones_zeros_at(input: &[u32], pos: u32) -> (u32, u32) { let mut count_zeros = 0; let mut count_ones = 0; for v in input { if v.get_bit(pos).unwrap() { count_ones += 1; } else { count_zeros += 1; } } (count_zeros, count_ones) } fn gamma(input: &[u32]) -> u32 { let mut ret = 0; for i in 0..32 { let (count_zeros, count_ones) = count_ones_zeros_at(input, i); if count_ones >= count_zeros { ret = ret.set_bit(i).unwrap(); } } ret } fn significant_bitcount(value: u32) -> Option<u32> { for i in 0..32 { if value.get_bit(i).unwrap() { return Some(i); } } None } fn epsilon(input: &[u32]) -> u32 { let gamma = gamma(input); let max = *input.iter().max().unwrap(); let start = significant_bitcount(max).unwrap(); let mut ret = 0; for i in start..32 { if !gamma.get_bit(i).unwrap() { ret = ret.set_bit(i).unwrap() } } ret } #[cfg(test)] mod tests { use super::*; const EXAMPLE: &str = "00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010"; #[test] fn part1_examples() { assert_eq!(gamma(&parse_input(EXAMPLE)), 0b1_0110); assert_eq!(gamma(&parse_input(EXAMPLE)), 22); assert_eq!(epsilon(&parse_input(EXAMPLE)), 0b1001); assert_eq!(epsilon(&parse_input(EXAMPLE)), 9); } #[test] fn part2_examples() { assert_eq!(oxygen(&parse_input(EXAMPLE)), 0b1_0111); assert_eq!(oxygen(&parse_input(EXAMPLE)), 23); assert_eq!(co2(&parse_input(EXAMPLE)), 0b0_1010); assert_eq!(co2(&parse_input(EXAMPLE)), 10); } }
use bitlab::*; #[aoc_generator(day3)] fn parse_input(input: &str) -> Vec<u32> { input .lines() .map(|line| u32::from_str_radix(line, 2).unwrap()) .collect() } #[aoc(day3, part1)] fn part1(input: &[u32]) -> u64 { gamma(input) as u64 * epsilon(input) as u64 } #[aoc(day3, part2)] fn part2(input: &[u32]) -> u64 { oxygen(input) as u64 * co2(input) as u64 } fn oxygen(input: &[u32]) -> u32 { let max = *input.iter().max().unwrap(); let start = significant_bitcount(max).unwrap(); let mut remaining = Vec::from(input); for i in start..32 { let (count_zeros, count_ones) = count_ones_zeros_at(&remaining, i); if count_ones >= count_zeros { remaining = remaining .into_iter() .filter(|v| v.get_bit(i).unwrap()) .collect(); } else { remaining = remaining .into_iter() .filter(|v| !v.get_bit(i).unwrap()) .collect(); } if remaining.len() == 1 { return remaining[0]; } } 0 } fn co2(input: &[u32]) -> u32 { let max = *input.iter().max().unwrap(); let start = significant_bitcount(max).unwrap(); let mut remaining = Vec::from(input); for i in start..32 { let (count_zeros, count_ones) = count_ones_zeros_at(&remaining, i); if count_zeros <= count_ones { remaining = remaining .into_iter() .filter(|v| !v.get_bit(i).unwrap()) .collect(); } else { remaining = remaining .into_iter() .filter(|v| v.get_bit(i).unwrap()) .collect(); } if remaining.len() == 1 { return remaining[0]; } } 0 } fn count_ones_zeros_at(input: &[u32], pos: u32) -> (u32, u32) { let mut count_zeros = 0; let mut count_ones = 0; for v in input { if v.get_bit(pos).unwrap() { count_ones += 1; } else { count_zeros += 1; } } (count_zeros, count_ones) } fn gamma(input: &[u32]) -> u32 { let mut ret = 0; for i in 0..32 { let (count_zeros, count_ones) = count_ones_zeros_at(input, i); if count_ones >= count_zeros { ret = ret.set_bit(i).unwrap(); } } ret } fn significant_bitcount(value: u32) -> Option<u32> { for i in 0..32 { if value.get_bit(i).unwrap() { return Some(i); } } None }
#[cfg(test)] mod tests { use super::*; const EXAMPLE: &str = "00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010"; #[test] fn part1_examples() { assert_eq!(gamma(&parse_input(EXAMPLE)), 0b1_0110); assert_eq!(gamma(&parse_input(EXAMPLE)), 22); assert_eq!(epsilon(&parse_input(EXAMPLE)), 0b1001); assert_eq!(epsilon(&parse_input(EXAMPLE)), 9); } #[test] fn part2_examples() { assert_eq!(oxygen(&parse_input(EXAMPLE)), 0b1_0111); assert_eq!(oxygen(&parse_input(EXAMPLE)), 23); assert_eq!(co2(&parse_input(EXAMPLE)), 0b0_1010); assert_eq!(co2(&parse_input(EXAMPLE)), 10); } }
fn epsilon(input: &[u32]) -> u32 { let gamma = gamma(input); let max = *input.iter().max().unwrap(); let start = significant_bitcount(max).unwrap(); let mut ret = 0; for i in start..32 { if !gamma.get_bit(i).unwrap() { ret = ret.set_bit(i).unwrap() } } ret }
function_block-full_function
[ { "content": "#[aoc(day7, part2)]\n\nfn part2(input: &[u32]) -> u32 {\n\n (0..input.len())\n\n .map(|target| fuel2(input, target as u32))\n\n .min()\n\n .unwrap()\n\n}\n\n\n", "file_path": "src/day7.rs", "rank": 2, "score": 218867.65510229085 }, { "content": "#[aoc(da...
Rust
src/rng/splitmix64simd.rs
tommyettinger/heh
a2a52c8ebd692d3e74222579f4f8ca04f4256b5d
use rand_core::{Error, RngCore, SeedableRng}; use rand_core::block::{BlockRngCore, BlockRng}; use faster::Transmute; use faster::vecs::{u64x4}; use byteorder::{LittleEndian, ByteOrder}; use super::Linnorm64; #[allow(missing_copy_implementations)] #[derive(Debug, Clone)] pub struct SplitMix64x4Core { x: u64x4, } impl SplitMix64x4Core { #[inline] pub fn next_u64x4(&mut self) -> u64x4 { const INC : u64x4 = u64x4::new(0xabdcdadb7e86b08bu64, 0x575bdce3dd69b537u64, 0x765ff07dee64eac9u64, 0x9e3779b97f4a7c15u64); const A_MUL : u64x4 = u64x4::new(0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64); const B_MUL : u64x4 = u64x4::new(0x94d049bb133111ebu64, 0x94d049bb133111ebu64, 0x94d049bb133111ebu64, 0x94d049bb133111ebu64); self.x += INC; let mut z = self.x; z = (z ^ (z >> 30)) * A_MUL; z = (z ^ (z >> 27)) * B_MUL; z ^ (z >> 31) } #[inline] pub fn from_seed_u64(seed: u64) -> SplitMix64x4Core { let mut rng = Linnorm64::from_seed_u64(seed); SplitMix64x4Core::from_seed(SplitMix64x4Seed::from_rng(&mut rng)) } } pub struct SplitMix64x4Seed([u8; 32]); impl SplitMix64x4Seed { #[inline] pub fn new(seed: [u8; 32]) -> SplitMix64x4Seed { SplitMix64x4Seed(seed) } pub fn from_rng<R: RngCore>(rng: &mut R) -> SplitMix64x4Seed { let mut seed = [0; 32]; rng.fill_bytes(&mut seed); SplitMix64x4Seed(seed) } } impl ::std::convert::AsMut<[u8]> for SplitMix64x4Seed { fn as_mut(&mut self) -> &mut [u8] { &mut self.0 } } impl ::std::default::Default for SplitMix64x4Seed { fn default() -> SplitMix64x4Seed { SplitMix64x4Seed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) } } impl SeedableRng for SplitMix64x4Core { type Seed = SplitMix64x4Seed; #[inline] fn from_seed(seed: SplitMix64x4Seed) -> SplitMix64x4Core { let seed = seed.0; SplitMix64x4Core { x: u64x4::new( LittleEndian::read_u64(&seed[0..8]), LittleEndian::read_u64(&seed[8..16]), LittleEndian::read_u64(&seed[16..24]), LittleEndian::read_u64(&seed[24..32]), ), } } } impl BlockRngCore for SplitMix64x4Core { type Item = u32; type Results = [u32; 8]; #[inline] fn generate(&mut self, results: &mut Self::Results) { let r = self.next_u64x4().be_u32s(); r.store(results, 0); } } #[derive(Clone, Debug)] pub struct SplitMix64x4(BlockRng<SplitMix64x4Core>); impl SplitMix64x4 { #[inline] pub fn from_seed_u64(seed: u64) -> Self { SplitMix64x4(BlockRng::<SplitMix64x4Core>::new(SplitMix64x4Core::from_seed_u64(seed))) } } impl RngCore for SplitMix64x4 { #[inline(always)] fn next_u32(&mut self) -> u32 { self.0.next_u32() } #[inline(always)] fn next_u64(&mut self) -> u64 { self.0.next_u64() } #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { self.0.fill_bytes(dest); } #[inline] fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { self.0.try_fill_bytes(dest) } } impl SeedableRng for SplitMix64x4 { type Seed = <SplitMix64x4Core as SeedableRng>::Seed; fn from_seed(seed: Self::Seed) -> Self { SplitMix64x4(BlockRng::<SplitMix64x4Core>::from_seed(seed)) } fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { BlockRng::<SplitMix64x4Core>::from_rng(rng).map(|rng| SplitMix64x4(rng)) } } #[test] fn test_vs_non_simd() { use ::rand_core::SeedableRng; use super::SplitMix64; let mut seed = [0; 32]; LittleEndian::write_u64(&mut seed[0..8], 0); LittleEndian::write_u64(&mut seed[8..16], 1); LittleEndian::write_u64(&mut seed[16..24], 2); LittleEndian::write_u64(&mut seed[24..32], 3); let mut rng_simd = SplitMix64x4Core::from_seed( SplitMix64x4Seed::new(seed)); fn splitmix_from_slice(slice: &[u8]) -> SplitMix64 { let mut seed = [0; 8]; for (x, y) in slice.iter().zip(seed.iter_mut()) { *y = *x; } SplitMix64::from_seed(seed) } let mut rngs = [ splitmix_from_slice(&seed[0..8]), splitmix_from_slice(&seed[8..16]), splitmix_from_slice(&seed[16..24]), splitmix_from_slice(&seed[24..32]), ]; let r_simd = rng_simd.next_u64x4(); let rs = [ rngs[0].next_u64(), rngs[1].next_u64(), rngs[2].next_u64(), rngs[3].next_u64(), ]; assert_eq!(r_simd.extract(0), rs[0]); assert_eq!(r_simd.extract(1), rs[1]); assert_eq!(r_simd.extract(2), rs[2]); assert_eq!(r_simd.extract(3), rs[3]); }
use rand_core::{Error, RngCore, SeedableRng}; use rand_core::block::{BlockRngCore, BlockRng}; use faster::Transmute; use faster::vecs::{u64x4}; use byteorder::{LittleEndian, ByteOrder}; use super::Linnorm64; #[allow(missing_copy_implementations)] #[derive(Debug, Clone)] pub struct SplitMix64x4Core { x: u64x4, } impl SplitMix64x4Core { #[inline]
z = (z ^ (z >> 30)) * A_MUL; z = (z ^ (z >> 27)) * B_MUL; z ^ (z >> 31) } #[inline] pub fn from_seed_u64(seed: u64) -> SplitMix64x4Core { let mut rng = Linnorm64::from_seed_u64(seed); SplitMix64x4Core::from_seed(SplitMix64x4Seed::from_rng(&mut rng)) } } pub struct SplitMix64x4Seed([u8; 32]); impl SplitMix64x4Seed { #[inline] pub fn new(seed: [u8; 32]) -> SplitMix64x4Seed { SplitMix64x4Seed(seed) } pub fn from_rng<R: RngCore>(rng: &mut R) -> SplitMix64x4Seed { let mut seed = [0; 32]; rng.fill_bytes(&mut seed); SplitMix64x4Seed(seed) } } impl ::std::convert::AsMut<[u8]> for SplitMix64x4Seed { fn as_mut(&mut self) -> &mut [u8] { &mut self.0 } } impl ::std::default::Default for SplitMix64x4Seed { fn default() -> SplitMix64x4Seed { SplitMix64x4Seed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) } } impl SeedableRng for SplitMix64x4Core { type Seed = SplitMix64x4Seed; #[inline] fn from_seed(seed: SplitMix64x4Seed) -> SplitMix64x4Core { let seed = seed.0; SplitMix64x4Core { x: u64x4::new( LittleEndian::read_u64(&seed[0..8]), LittleEndian::read_u64(&seed[8..16]), LittleEndian::read_u64(&seed[16..24]), LittleEndian::read_u64(&seed[24..32]), ), } } } impl BlockRngCore for SplitMix64x4Core { type Item = u32; type Results = [u32; 8]; #[inline] fn generate(&mut self, results: &mut Self::Results) { let r = self.next_u64x4().be_u32s(); r.store(results, 0); } } #[derive(Clone, Debug)] pub struct SplitMix64x4(BlockRng<SplitMix64x4Core>); impl SplitMix64x4 { #[inline] pub fn from_seed_u64(seed: u64) -> Self { SplitMix64x4(BlockRng::<SplitMix64x4Core>::new(SplitMix64x4Core::from_seed_u64(seed))) } } impl RngCore for SplitMix64x4 { #[inline(always)] fn next_u32(&mut self) -> u32 { self.0.next_u32() } #[inline(always)] fn next_u64(&mut self) -> u64 { self.0.next_u64() } #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { self.0.fill_bytes(dest); } #[inline] fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { self.0.try_fill_bytes(dest) } } impl SeedableRng for SplitMix64x4 { type Seed = <SplitMix64x4Core as SeedableRng>::Seed; fn from_seed(seed: Self::Seed) -> Self { SplitMix64x4(BlockRng::<SplitMix64x4Core>::from_seed(seed)) } fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { BlockRng::<SplitMix64x4Core>::from_rng(rng).map(|rng| SplitMix64x4(rng)) } } #[test] fn test_vs_non_simd() { use ::rand_core::SeedableRng; use super::SplitMix64; let mut seed = [0; 32]; LittleEndian::write_u64(&mut seed[0..8], 0); LittleEndian::write_u64(&mut seed[8..16], 1); LittleEndian::write_u64(&mut seed[16..24], 2); LittleEndian::write_u64(&mut seed[24..32], 3); let mut rng_simd = SplitMix64x4Core::from_seed( SplitMix64x4Seed::new(seed)); fn splitmix_from_slice(slice: &[u8]) -> SplitMix64 { let mut seed = [0; 8]; for (x, y) in slice.iter().zip(seed.iter_mut()) { *y = *x; } SplitMix64::from_seed(seed) } let mut rngs = [ splitmix_from_slice(&seed[0..8]), splitmix_from_slice(&seed[8..16]), splitmix_from_slice(&seed[16..24]), splitmix_from_slice(&seed[24..32]), ]; let r_simd = rng_simd.next_u64x4(); let rs = [ rngs[0].next_u64(), rngs[1].next_u64(), rngs[2].next_u64(), rngs[3].next_u64(), ]; assert_eq!(r_simd.extract(0), rs[0]); assert_eq!(r_simd.extract(1), rs[1]); assert_eq!(r_simd.extract(2), rs[2]); assert_eq!(r_simd.extract(3), rs[3]); }
pub fn next_u64x4(&mut self) -> u64x4 { const INC : u64x4 = u64x4::new(0xabdcdadb7e86b08bu64, 0x575bdce3dd69b537u64, 0x765ff07dee64eac9u64, 0x9e3779b97f4a7c15u64); const A_MUL : u64x4 = u64x4::new(0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64); const B_MUL : u64x4 = u64x4::new(0x94d049bb133111ebu64, 0x94d049bb133111ebu64, 0x94d049bb133111ebu64, 0x94d049bb133111ebu64); self.x += INC; let mut z = self.x;
function_block-random_span
[ { "content": "#[inline]\n\nfn rotate_left(x: u64x4, n: u32) -> u64x4 {\n\n // Protect against undefined behaviour for over-long bit shifts\n\n const BITS: u32 = 64;\n\n let n = n % BITS;\n\n (x << n) | (x >> ((BITS - n) % BITS))\n\n}\n\n\n\nimpl XoroShiro128x4Core {\n\n /// Return the next random...
Rust
src/keys/types.rs
ianco/aries-askar
7346f30c8c95bf2ce343bc50e0f38f4e3921c711
use std::borrow::Cow; use std::convert::Infallible; use std::fmt::{self, Debug, Display, Formatter}; use std::mem::ManuallyDrop; use std::ops::Deref; use std::ptr; use std::str::FromStr; use indy_utils::keys::{EncodedVerKey, KeyType as IndyKeyAlg, PrivateKey, VerKey}; use serde::{Deserialize, Serialize}; use zeroize::Zeroize; use crate::error::Error; use crate::types::{sorted_tags, EntryTag, SecretBytes}; #[derive(Clone, Debug, PartialEq, Eq, Zeroize)] pub enum KeyAlg { ED25519, Other(String), } serde_as_str_impl!(KeyAlg); impl KeyAlg { pub fn as_str(&self) -> &str { match self { Self::ED25519 => "ed25519", Self::Other(other) => other.as_str(), } } } impl AsRef<str> for KeyAlg { fn as_ref(&self) -> &str { self.as_str() } } impl FromStr for KeyAlg { type Err = Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "ed25519" => Self::ED25519, other => Self::Other(other.to_owned()), }) } } impl Display for KeyAlg { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } #[derive(Clone, Debug, PartialEq, Eq, Zeroize)] pub enum KeyCategory { PublicKey, KeyPair, Other(String), } impl KeyCategory { pub fn as_str(&self) -> &str { match self { Self::PublicKey => "public", Self::KeyPair => "keypair", Self::Other(other) => other.as_str(), } } pub fn into_string(self) -> String { match self { Self::Other(other) => other, _ => self.as_str().to_owned(), } } } serde_as_str_impl!(KeyCategory); impl AsRef<str> for KeyCategory { fn as_ref(&self) -> &str { self.as_str() } } impl FromStr for KeyCategory { type Err = Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "public" => Self::PublicKey, "keypair" => Self::KeyPair, other => Self::Other(other.to_owned()), }) } } impl Display for KeyCategory { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct KeyParams { pub alg: KeyAlg, #[serde(default, rename = "meta", skip_serializing_if = "Option::is_none")] pub metadata: Option<String>, #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")] pub reference: Option<String>, #[serde( default, rename = "pub", skip_serializing_if = "Option::is_none", with = "crate::serde_utils::as_base58" )] pub pub_key: Option<Vec<u8>>, #[serde( default, rename = "prv", skip_serializing_if = "Option::is_none", with = "crate::serde_utils::as_base58" )] pub prv_key: Option<SecretBytes>, } impl KeyParams { pub(crate) fn to_vec(&self) -> Result<Vec<u8>, Error> { serde_json::to_vec(self) .map_err(|e| err_msg!(Unexpected, "Error serializing key params: {}", e)) } pub(crate) fn from_slice(params: &[u8]) -> Result<KeyParams, Error> { let result = serde_json::from_slice(params) .map_err(|e| err_msg!(Unexpected, "Error deserializing key params: {}", e)); result } } impl Drop for KeyParams { fn drop(&mut self) { self.zeroize() } } impl Zeroize for KeyParams { fn zeroize(&mut self) { self.prv_key.zeroize(); } } #[derive(Clone, Debug, Eq)] pub struct KeyEntry { pub category: KeyCategory, pub ident: String, pub params: KeyParams, pub tags: Option<Vec<EntryTag>>, } impl KeyEntry { pub(crate) fn into_parts(self) -> (KeyCategory, String, KeyParams, Option<Vec<EntryTag>>) { let slf = ManuallyDrop::new(self); unsafe { ( ptr::read(&slf.category), ptr::read(&slf.ident), ptr::read(&slf.params), ptr::read(&slf.tags), ) } } pub fn is_local(&self) -> bool { self.params.reference.is_none() } pub fn encoded_verkey(&self) -> Result<EncodedVerKey, Error> { Ok(self .verkey()? .as_base58() .map_err(err_map!(Unexpected, "Error encoding verkey"))?) } pub fn verkey(&self) -> Result<VerKey, Error> { match (&self.params.alg, &self.params.pub_key) { (KeyAlg::ED25519, Some(pub_key)) => Ok(VerKey::new(pub_key, Some(IndyKeyAlg::ED25519))), (_, None) => Err(err_msg!(Input, "Undefined public key")), _ => Err(err_msg!(Unsupported, "Unsupported key algorithm")), } } pub fn private_key(&self) -> Result<PrivateKey, Error> { match (&self.params.alg, &self.params.prv_key) { (KeyAlg::ED25519, Some(prv_key)) => { Ok(PrivateKey::new(prv_key, Some(IndyKeyAlg::ED25519))) } (_, None) => Err(err_msg!(Input, "Undefined private key")), _ => Err(err_msg!(Unsupported, "Unsupported key algorithm")), } } pub(crate) fn sorted_tags(&self) -> Option<Vec<&EntryTag>> { self.tags.as_ref().and_then(sorted_tags) } } impl PartialEq for KeyEntry { fn eq(&self, rhs: &Self) -> bool { self.category == rhs.category && self.ident == rhs.ident && self.params == rhs.params && self.sorted_tags() == rhs.sorted_tags() } } #[derive(Clone)] pub struct PassKey<'a>(Option<Cow<'a, str>>); impl PassKey<'_> { pub fn as_ref(&self) -> PassKey<'_> { PassKey(Some(Cow::Borrowed(&**self))) } pub(crate) fn is_none(&self) -> bool { self.0.is_none() } pub(crate) fn into_owned(self) -> PassKey<'static> { let mut slf = ManuallyDrop::new(self); let val = slf.0.take(); PassKey(match val { None => None, Some(Cow::Borrowed(s)) => Some(Cow::Owned(s.to_string())), Some(Cow::Owned(s)) => Some(Cow::Owned(s)), }) } } impl Debug for PassKey<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if cfg!(test) { f.debug_tuple("PassKey").field(&*self).finish() } else { f.debug_tuple("PassKey").field(&"<secret>").finish() } } } impl Default for PassKey<'_> { fn default() -> Self { Self(None) } } impl Deref for PassKey<'_> { type Target = str; fn deref(&self) -> &str { match self.0.as_ref() { None => "", Some(s) => s.as_ref(), } } } impl Drop for PassKey<'_> { fn drop(&mut self) { self.zeroize(); } } impl<'a> From<&'a str> for PassKey<'a> { fn from(inner: &'a str) -> Self { Self(Some(Cow::Borrowed(inner))) } } impl From<String> for PassKey<'_> { fn from(inner: String) -> Self { Self(Some(Cow::Owned(inner))) } } impl<'a> From<Option<&'a str>> for PassKey<'a> { fn from(inner: Option<&'a str>) -> Self { Self(inner.map(Cow::Borrowed)) } } impl<'a, 'b> PartialEq<PassKey<'b>> for PassKey<'a> { fn eq(&self, other: &PassKey<'b>) -> bool { &**self == &**other } } impl Eq for PassKey<'_> {} impl Zeroize for PassKey<'_> { fn zeroize(&mut self) { match self.0.take() { Some(Cow::Owned(mut s)) => { s.zeroize(); } _ => (), } } } #[cfg(test)] mod tests { use super::*; #[test] fn key_params_roundtrip() { let params = KeyParams { alg: KeyAlg::ED25519, metadata: Some("meta".to_string()), reference: None, pub_key: Some(vec![0, 0, 0, 0]), prv_key: Some(vec![1, 1, 1, 1].into()), }; let enc_params = params.to_vec().unwrap(); let p2 = KeyParams::from_slice(&enc_params).unwrap(); assert_eq!(p2, params); } }
use std::borrow::Cow; use std::convert::Infallible; use std::fmt::{self, Debug, Display, Formatter}; use std::mem::ManuallyDrop; use std::ops::Deref; use std::ptr; use std::str::FromStr; use indy_utils::keys::{EncodedVerKey, KeyType as IndyKeyAlg, PrivateKey, VerKey}; use serde::{Deserialize, Serialize}; use zeroize::Zeroize; use crate::error::Error; use crate::types::{sorted_tags, EntryTag, SecretBytes}; #[derive(Clone, Debug, PartialEq, Eq, Zeroize)] pub enum KeyAlg { ED25519, Other(String), } serde_as_str_impl!(KeyAlg); impl KeyAlg { pub fn as_str(&self) -> &str { match self { Self::ED25519 => "ed25519", Self::Other(other) => other.as_str(), } } } impl AsRef<str> for KeyAlg { fn as_ref(&self) -> &str { self.as_str() } } impl FromStr for KeyAlg { type Err = Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "ed25519" => Self::ED25519, other => Self::Other(other.to_owned()), }) } } impl Display for KeyAlg { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } #[derive(Clone, Debug, PartialEq, Eq, Zeroize)] pub enum KeyCategory { PublicKey, KeyPair, Other(String), } impl KeyCategory { pub fn as_str(&self) -> &str { match self { Self::PublicKey => "public", Self::KeyPair => "keypair", Self::Other(other) => other.as_str(), } } pub fn into_string(self) -> String { match self { Self::Other(other) => other, _ => self.as_str().to_owned(), } } } serde_as_str_impl!(KeyCategory); impl AsRef<str> for KeyCategory { fn as_ref(&self) -> &str { self.as_str() } } impl FromStr for KeyCategory { type Err = Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "public" => Self::PublicKey, "keypair" => Self::KeyPair, other => Self::Other(other.to_owned()), }) } } impl Display for KeyCategory { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct KeyParams { pub alg: KeyAlg, #[serde(default, rename = "meta", skip_serializing_if = "Option::is_none")] pub metadata: Option<String>, #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")] pub reference: Option<String>, #[serde( default, rename = "pub", skip_serializing_if = "Option::is_none", with = "crate::serde_utils::as_base58" )] pub pub_key: Option<Vec<u8>>, #[serde( default, rename = "prv", skip_serializing_if = "Option::is_none", with = "crate::serde_utils::as_base58" )] pub prv_key: Option<SecretBytes>, } impl KeyParams { pub(crate) fn to_vec(&self) -> Result<Vec<u8>, Error> { serde_json::to_vec(self) .map_err(|e| err_msg!(Unexpected, "Error serializing key params: {}", e)) } pub(crate) fn from_slice(params: &[u8]) -> Result<KeyParams, Error> { let result = serde_json::from_slice(params) .map_err(|e| err_msg!(Unexpected, "Error deserializing key params: {}", e)); result } } impl Drop for KeyParams { fn drop(&mut self) { self.zeroize() } } impl Zeroize for KeyParams { fn zeroize(&mut self) { self.prv_key.zeroize(); } } #[derive(Clone, Debug, Eq)] pub struct KeyEntry { pub category: KeyCategory, pub ident: String, pub params: KeyParams, pub tags: Option<Vec<EntryTag>>, } impl KeyEntry { pub(crate) fn into_parts(self) -> (KeyCategory, String, KeyParams, Option<Vec<EntryTag>>) { let slf = ManuallyDrop::new(self); unsafe { ( ptr::read(&slf.category), ptr::read(&slf.ident), ptr::read(&slf.params), ptr::read(&slf.tags), ) } } pub fn is_local(&self) -> bool { self.params.reference.is_none() } pub fn encoded_verkey(&self) -> Result<EncodedVerKey, Error> { Ok(self .verkey()? .as_base58() .map_err(err_map!(Unexpected, "Error encoding verkey"))?) } pub fn verkey(&self) -> Result<VerKey, Error> { match (&self.params.alg, &self.params.pub_key) { (KeyAlg::ED25519, Some(pub_key)) => Ok(VerKey::new(pub_key, Some(IndyKeyAlg::ED25519))), (_, None) => Err(err_msg!(Input, "Undefined public key")), _ => Err(err_msg!(Unsupported, "Unsupported key algorithm")), } } pub fn private_key(&self) -> Result<PrivateKey, Error> { match (&self.params.alg, &self.params.prv_key) { (KeyAlg::ED25519, Some(prv_key)) => { Ok(PrivateKey::new(prv_key, Some(IndyKeyAlg::ED25519))) } (_, None) => Err(err_msg!(Input, "Undefined private key")), _ => Err(err_msg!(Unsupported, "Unsupported key algorithm")), } } pub(crate) fn sorted_tags(&self) -> Option<Vec<&EntryTag>> { self.tags
nt == rhs.ident && self.params == rhs.params && self.sorted_tags() == rhs.sorted_tags() } } #[derive(Clone)] pub struct PassKey<'a>(Option<Cow<'a, str>>); impl PassKey<'_> { pub fn as_ref(&self) -> PassKey<'_> { PassKey(Some(Cow::Borrowed(&**self))) } pub(crate) fn is_none(&self) -> bool { self.0.is_none() } pub(crate) fn into_owned(self) -> PassKey<'static> { let mut slf = ManuallyDrop::new(self); let val = slf.0.take(); PassKey(match val { None => None, Some(Cow::Borrowed(s)) => Some(Cow::Owned(s.to_string())), Some(Cow::Owned(s)) => Some(Cow::Owned(s)), }) } } impl Debug for PassKey<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if cfg!(test) { f.debug_tuple("PassKey").field(&*self).finish() } else { f.debug_tuple("PassKey").field(&"<secret>").finish() } } } impl Default for PassKey<'_> { fn default() -> Self { Self(None) } } impl Deref for PassKey<'_> { type Target = str; fn deref(&self) -> &str { match self.0.as_ref() { None => "", Some(s) => s.as_ref(), } } } impl Drop for PassKey<'_> { fn drop(&mut self) { self.zeroize(); } } impl<'a> From<&'a str> for PassKey<'a> { fn from(inner: &'a str) -> Self { Self(Some(Cow::Borrowed(inner))) } } impl From<String> for PassKey<'_> { fn from(inner: String) -> Self { Self(Some(Cow::Owned(inner))) } } impl<'a> From<Option<&'a str>> for PassKey<'a> { fn from(inner: Option<&'a str>) -> Self { Self(inner.map(Cow::Borrowed)) } } impl<'a, 'b> PartialEq<PassKey<'b>> for PassKey<'a> { fn eq(&self, other: &PassKey<'b>) -> bool { &**self == &**other } } impl Eq for PassKey<'_> {} impl Zeroize for PassKey<'_> { fn zeroize(&mut self) { match self.0.take() { Some(Cow::Owned(mut s)) => { s.zeroize(); } _ => (), } } } #[cfg(test)] mod tests { use super::*; #[test] fn key_params_roundtrip() { let params = KeyParams { alg: KeyAlg::ED25519, metadata: Some("meta".to_string()), reference: None, pub_key: Some(vec![0, 0, 0, 0]), prv_key: Some(vec![1, 1, 1, 1].into()), }; let enc_params = params.to_vec().unwrap(); let p2 = KeyParams::from_slice(&enc_params).unwrap(); assert_eq!(p2, params); } }
.as_ref().and_then(sorted_tags) } } impl PartialEq for KeyEntry { fn eq(&self, rhs: &Self) -> bool { self.category == rhs.category && self.ide
random
[ { "content": "/// Derive the (public) verification key for a keypair\n\npub fn derive_verkey(alg: KeyAlg, seed: &[u8]) -> Result<String> {\n\n match alg {\n\n KeyAlg::ED25519 => (),\n\n _ => return Err(err_msg!(Unsupported, \"Unsupported key algorithm\")),\n\n }\n\n\n\n let sk =\n\n ...
Rust
src/ciphers/bacon.rs
Swarley-hax/cienli
e02a20cc071812f0159d9821a8f07968645973a0
use regex::{Captures, Regex}; pub struct Bacon { letters: (char, char), } impl Bacon { pub fn new(letters: (char, char)) -> Result<Bacon, &'static str> { if letters.0 == letters.1 { return Err("Error: Letters must be different from each other!!"); } Ok(Bacon { letters: letters }) } pub fn encipher(&self, message: &str) -> String { message .to_ascii_uppercase() .chars() .map(|character| match character { 'A'..='Z' => format!("{:05b}", character as usize - 65) .replace("0", &self.letters.0.to_string()) .replace("1", &self.letters.1.to_string()), _ => character.to_string(), }) .collect::<String>() } pub fn decipher(&self, message: &str) -> String { let binary_message = message .replace(&self.letters.0.to_string(), "0") .replace(&self.letters.1.to_string(), "1"); let re = Regex::new(r"[01]{5}").unwrap(); let result = re.replace_all(&binary_message, |cap: &Captures| { ((u8::from_str_radix(&cap[0], 2).unwrap() + 65) as char).to_string() }); result.to_string() } } #[cfg(test)] mod tests { use super::Bacon; #[test] fn encipher_test() { let bacon = Bacon::new(('a', 'b')).unwrap(); assert_eq!( "aabbbaabaaababbababbabbba aababbaaababaaaaabaaabbabaaabb", bacon.encipher("Hello Friend") ); } #[test] fn decipher_test() { let bacon = Bacon::new(('a', 'b')).unwrap(); assert_eq!( "HELLO FRIEND", bacon.decipher("aabbbaabaaababbababbabbba aababbaaababaaaaabaaabbabaaabb") ); } #[test] fn encipher_with_different_letters() { let bacon = Bacon::new(('+', '=')).unwrap(); assert_eq!( "++===++=+++=+==+=+==+===+ ++=+==+++=+=+++++=+++==+=+++==", bacon.encipher("Hello Friend") ); } #[test] fn decipher_with_different_letters() { let bacon = Bacon::new(('+', '=')).unwrap(); assert_eq!( "HELLO FRIEND", bacon.decipher("++===++=+++=+==+=+==+===+ ++=+==+++=+=+++++=+++==+=+++==") ); } #[test] fn same_letters() { assert!(Bacon::new(('a', 'a')).is_err()); } }
use regex::{Captures, Regex}; pub struct Bacon { letters: (char, char), } impl Bacon { pub fn new(letters: (char, char)) -> Result<Bacon, &'static str> { if letters.0 == letters.
_test() { let bacon = Bacon::new(('a', 'b')).unwrap(); assert_eq!( "aabbbaabaaababbababbabbba aababbaaababaaaaabaaabbabaaabb", bacon.encipher("Hello Friend") ); } #[test] fn decipher_test() { let bacon = Bacon::new(('a', 'b')).unwrap(); assert_eq!( "HELLO FRIEND", bacon.decipher("aabbbaabaaababbababbabbba aababbaaababaaaaabaaabbabaaabb") ); } #[test] fn encipher_with_different_letters() { let bacon = Bacon::new(('+', '=')).unwrap(); assert_eq!( "++===++=+++=+==+=+==+===+ ++=+==+++=+=+++++=+++==+=+++==", bacon.encipher("Hello Friend") ); } #[test] fn decipher_with_different_letters() { let bacon = Bacon::new(('+', '=')).unwrap(); assert_eq!( "HELLO FRIEND", bacon.decipher("++===++=+++=+==+=+==+===+ ++=+==+++=+=+++++=+++==+=+++==") ); } #[test] fn same_letters() { assert!(Bacon::new(('a', 'a')).is_err()); } }
1 { return Err("Error: Letters must be different from each other!!"); } Ok(Bacon { letters: letters }) } pub fn encipher(&self, message: &str) -> String { message .to_ascii_uppercase() .chars() .map(|character| match character { 'A'..='Z' => format!("{:05b}", character as usize - 65) .replace("0", &self.letters.0.to_string()) .replace("1", &self.letters.1.to_string()), _ => character.to_string(), }) .collect::<String>() } pub fn decipher(&self, message: &str) -> String { let binary_message = message .replace(&self.letters.0.to_string(), "0") .replace(&self.letters.1.to_string(), "1"); let re = Regex::new(r"[01]{5}").unwrap(); let result = re.replace_all(&binary_message, |cap: &Captures| { ((u8::from_str_radix(&cap[0], 2).unwrap() + 65) as char).to_string() }); result.to_string() } } #[cfg(test)] mod tests { use super::Bacon; #[test] fn encipher
random
[ { "content": "pub fn key_gen(key: &str, message_len: usize) -> Result<String, &'static str> {\n\n let mut result: String = String::from(key);\n\n\n\n if key.len() <= 0 || message_len <= 0 {\n\n return Err(\"Error: Key and Message length must be 1 or greater than 1!!\");\n\n } else {\n\n i...
Rust
intonaco/src/cif.rs
urs-of-the-backwoods/fresco
9914df6d534f591448ed1501965f1bd03f3724de
use std; use std::io::{Cursor}; use std::mem; use libc; use std::env::vars; use std::ffi::CStr; use snowflake::ProcessUniqueId; use cbor::{Encoder}; #[cfg(unix)] use libloading::os::unix::{Library, Symbol}; #[cfg(windows)] use libloading::os::windows::{Library, Symbol}; use component; use cbor::{Config, GenericDecoder, DecodeError, value}; use entity::{Entity, EntityPointer}; use system::{System, ObjectLibSystem, CallbackSystem}; use ftypes::{FrMsg, FrMsgLength, FrComponentType, FrItemType, FrPropertyType, FrItem, FrMessageFn, FrMessageFn2}; /* void (*inEntityCreate) (FrMsg m, FrMsgLength l, FrEntity *e); // Msg contains a CBOR array from arrays [u64, bs] void (*inEntityReadComponent) (FrEntity e, FrComponentType ct, FrMessageFn f); // also names are "Entity", read write works per component void (*inEntityWriteComponent) (FrEntity e, FrComponentType ct, FrMsg m, FrMsgLength l); void (*inEntityReadId) (FrEntity e, FrItem it, FrMessageFn f); void (*inEntityDestroy) (FrEntity e); void (*inObjectLibSystemInit) (FrGiornataEnv g, msgPointer m, msgLength l, FrSystem *ps); // Msg contains specific system creation parameters void (*inObjectLibSystemAddEntity) (FrSystem s, FrEntity e); void (*inObjectLibSystemRemoveEntity) (FrSystem s, FrEntity e); void (*inObjectLibSystemShutdown) (FrSystem s); void (*inObjectLibSystemStep) (FrSystem s); // runs one cycle of system (control over Thread needed) void (*inCallbackSystemInit) (FrSystem *ps); void (*inCallbackSystemRegisterReceiver) (FrSystem s, FrEntity e, FrComponentType ct, FrMessageFn2 f); void (*inCallbackSystemShutdown) (FrSystem s); void (*inCallbackSystemStep) (FrSystem s); */ #[no_mangle] pub extern "C" fn inEntityCreate(data: *const u8, len: u32, pp: *mut EntityPointer) { let mut cts:Vec<(u64, Vec<u8>)> = Vec::new(); if len > 0 { let dv = component::vec_from_c_char_p(data, len); let mut reader = Cursor::new(dv); let mut d = GenericDecoder::new(Config::default(), reader); loop { match d.value() { Ok(value::Value::U64(u)) => { match d.value() { Ok(value::Value::Bytes(v)) => match v { value::Bytes::Bytes(v) => cts.push((u, v)), value::Bytes::Chunks(l) => cts.push((u, l.front().unwrap().clone())), }, Ok(other) => panic!("inEntityCreate, bytes not following u64: {:?}", other), Err(err) => panic!("inEntityCreate, error after u64: {:?}", err), } }, Ok(value::Value::I64(u)) => panic!("inEntityCreate, found i64 instead of u64: {:?}", u), _ => break, } } } let ep = Entity::to_ptr(Entity::new(cts)); unsafe { *pp = ep; } } #[no_mangle] pub extern "C" fn inEntityDestroy(ep: EntityPointer) { let e = Entity::from_ptr(ep); } #[no_mangle] pub extern "C" fn inEntityReadComponent(ep: EntityPointer, ct: u64, ip: FrItem, rcb: FrMessageFn) { let av = Entity::do_with(ep, (|en| { return en.get(ct); })); unsafe { rcb(ip, av.as_ptr(), av.len() as u32); } } #[no_mangle] pub extern "C" fn inEntityWriteComponent(ep: EntityPointer, ct: u64, p: *const u8, l: u32) { Entity::do_with(ep, (|en| { let v = component::vec_from_c_char_p(p, l); en.set(ct, v); })); } #[no_mangle] pub extern "C" fn inEntityId(ep: EntityPointer, ip: FrItem, rcb: FrMessageFn) { let id_bs = Entity::do_with(ep, (|en| { return en.id(); })); let id_u8 = unsafe { mem::transmute::<ProcessUniqueId, [u8; 16]>(id_bs) }; let mut buf = vec![]; let mut enc = Encoder::new(buf); enc.bytes(&id_u8); let id_bs2 = &enc.into_writer(); unsafe { rcb(ip, id_u8.as_ptr(), id_u8.len() as u32); } } #[no_mangle] pub extern "C" fn inObjectLibSystemInit(env: *const libc::c_char, pp: *mut *mut ObjectLibSystem) { for (k, v) in vars() { if k.eq( unsafe { &CStr::from_ptr(env).to_string_lossy().into_owned() }) { let lib = Library::new(v).unwrap(); let b = Box::new(ObjectLibSystem::new(&lib)); unsafe { *pp = Box::into_raw(b); } mem::forget(lib); return; } }; panic!("Intonaco: env variable GIORNATA not set!"); return; } #[no_mangle] pub extern "C" fn inObjectLibSystemStep(ols: *mut ObjectLibSystem) { unsafe { let olsb = Box::from_raw(ols); olsb.step_system(); std::mem::forget(olsb); } } #[no_mangle] pub extern "C" fn inObjectLibSystemShutdown(ols: *mut ObjectLibSystem) { } #[no_mangle] pub extern "C" fn inObjectLibSystemAddEntity (ols: *mut ObjectLibSystem, ep: EntityPointer) { unsafe { let olsb = Box::from_raw(ols); olsb.add_entity(ep); std::mem::forget(olsb); } } #[no_mangle] pub extern "C" fn inObjectLibSystemRemoveEntity (ols: *mut ObjectLibSystem, ep: EntityPointer) { } #[no_mangle] pub extern "C" fn inCallbackSystemInit(pp: *mut *mut CallbackSystem) { let b = Box::new(CallbackSystem::new()); unsafe { *pp = Box::into_raw(b); } } #[no_mangle] pub extern "C" fn inCallbackSystemRegisterReceiver (cbs: *mut CallbackSystem, ep: EntityPointer, ct: u64, mfp: FrMessageFn2) { unsafe { let cb = Box::from_raw(cbs); cb.register_callback(ep, ct, mfp); std::mem::forget(cb); } } #[no_mangle] pub extern "C" fn inCallbackSystemShutdown(cbs: *mut CallbackSystem) { } #[no_mangle] pub extern "C" fn inCallbackSystemStep(cbs: *mut CallbackSystem) { unsafe { let cb = Box::from_raw(cbs); cb.step_system(); std::mem::forget(cb); } }
use std; use std::io::{Cursor}; use std::mem; use libc; use std::env::vars; use std::ffi::CStr; use snowflake::ProcessUniqueId; use cbor::{Encoder}; #[cfg(unix)] use libloading::os::unix::{Library, Symbol}; #[cfg(windows)] use libloading::os::windows::{Library, Symbol}; use component; use cbor::{Config, GenericDecoder, DecodeError, value}; use entity::{Entity, EntityPointer}; use system::{System, ObjectLibSystem, CallbackSystem}; use ftypes::{FrMsg, FrMsgLength, FrComponentType, FrItemType, FrPropertyType, FrItem, FrMessageFn, FrMessageFn2}; /* void (*inEntityCreate) (FrMsg m, FrMsgLength l, FrEntity *e); // Msg contains a CBOR array from arrays [u64, bs] void (*inEntityReadComponent) (FrEntity e, FrComponentType ct, FrMessageFn f); // also names are "Entity", read write works per component void (*inEntityWriteComponent) (FrEntity e, FrComponentType ct, FrMsg m, FrMsgLength l); void (*inEntityReadId) (FrEntity e, FrItem it, FrMessageFn f); void (*inEntityDestroy) (FrEntity e); void (*inObjectLibSystemInit) (FrGiornataEnv g, msgPointer m, msgLength l, FrSystem *ps); // Msg contains specific system creation parameters void (*inObjectLibSystemAddEntity) (FrSystem s, FrEntity e); void (*inObjectLibSystemRemoveEntity) (FrSystem s, FrEntity e); void (*inObjectLibSystemShutdown) (FrSystem s); void (*inObjectLibSystemStep) (FrSystem s); // runs one cycle of system (control over Thread needed) void (*inCallbackSystemInit) (FrSystem *ps); void (*inCallbackSystemRegisterReceiver) (FrSystem s, FrEntity e, FrComponentType ct, FrMessageFn2 f); void (*inCallbackSystemShutdown) (FrSystem s); void (*inCallbackSystemStep) (FrSystem s); */ #[no_mangle] pub extern "C" fn inEntityCreate(data: *const u8, len: u32, pp: *mut EntityPointer) { let mut cts:Vec<(u64, Vec<u8>)> = Vec::new(); if len > 0 { let dv = component::vec_from_c_char_p(data, len); let mut reader = Cursor::new(dv); let mut d = GenericDecoder::new(Config::default(), reader); loop { match d.value() { Ok(value::Value::U64(u)) => { match d.value() { Ok(value::Value::Bytes(v)) => match v { value::Bytes::Bytes(v) => cts.push((u, v)), value::Bytes::Chunks(l) => cts.push((u, l.front().unwrap().clone())), }, Ok(other) => panic!("inEntityCreate, bytes not following u64: {:?}", other), Err(err) => panic!("inEntityCreate, error after u64: {:?}", err), } }, Ok(value::Value::I64(u)) => panic!("inEntityCreate, found i64 instead of u64: {:?}", u), _ => break, } } } let ep = Entity::to_ptr(Entity::new(cts)); unsafe { *pp = ep; } } #[no_mangle] pub extern "C" fn inEntityDestroy(ep: EntityPointer) { let e = Entity::from_ptr(ep); } #[no_mangle] pub extern "C" fn inEntityReadComponent(ep: EntityPointer, ct: u64, ip: FrItem, rcb: FrMessageFn) { let av = Entity::do_with(ep, (|en| { return en.get(ct); })); unsafe { rcb(ip, av.as_ptr(), av.len() as u32); } } #[no_mangle] pub extern "C" fn inEntityWriteComponent(ep: EntityPointer, ct: u64, p: *const u8, l: u32) { Entity::do_with(ep, (|en| { let v = component::vec_from_c_char_p(p, l); en.set(ct, v); })); } #[no_mangle] pub extern "C" fn inEntityId(ep: EntityPointer, ip: FrItem, rcb: FrMessageFn) { let id_bs = Entity::do_with(ep, (|en| { return en.id(); })); let id_u8 = unsafe { mem::transmute::<ProcessUniqueId, [u8; 16]>(id_bs) }; let mut buf = vec![]; let mut enc = Encoder::new(buf); enc.bytes(&id_u8); let id_bs2 = &enc.into_writer(); unsafe { rcb(ip, id_u8.as_ptr(), id_u8.len() as u32); } } #[no_mangle] pub extern "C" fn inObjectLibSystemInit(env: *const libc::c_char, pp: *mut *mut ObjectLibSystem) { for (k, v) in vars() { if k.eq( unsafe { &CStr::from_ptr(env).to_string_lossy().into_owned() }) { let lib = Library::new(v).unwrap(); let b = Box::new(ObjectLibSystem::new(&lib)); unsafe { *pp = Box::into_raw(b); } mem::forget(lib); return; } }; panic!("Intonaco: env variable GIORNATA not set!"); return; } #[no_mangle] pub extern "C" fn inObjectLibSystemStep(ols: *mut ObjectLibSystem) { unsafe { let olsb = Box::from_raw(ols); olsb.step_system(); std::mem::forget(olsb); } } #[no_mangle] pub extern "C" fn inObjectLibSystemShutdown(ols: *mut ObjectLibSystem) { } #[no_mangle] pub extern "C" fn inObjectLibSystemAddEntity (ols: *mut ObjectLibSystem, ep: EntityPointer) { unsafe { let olsb = Box::from_raw(ols); olsb.add_entity(ep); std::mem::forget(olsb); } } #[no_mangle] pub extern "C" fn inObjectLibSystemRemoveEntity (ols: *mut ObjectLibSystem, ep: EntityPointer) { } #[no_mangle] pub extern "C" fn inCallbackSystemInit(pp: *mut *mut CallbackSystem) { let b = Box::new(CallbackSystem::new()); unsafe { *pp = Box::into_raw(b); } } #[no_mangle]
#[no_mangle] pub extern "C" fn inCallbackSystemShutdown(cbs: *mut CallbackSystem) { } #[no_mangle] pub extern "C" fn inCallbackSystemStep(cbs: *mut CallbackSystem) { unsafe { let cb = Box::from_raw(cbs); cb.step_system(); std::mem::forget(cb); } }
pub extern "C" fn inCallbackSystemRegisterReceiver (cbs: *mut CallbackSystem, ep: EntityPointer, ct: u64, mfp: FrMessageFn2) { unsafe { let cb = Box::from_raw(cbs); cb.register_callback(ep, ct, mfp); std::mem::forget(cb); } }
function_block-full_function
[ { "content": "pub fn set_c_value(fp: FrMessageFn2, ep: EntityPointer, ct: u64, msg: &[u8]) {\n\n unsafe {\n\n fp (ep, ct, msg.as_ptr(), msg.len() as u32);\n\n }\n\n}\n\n\n\nimpl CallbackSystem {\n\n pub fn new() -> CallbackSystem {\n\n let cbs = CallbackSystem {\n\n queue: Arc:...
Rust
backend/src/api/sounds.rs
dominikks/discord-soundboard-bot
900c93f66d55434ac5e0e95fc5db224a6cf78401
use crate::api::auth::UserId; use crate::api::Snowflake; use crate::audio_utils; use crate::db::models; use crate::db::DbConn; use crate::discord::management::check_guild_moderator; use crate::discord::management::check_guild_user; use crate::discord::management::get_guilds_for_user; use crate::discord::management::PermissionError; use crate::file_handling; use crate::CacheHttp; use bigdecimal::BigDecimal; use bigdecimal::FromPrimitive; use bigdecimal::ToPrimitive; use diesel::prelude::*; use diesel::result::Error as DieselError; use rocket::data::ToByteUnit; use rocket::response::NamedFile; use rocket::response::Responder; use rocket::routes; use rocket::Data; use rocket::Route; use rocket::State; use rocket_contrib::json::Json; use serde::Deserialize; use serde::Serialize; use serde_with::serde_as; use serde_with::TimestampSeconds; use serenity::model::id::GuildId; use std::convert::TryFrom; use std::num::TryFromIntError; use std::path::PathBuf; use std::time::SystemTime; use tokio::fs; pub fn get_routes() -> Vec<Route> { routes![ list_sounds, get_sound, create_sound, update_sound, delete_sound, upload_sound ] } #[derive(Debug, Responder)] enum SoundsError { #[response(status = 500)] IoError(String), #[response(status = 500)] SerenityError(String), #[response(status = 500)] InternalError(String), #[response(status = 500)] DieselError(String), #[response(status = 403)] InsufficientPermission(String), #[response(status = 404)] NotFound(String), #[response(status = 400)] InvalidSoundfile(String), } impl SoundsError { fn bigdecimal_error() -> Self { Self::InternalError(String::from("Number handling error")) } } impl From<DieselError> for SoundsError { fn from(err: DieselError) -> Self { if err == DieselError::NotFound { Self::NotFound(String::from("A sound with the given id does not exist")) } else { Self::DieselError(String::from("Failed to load data from database.")) } } } impl From<std::io::Error> for SoundsError { fn from(_: std::io::Error) -> Self { Self::IoError(String::from("Internal IO Error")) } } impl From<serenity::Error> for SoundsError { fn from(_: serenity::Error) -> Self { Self::SerenityError(String::from("Error fetching Discord API")) } } impl From<TryFromIntError> for SoundsError { fn from(_: TryFromIntError) -> Self { Self::InternalError(String::from("Number conversion failed")) } } impl From<PermissionError> for SoundsError { fn from(_: PermissionError) -> Self { Self::InsufficientPermission(String::from( "You do not have the permission to perform this action", )) } } #[serde_as] #[serde(rename_all = "camelCase")] #[derive(Serialize, Debug)] struct Sound { id: Snowflake, guild_id: Snowflake, name: String, category: String, #[serde_as(as = "TimestampSeconds<String>")] created_at: SystemTime, volume_adjustment: Option<f32>, soundfile: Option<Soundfile>, } #[serde_as] #[serde(rename_all = "camelCase")] #[derive(Serialize, Debug)] struct Soundfile { max_volume: f32, mean_volume: f32, length: f32, #[serde_as(as = "TimestampSeconds<String>")] uploaded_at: SystemTime, } impl TryFrom<(models::Sound, Option<models::Soundfile>)> for Sound { type Error = SoundsError; fn try_from(input: (models::Sound, Option<models::Soundfile>)) -> Result<Self, Self::Error> { let (s, f) = input; Ok(Self { id: Snowflake(u64::try_from(s.id)?), guild_id: Snowflake(s.guild_id.to_u64().ok_or(SoundsError::bigdecimal_error())?), name: s.name, category: s.category, created_at: s.created_at, volume_adjustment: s.volume_adjustment, soundfile: f.map(|f| Soundfile { max_volume: f.max_volume, mean_volume: f.mean_volume, length: f.length, uploaded_at: f.uploaded_at, }), }) } } #[get("/")] async fn list_sounds( cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, ) -> Result<Json<Vec<Sound>>, SoundsError> { let guild_ids = get_guilds_for_user(cache_http.inner(), &db, user.into()) .await? .into_iter() .map(|(guildinfo, _)| { BigDecimal::from_u64(guildinfo.id.0).ok_or(SoundsError::bigdecimal_error()) }) .collect::<Result<Vec<_>, _>>()?; let sounds = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; sounds::table .filter(sounds::guild_id.eq_any(guild_ids)) .left_join(soundfiles::table) .load::<(models::Sound, Option<models::Soundfile>)>(c) }) .await?; Ok(Json( sounds .into_iter() .map(|data| Sound::try_from(data)) .collect::<Result<Vec<_>, _>>()?, )) } #[get("/<sound_id>")] async fn get_sound( sound_id: i32, cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, ) -> Result<NamedFile, SoundsError> { let (filename, guild_id) = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; soundfiles::table .find(sound_id) .inner_join(sounds::table) .select((soundfiles::file_name, sounds::guild_id)) .first::<(String, BigDecimal)>(c) }) .await?; let guild_id = GuildId(guild_id.to_u64().ok_or(SoundsError::bigdecimal_error())?); check_guild_user(&cache_http.inner(), &db, user.into(), guild_id).await?; Ok(NamedFile::open(file_handling::get_full_sound_path(&filename)).await?) } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] struct CreateSoundParameter { guild_id: Snowflake, name: String, category: String, volume_adjustment: Option<f32>, } #[post("/", format = "json", data = "<params>")] async fn create_sound( cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, params: Json<CreateSoundParameter>, ) -> Result<Json<Sound>, SoundsError> { let params = params.into_inner(); check_guild_moderator( cache_http.inner(), &db, user.clone().into(), GuildId(params.guild_id.0), ) .await?; let uid = BigDecimal::from_u64(user.0).ok_or(SoundsError::bigdecimal_error())?; let gid = BigDecimal::from_u64(params.guild_id.0).ok_or(SoundsError::bigdecimal_error())?; let sound = db .run(|c| { use crate::db::schema::sounds; diesel::insert_into(sounds::table) .values(( sounds::guild_id.eq(gid), sounds::name.eq(params.name), sounds::category.eq(params.category), sounds::volume_adjustment.eq(params.volume_adjustment), sounds::created_by_user_id.eq(Some(uid.clone())), sounds::last_edited_by_user_id.eq(Some(uid)), )) .get_result::<models::Sound>(c) }) .await?; Ok(Json(Sound::try_from((sound, None))?)) } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] struct UpdateSoundParameter { name: Option<String>, category: Option<String>, #[serde(default, with = "::serde_with::rust::double_option")] volume_adjustment: Option<Option<f32>>, } impl From<UpdateSoundParameter> for models::SoundChangeset { fn from(s: UpdateSoundParameter) -> Self { Self { name: s.name, category: s.category, volume_adjustment: s.volume_adjustment, } } } #[put("/<sound_id>", format = "json", data = "<params>")] async fn update_sound( sound_id: i32, cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, params: Json<UpdateSoundParameter>, ) -> Result<(), SoundsError> { let guild_id = db .run(move |c| { use crate::db::schema::sounds; sounds::table .find(sound_id) .select(sounds::guild_id) .first::<BigDecimal>(c) }) .await?; let guild_id = guild_id.to_u64().ok_or(SoundsError::bigdecimal_error())?; check_guild_moderator( cache_http.inner(), &db, user.clone().into(), GuildId(guild_id), ) .await?; let uid = BigDecimal::from_u64(user.0).ok_or(SoundsError::bigdecimal_error())?; let params = params.into_inner(); db.run(move |c| { use crate::db::schema::sounds; diesel::update(sounds::table.filter(sounds::id.eq(sound_id))) .set(( &models::SoundChangeset::from(params), sounds::last_edited_at.eq(SystemTime::now()), sounds::last_edited_by_user_id.eq(Some(uid)), )) .execute(c) }) .await?; Ok(()) } #[delete("/<sound_id>")] async fn delete_sound( sound_id: i32, cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, ) -> Result<(), SoundsError> { let (guild_id, file_name) = fetch_guild_and_file(sound_id, &db).await?; check_guild_moderator(cache_http.inner(), &db, user.into(), GuildId(guild_id)).await?; if let Some(file_name) = file_name { if let Err(err) = fs::remove_file(file_handling::get_full_sound_path(&file_name)).await { if err.kind() != std::io::ErrorKind::NotFound { return Err(SoundsError::InternalError(String::from( "Failed to delete the corresponding sound file", ))); } } } let affected_rows = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; diesel::delete(soundfiles::table.filter(soundfiles::sound_id.eq(sound_id))).execute(c)?; diesel::delete(sounds::table.filter(sounds::id.eq(sound_id))).execute(c) }) .await?; if affected_rows > 0 { Ok(()) } else { Err(SoundsError::NotFound(String::from( "A soundfile with the given id does not exist", ))) } } #[post("/<sound_id>", format = "audio/mpeg", data = "<data>")] async fn upload_sound( sound_id: i32, data: Data, cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, ) -> Result<Json<Soundfile>, SoundsError> { let (guild_id, file_name) = fetch_guild_and_file(sound_id, &db).await?; check_guild_moderator( cache_http.inner(), &db, user.clone().into(), GuildId(guild_id), ) .await?; let uid = BigDecimal::from_u64(user.0).ok_or(SoundsError::bigdecimal_error())?; let file_name = file_name.unwrap_or(format!("{}_{}.mp3", guild_id, sound_id)); let file_path = file_handling::get_full_sound_path(&file_name); let save_res = save_sound_file(sound_id, uid, file_name, &file_path, data, &db).await; if save_res.is_err() { let delete_res = fs::remove_file(&file_path).await; let db_res = db .run(move |c| { use crate::db::schema::soundfiles; diesel::delete(soundfiles::table.filter(soundfiles::sound_id.eq(sound_id))).execute(c) }) .await; delete_res?; db_res?; } save_res } async fn save_sound_file( sound_id: i32, user_id: BigDecimal, file_name: String, file_path: &PathBuf, data: Data, db: &DbConn, ) -> Result<Json<Soundfile>, SoundsError> { data.open(10.mebibytes()).stream_to_file(file_path).await?; let volume = audio_utils::detect_volume(&file_path).await; let length = audio_utils::get_length(&file_path).await; if let (Some(volume), Some(length)) = (volume, length) { let sound_info = models::Soundfile { sound_id, file_name, max_volume: volume.max_volume, mean_volume: volume.mean_volume, length, uploaded_by_user_id: Some(user_id), uploaded_at: SystemTime::now(), }; { let sound_info = sound_info.clone(); db.run(move |c| { use crate::db::schema::soundfiles; diesel::insert_into(soundfiles::table) .values(&sound_info) .on_conflict(soundfiles::sound_id) .do_update() .set(&sound_info) .execute(c) }) .await?; } Ok(Json(Soundfile { max_volume: sound_info.max_volume, mean_volume: sound_info.mean_volume, length: sound_info.length, uploaded_at: sound_info.uploaded_at, })) } else { Err(SoundsError::InvalidSoundfile(String::from( "File could not be analyzed. Is it corrupted?", ))) } } async fn fetch_guild_and_file( sound_id: i32, db: &DbConn, ) -> Result<(u64, Option<String>), SoundsError> { let (guild_id, file_name) = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; sounds::table .find(sound_id) .left_join(soundfiles::table) .select((sounds::guild_id, soundfiles::file_name.nullable())) .first::<(BigDecimal, Option<String>)>(c) }) .await?; Ok(( guild_id.to_u64().ok_or(SoundsError::bigdecimal_error())?, file_name, )) }
use crate::api::auth::UserId; use crate::api::Snowflake; use crate::audio_utils; use crate::db::models; use crate::db::DbConn; use crate::discord::management::check_guild_moderator; use crate::discord::management::check_guild_user; use crate::discord::management::get_guilds_for_user; use crate::discord::management::PermissionError; use crate::file_handling; use crate::CacheHttp; use bigdecimal::BigDecimal; use bigdecimal::FromPrimitive; use bigdecimal::ToPrimitive; use diesel::prelude::*; use diesel::result::Error as DieselError; use rocket::data::ToByteUnit; use rocket::response::NamedFile; use rocket::response::Responder; use rocket::routes; use rocket::Data; use rocket::Route; use rocket::State; use rocket_contrib::json::Json; use serde::Deserialize; use serde::Serialize; use serde_with::serde_as; use serde_with::TimestampSeconds; use serenity::model::id::GuildId; use std::convert::TryFrom; use std::num::TryFromIntError; use std::path::PathBuf; use std::time::SystemTime; use tokio::fs; pub fn get_routes() -> Vec<Route> { routes![ list_sounds, get_sound, create_sound, update_sound, delete_sound, upload_sound ] } #[derive(Debug, Responder)] enum SoundsError { #[response(status = 500)] IoError(String), #[response(status = 500)] SerenityError(String), #[response(status = 500)] InternalError(String), #[response(status = 500)] DieselError(String), #[response(status = 403)] InsufficientPermission(String), #[response(status = 404)] NotFound(String), #[response(status = 400)] InvalidSoundfile(String), } impl SoundsError { fn bigdecimal_error() -> Self { Self::InternalError(String::from("Number handling error")) } } impl From<DieselError> for SoundsError { fn from(err: DieselError) -> Self { if err == DieselError::NotFound { Self::NotFound(String::from("A sound with the given id does not exist")) } else { Self::DieselError(String::from("Failed to load data from database.")) } } } impl From<std::io::Error> for SoundsError { fn from(_: std::io::Error) -> Self { Self::IoError(String::from("Internal IO Error")) } } impl From<serenity::Error> for SoundsError { fn from(_: serenity::Error) -> Self { Self::SerenityError(String::from("Error fetching Discord API")) } } impl From<TryFromIntError> for SoundsError { fn from(_: TryFromIntError) -> Self { Self::InternalError(String::from("Number conversion failed")) } } impl From<PermissionError> for SoundsError { fn from(_: PermissionError) -> Self { Self::InsufficientPermission(String::from( "You do not have the permission to perform this action", )) } } #[serde_as] #[serde(rename_all = "camelCase")] #[derive(Serialize, Debug)] struct Sound { id: Snowflake, guild_id: Snowflake, name: String, category: String, #[serde_as(as = "TimestampSeconds<String>")] created_at: SystemTime, volume_adjustment: Option<f32>, soundfile: Option<Soundfile>, } #[serde_as] #[serde(rename_all = "camelCase")] #[derive(Serialize, Debug)] struct Soundfile { max_volume: f32, mean_volume: f32, length: f32, #[serde_as(as = "TimestampSeconds<String>")] uploaded_at: SystemTime, } impl TryFrom<(models::Sound, Option<models::Soundfile>)> for Sound { type Error = SoundsError; fn try_from(input: (models::Sound, Option<models::Soundfile>)) -> Result<Self, Self::Error> { let (s, f) = input; Ok(Self { id: Snowflake(u64::try_from(s.id)?), guild_id: Snowflake(s.guild_id.to_u64().ok_or(SoundsError::bigdecimal_error())?), name: s.name, category: s.category, created_at: s.created_at, volume_adjustment: s.volume_adjustment, soundfile: f.map(|f| Soundfile { max_volume: f.max_volume, mean_volume: f.mean_volume, length: f.length, uploaded_at: f.uploaded_at, }), }) } } #[get("/")] async fn list_sounds( cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, ) -> Result<Json<Vec<Sound>>, SoundsError> { let guild_ids = get_guilds_for_user(cache_http.inner(), &db, user.into()) .await? .into_iter() .map(|(guildinfo, _)| { BigDecimal::from_u64(guildinfo.id.0).ok_or(SoundsError::bigdecimal_error()) }) .collect::<Result<Vec<_>, _>>()?; let sounds = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; sounds::table .filter(sounds::guild_id.eq_any(guild_ids)) .left_join(soundfiles::table) .load::<(models::Sound, Option<models::Soundfile>)>(c) }) .await?; Ok(Json( sounds .into_iter() .map(|data| Sound::try_from(data)) .collect::<Result<Vec<_>, _>>()?, )) } #[get("/<sound_id>")] async fn get_sound( sound_id: i32, cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, ) -> Result<NamedFile, SoundsError> { let (filename, guild_id) = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; soundfiles::table .find(sound_id) .inner_join(sounds::table) .select((soundfiles::file_name, sounds::guild_id)) .first::<(String, BigDecimal)>(c) }) .await?; let guild_id = GuildId(guild_id.to_u64().ok_or(SoundsError::bigdecimal_error())?); check_guild_user(&cache_http.inner(), &db, user.into(), guild_id).await?; Ok(NamedFile::open(file_handling::get_full_sound_path(&filename)).await?) } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] struct CreateSoundParameter { guild_id: Snowflake, name: String, category: String, volume_adjustment: Option<f32>, } #[post("/", format = "json", data = "<params>")] async fn create_sound( cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, params: Json<CreateSoundParameter>, ) -> Result<Json<Sound>, SoundsError> { let params = params.into_inner(); check_guild_moderator( cache_http.inner(), &db, user.clone().into(), GuildId(params.guild_id.0), ) .await?; let uid = BigDecimal::from_u64(user.0).ok_or(SoundsError::bigdecimal_error())?; let gid = BigDecimal::from_u64(params.guild_id.0).ok_or(SoundsError::bigdecimal_error())?; let sound = db .run(|c| { use crate::db::schema::sounds; diesel::insert_into(sounds::table) .values(( sounds::guild_id.eq(gid), sounds::name.eq(params.name), sounds::category.eq(params.category), sounds::volume_adjustment.eq(params.volume_adjustment), sounds::created_by_user_id.eq(Some(uid.clone())), sounds::last_edited_by_user_id.eq(Some(uid)), )) .get_result::<models::Sound>(c) }) .await?; Ok(Json(Sound::try_from((sound, None))?)) } #[serde(rename_all = "camelCase")] #[derive(Deserialize, Debug)] struct UpdateSoundParameter { name: Option<String>, category: Option<String>, #[serde(default, with = "::serde_with::rust::doub
sError> { let (guild_id, file_name) = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; sounds::table .find(sound_id) .left_join(soundfiles::table) .select((sounds::guild_id, soundfiles::file_name.nullable())) .first::<(BigDecimal, Option<String>)>(c) }) .await?; Ok(( guild_id.to_u64().ok_or(SoundsError::bigdecimal_error())?, file_name, )) }
le_option")] volume_adjustment: Option<Option<f32>>, } impl From<UpdateSoundParameter> for models::SoundChangeset { fn from(s: UpdateSoundParameter) -> Self { Self { name: s.name, category: s.category, volume_adjustment: s.volume_adjustment, } } } #[put("/<sound_id>", format = "json", data = "<params>")] async fn update_sound( sound_id: i32, cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, params: Json<UpdateSoundParameter>, ) -> Result<(), SoundsError> { let guild_id = db .run(move |c| { use crate::db::schema::sounds; sounds::table .find(sound_id) .select(sounds::guild_id) .first::<BigDecimal>(c) }) .await?; let guild_id = guild_id.to_u64().ok_or(SoundsError::bigdecimal_error())?; check_guild_moderator( cache_http.inner(), &db, user.clone().into(), GuildId(guild_id), ) .await?; let uid = BigDecimal::from_u64(user.0).ok_or(SoundsError::bigdecimal_error())?; let params = params.into_inner(); db.run(move |c| { use crate::db::schema::sounds; diesel::update(sounds::table.filter(sounds::id.eq(sound_id))) .set(( &models::SoundChangeset::from(params), sounds::last_edited_at.eq(SystemTime::now()), sounds::last_edited_by_user_id.eq(Some(uid)), )) .execute(c) }) .await?; Ok(()) } #[delete("/<sound_id>")] async fn delete_sound( sound_id: i32, cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, ) -> Result<(), SoundsError> { let (guild_id, file_name) = fetch_guild_and_file(sound_id, &db).await?; check_guild_moderator(cache_http.inner(), &db, user.into(), GuildId(guild_id)).await?; if let Some(file_name) = file_name { if let Err(err) = fs::remove_file(file_handling::get_full_sound_path(&file_name)).await { if err.kind() != std::io::ErrorKind::NotFound { return Err(SoundsError::InternalError(String::from( "Failed to delete the corresponding sound file", ))); } } } let affected_rows = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; diesel::delete(soundfiles::table.filter(soundfiles::sound_id.eq(sound_id))).execute(c)?; diesel::delete(sounds::table.filter(sounds::id.eq(sound_id))).execute(c) }) .await?; if affected_rows > 0 { Ok(()) } else { Err(SoundsError::NotFound(String::from( "A soundfile with the given id does not exist", ))) } } #[post("/<sound_id>", format = "audio/mpeg", data = "<data>")] async fn upload_sound( sound_id: i32, data: Data, cache_http: State<'_, CacheHttp>, db: DbConn, user: UserId, ) -> Result<Json<Soundfile>, SoundsError> { let (guild_id, file_name) = fetch_guild_and_file(sound_id, &db).await?; check_guild_moderator( cache_http.inner(), &db, user.clone().into(), GuildId(guild_id), ) .await?; let uid = BigDecimal::from_u64(user.0).ok_or(SoundsError::bigdecimal_error())?; let file_name = file_name.unwrap_or(format!("{}_{}.mp3", guild_id, sound_id)); let file_path = file_handling::get_full_sound_path(&file_name); let save_res = save_sound_file(sound_id, uid, file_name, &file_path, data, &db).await; if save_res.is_err() { let delete_res = fs::remove_file(&file_path).await; let db_res = db .run(move |c| { use crate::db::schema::soundfiles; diesel::delete(soundfiles::table.filter(soundfiles::sound_id.eq(sound_id))).execute(c) }) .await; delete_res?; db_res?; } save_res } async fn save_sound_file( sound_id: i32, user_id: BigDecimal, file_name: String, file_path: &PathBuf, data: Data, db: &DbConn, ) -> Result<Json<Soundfile>, SoundsError> { data.open(10.mebibytes()).stream_to_file(file_path).await?; let volume = audio_utils::detect_volume(&file_path).await; let length = audio_utils::get_length(&file_path).await; if let (Some(volume), Some(length)) = (volume, length) { let sound_info = models::Soundfile { sound_id, file_name, max_volume: volume.max_volume, mean_volume: volume.mean_volume, length, uploaded_by_user_id: Some(user_id), uploaded_at: SystemTime::now(), }; { let sound_info = sound_info.clone(); db.run(move |c| { use crate::db::schema::soundfiles; diesel::insert_into(soundfiles::table) .values(&sound_info) .on_conflict(soundfiles::sound_id) .do_update() .set(&sound_info) .execute(c) }) .await?; } Ok(Json(Soundfile { max_volume: sound_info.max_volume, mean_volume: sound_info.mean_volume, length: sound_info.length, uploaded_at: sound_info.uploaded_at, })) } else { Err(SoundsError::InvalidSoundfile(String::from( "File could not be analyzed. Is it corrupted?", ))) } } async fn fetch_guild_and_file( sound_id: i32, db: &DbConn, ) -> Result<(u64, Option<String>), Sound
random
[ { "content": "pub fn get_full_sound_path(filename: &str) -> PathBuf {\n\n (*SOUNDS_FOLDER).join(filename)\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum FileError {\n\n IoError(io::Error),\n\n}\n\n\n\nimpl From<io::Error> for FileError {\n\n fn from(err: io::Error) -> Self {\n\n FileError::IoError(err)\n\n }\n...
Rust
tests/board.rs
SamRond/alpha-rust
434e6cc4c95ebd337f021f64c555b70c012010f4
mod utils; #[cfg(test)] mod tests { use alpha_rust::Board; use std::sync::Once; static INIT: Once = Once::new(); fn init() { INIT.call_once(|| { crate::utils::set_panic_hook(); }); } #[test] fn test_board_init() { init(); let board = Board::new("".to_string()); print!("\n\n"); print!("Checking if FEN is set to correct default value... "); assert_eq!(board.get_fen(), "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); println!("true"); print!("Checking if white pieces are correctly initialized... "); assert_eq!(board.get_white_pieces()[0].len(), 8); assert_eq!(board.get_white_pieces()[1].len(), 2); assert_eq!(board.get_white_pieces()[2].len(), 2); assert_eq!(board.get_white_pieces()[3].len(), 2); assert_eq!(board.get_white_pieces()[4].len(), 1); assert_eq!(board.get_white_pieces()[5].len(), 1); println!("true"); print!("Checking if black pieces are correctly initialized... "); assert_eq!(board.get_black_pieces()[0].len(), 8); assert_eq!(board.get_black_pieces()[1].len(), 2); assert_eq!(board.get_black_pieces()[2].len(), 2); assert_eq!(board.get_black_pieces()[3].len(), 2); assert_eq!(board.get_black_pieces()[4].len(), 1); assert_eq!(board.get_black_pieces()[5].len(), 1); println!("true"); print!("Checking if black king is in correct position... "); assert_eq!(board.get_black_pieces()[5][0].get_position(), alpha_rust::Coordinates { rank: 8, file: 5}); println!("true"); print!("Checking if white king is in correct position... "); assert_eq!(board.get_white_pieces()[5][0].get_position(), alpha_rust::Coordinates { rank: 1, file: 5}); println!("true"); print!("Checking if e2 pawn is in correct position... "); assert_eq!(board.get_white_pieces()[0][4].get_position(), alpha_rust::Coordinates { rank: 2, file: 5}); println!("true"); print!("Checking if e7 pawn is in correct position... "); assert_eq!(board.get_black_pieces()[0][4].get_position(), alpha_rust::Coordinates { rank: 7, file: 5}); println!("true"); print!("\n\n"); } #[test] fn test_board_init_with_fen() { init(); let board = Board::new("rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2".to_string()); print!("Checking if FEN is set to correct value... "); assert_eq!(board.get_fen(), "rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2"); println!("true"); print!("Checking if white e pawn is in correct position... "); assert_eq!(board.get_white_pieces()[0][0].get_position(), alpha_rust::Coordinates { rank: 4, file: 5}); println!("true"); print!("Checking if black c pawn is in correct position... "); assert_eq!(board.get_black_pieces()[0][7].get_position(), alpha_rust::Coordinates { rank: 5, file: 3}); println!("true"); print!("Checking if white knight is in correct position... "); assert_eq!(board.get_white_pieces()[1][0].get_position(), alpha_rust::Coordinates { rank: 3, file: 6}); println!("true"); } #[test] fn test_board_init_with_two_queens() { init(); let board = Board::new("rnbqkbnr/pp1ppqpp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2".to_string()); print!("Checking if FEN is set to correct value... "); assert_eq!(board.get_fen(), "rnbqkbnr/pp1ppqpp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2"); println!("true"); print!("Checking if white a pawn is in correct position... "); assert_eq!(board.get_white_pieces()[0][0].get_position(), alpha_rust::Coordinates { rank: 4, file: 5}); println!("true"); print!("Checking if black h pawn is in correct position... "); assert_eq!(board.get_black_pieces()[0][6].get_position(), alpha_rust::Coordinates { rank: 5, file: 3}); println!("true"); print!("Checking if white knight is in correct position... "); assert_eq!(board.get_white_pieces()[1][0].get_position(), alpha_rust::Coordinates { rank: 3, file: 6}); println!("true"); print!("Checking if first black queen is in correct position... "); assert_eq!(board.get_black_pieces()[4][0].get_position(), alpha_rust::Coordinates { rank: 8, file: 4}); println!("true"); print!("Checking if second black queen is in correct position... "); assert_eq!(board.get_black_pieces()[4][1].get_position(), alpha_rust::Coordinates { rank: 7, file: 6}); println!("true"); } #[test] fn test_pawn_move() { init(); let mut board = Board::new("".to_string()); print!("\n\n"); print!("Checking if pawn move 1. e4 is successful... "); let pawn = &mut board.get_white_pieces()[0][4]; let mv = board.make_move(pawn, 4, 5); assert!(mv); assert_eq!(board.find_piece_by_coords(4, 5).unwrap(), pawn); println!("true"); } #[test] fn test_knight_move() { let mut board = Board::new("".to_string()); print!("\n\n"); print!("Checking if knight move is successful... "); let knight = &mut board.get_white_pieces()[1][1]; let mv = board.make_move(knight, 3, 6); assert!(mv); let res = board.find_piece_by_coords(3, 6).unwrap(); assert_eq!(res.get_position(), board.get_white_pieces()[1][1].get_position()); println!("true"); print!("\n\n"); } #[test] fn test_for_in_check() { let mut board = Board::new("".to_string()); print!("\n\n"); let w_pawn = &mut board.get_white_pieces()[0][4]; board.make_move(w_pawn, 4, 5); let b_pawn = &mut board.get_black_pieces()[0][5]; board.make_move(b_pawn, 5, 6); let w_queen = &mut board.get_white_pieces()[4][0]; board.make_move(w_queen, 5, 8); } }
mod utils; #[cfg(test)] mod tests { use alpha_rust::Board; use std::sync::Once; static INIT: Once = Once::new(); fn init() { INIT.call_once(|| { crate::utils::set_panic_hook(); }); } #[test] fn test_board_init() { init(); let board = Board::new("".to_string()); print!("\n\n"); print!("Checking if FEN is set to correct default value... "); assert_eq!(board.get_fen(), "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); println!("true"); print!("Checking if white pieces are correctly initialized... "); assert_eq!(board.get_white_pieces()[0].len(), 8); assert_eq!(board.get_white_pieces()[1].len(), 2); assert_eq!(board.get_white_pieces()[2].len(), 2); assert_eq!(board.get_white_pieces()[3].len(), 2); assert_eq!(board.get_white_pieces()[4].len(), 1); assert_eq!(board.get_white_pieces()[5].len(), 1); println!("true"); print!("Checking if black pieces are correctly initialized... "); assert_eq!(board.get_black_pieces()[0].len(), 8); assert_eq!(board.get_black_pieces()[1].len(), 2); assert_eq!(board.get_black_pieces()[2].len(), 2); assert_eq!(board.get_black_pieces()[3].len(), 2); assert_eq!(board.get_black_pieces()[4].len(), 1); assert_eq!(board.get_black_pieces()[5].len(), 1); println!("true"); print!("Checking if black king is in correct position... "); assert_eq!(board.get_black_pieces()[5][0].get_position(), alpha_rust::Coordinates { rank: 8, file: 5}); println!("true"); print!("Checking if white king is in correct position... "); assert_eq!(board.get_white_pieces()[5][0].get_position(), alpha_rust::Coordinates { rank: 1, file: 5}); println!("true"); print!("Checking if e2 pawn is in correct position... "); assert_eq!(board.get_white_pieces()[0][4].get_position(), alpha_rust::Coordinates { rank: 2, file: 5}); println!("true"); print!("Checking if e7 pawn is in correct position... "); assert_eq!(board.get_black_pieces()[0][4].get_position(), alpha_rust::Coordinates { rank: 7, file: 5}); println!("true"); print!("\n\n"); } #[test] fn test_board_init_with_fen() { init(); let board = Board::new("rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2".to_string()); print!("Checking if FEN is set to correct value... "); assert_eq!(board.get_fen(), "rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2"); println!("true"); print!("Checking if white e pawn is in correct position... "); assert_eq!(board.get_white_pieces()[0][0].get_position(), alpha_rust::Coordinates { rank: 4, file: 5}); println!("true"); print!("Checking if black c pawn is in correct position... "); assert_eq!(board.get_black_pieces()[0][7].get_position(), alpha_rust::Coordinates { rank: 5, file: 3}); println!("true"); print!("Checking if white knight is in correct position... "); assert_eq!(board.get_white_pieces()[1][0].get_position(), alpha_rust::Coordinates { rank: 3, file: 6}); println!("true"); } #[test] fn test_board_init_with_two_queens() { init(); let board = Board::new("rnbqkbnr/pp1ppqpp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2".to_string()); print!("Checking if FEN is set to correct value... "); assert_eq!(board.get_fen(), "rnbqkbnr/pp1ppqpp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2"); println!("true"); print!("Checking if white a pawn is in correct position... "); assert_eq!(board.get_white_pieces()[0][0].get_position(), alpha_rust::Coordinates { rank: 4, file: 5}); println!("true"); print!("Checking if black h pawn is in correct position... "); assert_eq!(board.get_black_pieces()[0][6].get_position(), alpha_rust::Coordinates { rank: 5, file: 3}); println!("true"); print!("Checking if white knight is in correct position... "); assert_eq!(board.get_white_pieces()[1][0].get_position(), alpha_rust::Coordinates { rank: 3, file: 6}); println!("true"); print!("Checking if first black queen is in correct position... "); assert_eq!(board.get_black_pieces()[4][0].get_position(), alpha_rust::Coordinates { rank: 8, file: 4}); println!("true"); print!("Checking if second black queen is in correct position... "); assert_eq!(board.get_black_pieces()[4][1].get_position(), alpha_rust::Coordinates { rank: 7, file: 6}); println!("true"); } #[test] fn test_pawn_move() { init(); let mut board = Board::new("".to_string()); print!("\n\n"); print!("Checking if pawn move 1. e4 is successful... "); let pawn = &mut board.get_white_pieces()[0][4];
#[test] fn test_knight_move() { let mut board = Board::new("".to_string()); print!("\n\n"); print!("Checking if knight move is successful... "); let knight = &mut board.get_white_pieces()[1][1]; let mv = board.make_move(knight, 3, 6); assert!(mv); let res = board.find_piece_by_coords(3, 6).unwrap(); assert_eq!(res.get_position(), board.get_white_pieces()[1][1].get_position()); println!("true"); print!("\n\n"); } #[test] fn test_for_in_check() { let mut board = Board::new("".to_string()); print!("\n\n"); let w_pawn = &mut board.get_white_pieces()[0][4]; board.make_move(w_pawn, 4, 5); let b_pawn = &mut board.get_black_pieces()[0][5]; board.make_move(b_pawn, 5, 6); let w_queen = &mut board.get_white_pieces()[4][0]; board.make_move(w_queen, 5, 8); } }
let mv = board.make_move(pawn, 4, 5); assert!(mv); assert_eq!(board.find_piece_by_coords(4, 5).unwrap(), pawn); println!("true"); }
function_block-function_prefix_line
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
src/file_link.rs
vikigenius/dlm
d449e0cc490b999a41c5d73cbf364437593cafae
use crate::dlm_error::DlmError; use crate::dlm_error::DlmError::Other; use std::str; pub struct FileLink { pub url: String, pub file_name_no_extension: String, pub extension: String, pub file_name: String, } const NO_EXT: &str = ".NO_EXT"; impl FileLink { pub fn new(url: String) -> Result<FileLink, DlmError> { let trimmed = url.trim(); if trimmed.is_empty() { Err(Other { message: "FileLink cannot be built from an empty URL".to_string(), }) } else if trimmed.ends_with('/') { let message = format!( "FileLink cannot be built with an invalid extension '{}'", trimmed ); Err(Other { message }) } else { let url_decoded = url_decode(url.as_str())?; let last_segment_rev: String = url_decoded.chars().rev().take_while(|c| c != &'/').collect(); let (extension, file_name_no_extension) = if last_segment_rev.contains('.') { let ext_rev: String = last_segment_rev.chars().take_while(|c| c != &'.').collect(); let ext: String = ext_rev.chars().rev().collect(); let tmp: String = url_decoded .chars() .rev() .skip(ext.len()) .take_while(|c| c != &'/') .collect(); let file_name_no_extension: String = tmp.chars().rev().collect(); (ext, file_name_no_extension) } else { let file_name_no_extension: String = last_segment_rev.chars().rev().collect(); (NO_EXT.to_string(), file_name_no_extension) }; let file_name = format!("{}{}", file_name_no_extension, extension); let file_link = FileLink { url, file_name_no_extension, extension, file_name, }; Ok(file_link) } } pub fn full_path(&self, output_dir: &str) -> String { format!("{}/{}", output_dir, self.file_name) } } fn url_decode(data: &str) -> Result<String, DlmError> { let mut unescaped_bytes: Vec<u8> = Vec::new(); let mut bytes = data.bytes(); while let Some(b) = bytes.next() { match b as char { '%' => { let bytes_to_decode = &[bytes.next().unwrap(), bytes.next().unwrap()]; let hex_str = str::from_utf8(bytes_to_decode).unwrap(); unescaped_bytes.push(u8::from_str_radix(hex_str, 16).unwrap()); } _ => { unescaped_bytes.push(b); } } } String::from_utf8(unescaped_bytes).map_err(|e| DlmError::UrlDecodeError { message: e.to_string(), }) } #[cfg(test)] mod file_link_tests { use crate::dlm_error::DlmError; use crate::file_link::*; #[test] fn no_empty_string() { match FileLink::new("".to_string()) { Err(DlmError::Other { message }) => assert_eq!( message, "FileLink cannot be built from an empty URL".to_string() ), _ => assert_eq!(true, false), } } #[test] fn happy_case() { let url = "http://www.google.com/area51.txt".to_string(); match FileLink::new(url.clone()) { Ok(fl) => { assert_eq!(fl.url, url); assert_eq!(fl.file_name, "area51.txt".to_string()); assert_eq!(fl.extension, "txt".to_string()); assert_eq!(fl.file_name_no_extension, "area51.".to_string()); } _ => assert_eq!(true, false), } } #[test] fn full_path() { let url = "http://www.google.com/area51.txt".to_string(); let fl = FileLink::new(url).unwrap(); let full_path = fl.full_path("/secret-folder"); assert_eq!(full_path, "/secret-folder/area51.txt".to_string()) } #[test] fn trailing_slash() { let url = "http://www.google.com/area51/".to_string(); match FileLink::new(url.clone()) { Err(DlmError::Other { message }) => assert_eq!( message, "FileLink cannot be built with an invalid extension 'http://www.google.com/area51/'".to_string() ), _ => assert_eq!(true, false), } } #[test] fn no_extension() { let url = "http://www.google.com/area51".to_string(); let fl = FileLink::new(url).unwrap(); let full_path = fl.full_path("/secret-folder"); assert_eq!(full_path, "/secret-folder/area51.NO_EXT".to_string()) } }
use crate::dlm_error::DlmError; use crate::dlm_error::DlmError::Other; use std::str; pub struct FileLink { pub url: String, pub file_name_no_extension: String, pub extension: String, pub file_name: String, } const NO_EXT: &str = ".NO_EXT"; impl FileLink { pub fn new(url: String) -> Result<FileLink, DlmError> { let trimmed = url.trim(); if trimmed.is_empty() { Err(Other { message: "FileLink cannot be built from an empty URL".to_string(), }) } else if trimmed.ends_with('/') { let message = format!( "FileLink cannot be built with an invalid extension '{}'", trimmed ); Err(Other { message }) } else { let url_decoded = url_decode(url.as_str())?; let last_segment_rev: String = url_decoded.chars().rev().take_while(|c| c != &'/').collect(); let (extension, file_name_no_extension) = if last_segment_rev.contains('.') { let ext_rev: String = last_segment_rev.chars().take_while(|c| c != &'.').collect(); let ext: String = ext_rev.chars().rev().collect(); let tmp: String = url_decoded .chars() .rev() .skip(ext.len()) .take_while(|c| c != &'/') .collect(); let file_name_no_extension: String = tmp.chars().rev().collect(); (ext, file_name_no_extension) } else { let file_name_no_extension: String = last_segment_rev.chars().rev().collect(); (NO_EXT.to_string(), file_name_no_extension) }; l
; assert_eq!(fl.file_name_no_extension, "area51.".to_string()); } _ => assert_eq!(true, false), } } #[test] fn full_path() { let url = "http://www.google.com/area51.txt".to_string(); let fl = FileLink::new(url).unwrap(); let full_path = fl.full_path("/secret-folder"); assert_eq!(full_path, "/secret-folder/area51.txt".to_string()) } #[test] fn trailing_slash() { let url = "http://www.google.com/area51/".to_string(); match FileLink::new(url.clone()) { Err(DlmError::Other { message }) => assert_eq!( message, "FileLink cannot be built with an invalid extension 'http://www.google.com/area51/'".to_string() ), _ => assert_eq!(true, false), } } #[test] fn no_extension() { let url = "http://www.google.com/area51".to_string(); let fl = FileLink::new(url).unwrap(); let full_path = fl.full_path("/secret-folder"); assert_eq!(full_path, "/secret-folder/area51.NO_EXT".to_string()) } }
et file_name = format!("{}{}", file_name_no_extension, extension); let file_link = FileLink { url, file_name_no_extension, extension, file_name, }; Ok(file_link) } } pub fn full_path(&self, output_dir: &str) -> String { format!("{}/{}", output_dir, self.file_name) } } fn url_decode(data: &str) -> Result<String, DlmError> { let mut unescaped_bytes: Vec<u8> = Vec::new(); let mut bytes = data.bytes(); while let Some(b) = bytes.next() { match b as char { '%' => { let bytes_to_decode = &[bytes.next().unwrap(), bytes.next().unwrap()]; let hex_str = str::from_utf8(bytes_to_decode).unwrap(); unescaped_bytes.push(u8::from_str_radix(hex_str, 16).unwrap()); } _ => { unescaped_bytes.push(b); } } } String::from_utf8(unescaped_bytes).map_err(|e| DlmError::UrlDecodeError { message: e.to_string(), }) } #[cfg(test)] mod file_link_tests { use crate::dlm_error::DlmError; use crate::file_link::*; #[test] fn no_empty_string() { match FileLink::new("".to_string()) { Err(DlmError::Other { message }) => assert_eq!( message, "FileLink cannot be built from an empty URL".to_string() ), _ => assert_eq!(true, false), } } #[test] fn happy_case() { let url = "http://www.google.com/area51.txt".to_string(); match FileLink::new(url.clone()) { Ok(fl) => { assert_eq!(fl.url, url); assert_eq!(fl.file_name, "area51.txt".to_string()); assert_eq!(fl.extension, "txt".to_string())
random
[ { "content": "pub fn get_args() -> (String, usize, String) {\n\n let app = app();\n\n let matches = app.get_matches();\n\n\n\n let max_concurrent_downloads = matches.value_of_t(\"maxConcurrentDownloads\")\n\n .expect(\"maxConcurrentDownloads was not an integer\");\n\n if max_concurrent_downlo...
Rust
services/pool/src/service.rs
tiagolobocastro/Mayastor
c9cf777e7776f529a2433d29b8513d1c601684a6
#![allow(clippy::unit_arg)] use super::*; use common::wrapper::v0::*; #[derive(Clone, Debug, Default)] pub(super) struct PoolSvc { registry: Registry<NodeWrapperPool>, } impl PoolSvc { pub fn new(period: std::time::Duration) -> Self { let obj = Self { registry: Registry::new(period), }; obj.start(); obj } fn start(&self) { self.registry.start(); } async fn get_node_pools( &self, node_id: Option<NodeId>, ) -> Result<Vec<Pool>, SvcError> { Ok(match node_id { None => self.registry.list_pools().await, Some(node_id) => self.registry.list_node_pools(&node_id).await, }) } async fn get_node_replicas( &self, node_id: Option<NodeId>, ) -> Result<Vec<Replica>, SvcError> { Ok(match node_id { None => self.registry.list_replicas().await, Some(node_id) => self.registry.list_node_replicas(&node_id).await, }) } #[tracing::instrument(level = "debug", err)] pub(super) async fn get_pools( &self, request: &GetPools, ) -> Result<Pools, SvcError> { let filter = request.filter.clone(); Ok(Pools(match filter { Filter::None => self.get_node_pools(None).await?, Filter::Node(node_id) => self.get_node_pools(Some(node_id)).await?, Filter::NodePool(node_id, pool_id) => { let pools = self.get_node_pools(Some(node_id)).await?; pools.iter().filter(|&p| p.id == pool_id).cloned().collect() } Filter::Pool(pool_id) => { let pools = self.get_node_pools(None).await?; pools.iter().filter(|&p| p.id == pool_id).cloned().collect() } _ => { return Err(SvcError::InvalidFilter { filter, }) } })) } #[tracing::instrument(level = "debug", err)] pub(super) async fn get_replicas( &self, request: &GetReplicas, ) -> Result<Replicas, SvcError> { let filter = request.filter.clone(); Ok(Replicas(match filter { Filter::None => self.get_node_replicas(None).await?, Filter::Node(node_id) => { self.get_node_replicas(Some(node_id)).await? } Filter::NodePool(node_id, pool_id) => { let replicas = self.get_node_replicas(Some(node_id)).await?; replicas .iter() .filter(|&p| p.pool == pool_id) .cloned() .collect() } Filter::Pool(pool_id) => { let replicas = self.get_node_replicas(None).await?; replicas .iter() .filter(|&p| p.pool == pool_id) .cloned() .collect() } Filter::NodePoolReplica(node_id, pool_id, replica_id) => { let replicas = self.get_node_replicas(Some(node_id)).await?; replicas .iter() .filter(|&p| p.pool == pool_id && p.uuid == replica_id) .cloned() .collect() } Filter::NodeReplica(node_id, replica_id) => { let replicas = self.get_node_replicas(Some(node_id)).await?; replicas .iter() .filter(|&p| p.uuid == replica_id) .cloned() .collect() } Filter::PoolReplica(pool_id, replica_id) => { let replicas = self.get_node_replicas(None).await?; replicas .iter() .filter(|&p| p.pool == pool_id && p.uuid == replica_id) .cloned() .collect() } Filter::Replica(replica_id) => { let replicas = self.get_node_replicas(None).await?; replicas .iter() .filter(|&p| p.uuid == replica_id) .cloned() .collect() } _ => { return Err(SvcError::InvalidFilter { filter, }) } })) } #[tracing::instrument(level = "debug", err)] pub(super) async fn create_replica( &self, request: &CreateReplica, ) -> Result<Replica, SvcError> { self.registry.create_replica(&request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn destroy_replica( &self, request: &DestroyReplica, ) -> Result<(), SvcError> { self.registry.destroy_replica(&request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn share_replica( &self, request: &ShareReplica, ) -> Result<String, SvcError> { self.registry.share_replica(&request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn unshare_replica( &self, request: &UnshareReplica, ) -> Result<(), SvcError> { self.registry.unshare_replica(&request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn create_pool( &self, request: &CreatePool, ) -> Result<Pool, SvcError> { self.registry.create_pool(request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn destroy_pool( &self, request: &DestroyPool, ) -> Result<(), SvcError> { self.registry.destroy_pool(request).await } }
#![allow(clippy::unit_arg)] use super::*; use common::wrapper::v0::*; #[derive(Clone, Debug, Default)] pub(super) struct PoolSvc { registry: Registry<NodeWrapperPool>, } impl PoolSvc {
fn start(&self) { self.registry.start(); } async fn get_node_pools( &self, node_id: Option<NodeId>, ) -> Result<Vec<Pool>, SvcError> { Ok(match node_id { None => self.registry.list_pools().await, Some(node_id) => self.registry.list_node_pools(&node_id).await, }) } async fn get_node_replicas( &self, node_id: Option<NodeId>, ) -> Result<Vec<Replica>, SvcError> { Ok(match node_id { None => self.registry.list_replicas().await, Some(node_id) => self.registry.list_node_replicas(&node_id).await, }) } #[tracing::instrument(level = "debug", err)] pub(super) async fn get_pools( &self, request: &GetPools, ) -> Result<Pools, SvcError> { let filter = request.filter.clone(); Ok(Pools(match filter { Filter::None => self.get_node_pools(None).await?, Filter::Node(node_id) => self.get_node_pools(Some(node_id)).await?, Filter::NodePool(node_id, pool_id) => { let pools = self.get_node_pools(Some(node_id)).await?; pools.iter().filter(|&p| p.id == pool_id).cloned().collect() } Filter::Pool(pool_id) => { let pools = self.get_node_pools(None).await?; pools.iter().filter(|&p| p.id == pool_id).cloned().collect() } _ => { return Err(SvcError::InvalidFilter { filter, }) } })) } #[tracing::instrument(level = "debug", err)] pub(super) async fn get_replicas( &self, request: &GetReplicas, ) -> Result<Replicas, SvcError> { let filter = request.filter.clone(); Ok(Replicas(match filter { Filter::None => self.get_node_replicas(None).await?, Filter::Node(node_id) => { self.get_node_replicas(Some(node_id)).await? } Filter::NodePool(node_id, pool_id) => { let replicas = self.get_node_replicas(Some(node_id)).await?; replicas .iter() .filter(|&p| p.pool == pool_id) .cloned() .collect() } Filter::Pool(pool_id) => { let replicas = self.get_node_replicas(None).await?; replicas .iter() .filter(|&p| p.pool == pool_id) .cloned() .collect() } Filter::NodePoolReplica(node_id, pool_id, replica_id) => { let replicas = self.get_node_replicas(Some(node_id)).await?; replicas .iter() .filter(|&p| p.pool == pool_id && p.uuid == replica_id) .cloned() .collect() } Filter::NodeReplica(node_id, replica_id) => { let replicas = self.get_node_replicas(Some(node_id)).await?; replicas .iter() .filter(|&p| p.uuid == replica_id) .cloned() .collect() } Filter::PoolReplica(pool_id, replica_id) => { let replicas = self.get_node_replicas(None).await?; replicas .iter() .filter(|&p| p.pool == pool_id && p.uuid == replica_id) .cloned() .collect() } Filter::Replica(replica_id) => { let replicas = self.get_node_replicas(None).await?; replicas .iter() .filter(|&p| p.uuid == replica_id) .cloned() .collect() } _ => { return Err(SvcError::InvalidFilter { filter, }) } })) } #[tracing::instrument(level = "debug", err)] pub(super) async fn create_replica( &self, request: &CreateReplica, ) -> Result<Replica, SvcError> { self.registry.create_replica(&request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn destroy_replica( &self, request: &DestroyReplica, ) -> Result<(), SvcError> { self.registry.destroy_replica(&request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn share_replica( &self, request: &ShareReplica, ) -> Result<String, SvcError> { self.registry.share_replica(&request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn unshare_replica( &self, request: &UnshareReplica, ) -> Result<(), SvcError> { self.registry.unshare_replica(&request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn create_pool( &self, request: &CreatePool, ) -> Result<Pool, SvcError> { self.registry.create_pool(request).await } #[tracing::instrument(level = "debug", err)] pub(super) async fn destroy_pool( &self, request: &DestroyPool, ) -> Result<(), SvcError> { self.registry.destroy_pool(request).await } }
pub fn new(period: std::time::Duration) -> Self { let obj = Self { registry: Registry::new(period), }; obj.start(); obj }
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct RebuildTask {\n\n buffer: DmaBuf,\n\n sender: mpsc::Sender<TaskResult>,\n\n error: Option<TaskResult>,\n\n}\n\n\n\n/// Pool of rebuild tasks and progress tracking\n\n/// Each task uses a clone of the sender allowing the management task to poll a\n\n/// single re...
Rust
src/day24.rs
Strackeror/aoc_2021_rust
076582e489dd9ea33b9cf4846626a81f1dcbde4b
use std::{cell::RefCell, collections::HashMap}; use itertools::Itertools; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Param { Number(i64), Variable(char), } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Expr { Input(char), Add(char, Param), Mul(char, Param), Div(char, Param), Mod(char, Param), Eql(char, Param), } peg::parser! { grammar instructions_parser() for str { rule identifier() -> char = c:$(['a'..='z']) {c.as_bytes()[0] as char} rule number() -> Param = n:$("-"? ['0'..='9']+) { Param::Number(n.parse().unwrap())} rule variable() -> Param = i:identifier() { Param::Variable(i) } rule param() -> Param = number() / variable() rule input() -> Expr = "inp" " " t:identifier() {Expr::Input(t)} rule add() -> Expr = "add" " " t:identifier() " " p:param() {Expr::Add(t, p)} rule mul() -> Expr = "mul" " " t:identifier() " " p:param() {Expr::Mul(t, p)} rule div() -> Expr = "div" " " t:identifier() " " p:param() {Expr::Div(t, p)} rule modu() -> Expr = "mod" " " t:identifier() " " p:param() {Expr::Mod(t, p)} rule eql() -> Expr = "eql" " " t:identifier() " " p:param() {Expr::Eql(t, p)} rule inst() -> Expr = input() / add() / mul() / div() / modu() / eql() pub rule list() -> Vec<Expr> = l:inst() ** "\n" {l} } } fn cid(c: char) -> usize { c as usize - 'w' as usize } fn val(state: [i64; 4], p: Param) -> i64 { match p { Param::Number(n) => n, Param::Variable(c) => state[cid(c)], } } fn process_expr(expr: Expr, mut state: [i64; 4]) -> [i64; 4] { match expr { Expr::Add(c, b) => { state[cid(c)] = state[cid(c)] + val(state, b); } Expr::Mul(c, b) => { state[cid(c)] = state[cid(c)] * val(state, b); } Expr::Div(c, b) => { state[cid(c)] = state[cid(c)] / val(state, b); } Expr::Mod(c, b) => { state[cid(c)] = state[cid(c)] % val(state, b); } Expr::Eql(c, b) => { state[cid(c)] = (state[cid(c)] == val(state, b)) as _; } _ => unreachable!(), }; state } fn processr(exprs: &[Expr]) -> Option<i64> { fn cid(c: char) -> usize { c as usize - 'w' as usize } fn param(p: Param, state: &[i64]) -> i64 { match p { Param::Number(n) => n, Param::Variable(c) => state[cid(c)], } } fn recursive( idx: usize, total: i64, state: [i64; 4], exprs: &[Expr], mem: &mut HashMap<(usize, [i64; 4]), Option<i64>>, ) -> Option<i64> { if idx == exprs.len() { return if state[3] == 0 { dbg!(Some(total)) } else { None }; } if let Some(o) = mem.get(&(idx, state)) { return *o; } let mut nstate = state; let result = match exprs[idx] { Expr::Input(n) => (0..=9) .rev() .filter_map(|d| { nstate[cid(n)] = d; recursive(idx + 1, total * 10 + d, nstate, exprs, mem) }) .next(), Expr::Eql(c, p) => { nstate[cid(c)] = (nstate[cid(c)] == param(p, &nstate)) as i64; recursive(idx + 1, total, nstate, exprs, mem) } Expr::Add(c, p) => { nstate[cid(c)] = nstate[cid(c)] + param(p, &nstate); recursive(idx + 1, total, nstate, exprs, mem) } Expr::Mul(c, p) => { nstate[cid(c)] = nstate[cid(c)] * param(p, &nstate); recursive(idx + 1, total, nstate, exprs, mem) } Expr::Div(c, p) => { nstate[cid(c)] = nstate[cid(c)] / param(p, &nstate); recursive(idx + 1, total, nstate, exprs, mem) } Expr::Mod(c, p) => { nstate[cid(c)] = nstate[cid(c)] % param(p, &nstate); recursive(idx + 1, total, nstate, exprs, mem) } }; mem.insert((idx, state), result); result } recursive(0, 0, [0, 0, 0, 0], exprs, &mut HashMap::new()) } #[test] fn example1() { let parsed = instructions_parser::list(&std::fs::read_to_string("input/day24/example1.txt").unwrap()); dbg!(&parsed); processr(&parsed.unwrap()); } #[test] fn example2() { let parsed = instructions_parser::list(&std::fs::read_to_string("input/day24/example2.txt").unwrap()); dbg!(&parsed); processr(&parsed.unwrap()); } #[test] fn input() { let parsed = instructions_parser::list(&std::fs::read_to_string("input/day24/input.txt").unwrap()); dbg!(&parsed); processr(&parsed.unwrap()); }
use std::{cell::RefCell, collections::HashMap}; use itertools::Itertools; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Param { Number(i64), Variable(char), } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Expr { Input(char), Add(char, Param), Mul(char, Param), Div(char, Param), Mod(char, Param), Eql(char, Param), } peg::parser! { grammar instructions_parser() for str { rule identifier() -> char = c:$(['a'..='z']) {c.as_bytes()[0] as char} rule number() -> Param = n:$("-"? ['0'..='9']+) { Param::Number(n.parse().unwrap())} rule variable() -> Param = i:identifier() { Param::Variable(i) } rule param() -> Param = number() / variable() rule input() -> Expr = "inp" " " t:identifier() {Expr::Input(t)} rule add() -> Expr = "add" " " t:identifier() " " p:param() {Expr::Add(t, p)} rule mul() -> Expr = "mul" " " t:identifier() " " p:param() {Expr::Mul(t, p)} rule div() -> Expr = "div" " " t:identifier() " " p:param() {Expr::Div(t, p)} rule modu() -> Expr = "mod" " " t:identifier() " " p:param() {Expr::Mod(t, p)} rule eql() -> Expr = "eql" " " t:identifier() " " p:param() {Expr::Eql(t, p)} rule inst() -> Expr = input() / add() / mul() / div() / modu() / eql() pub rule list() -> Vec<Expr> = l:inst() ** "\n" {l} } } fn cid(c: char) -> usize { c as usize - 'w' as usize }
fn process_expr(expr: Expr, mut state: [i64; 4]) -> [i64; 4] { match expr { Expr::Add(c, b) => { state[cid(c)] = state[cid(c)] + val(state, b); } Expr::Mul(c, b) => { state[cid(c)] = state[cid(c)] * val(state, b); } Expr::Div(c, b) => { state[cid(c)] = state[cid(c)] / val(state, b); } Expr::Mod(c, b) => { state[cid(c)] = state[cid(c)] % val(state, b); } Expr::Eql(c, b) => { state[cid(c)] = (state[cid(c)] == val(state, b)) as _; } _ => unreachable!(), }; state } fn processr(exprs: &[Expr]) -> Option<i64> { fn cid(c: char) -> usize { c as usize - 'w' as usize } fn param(p: Param, state: &[i64]) -> i64 { match p { Param::Number(n) => n, Param::Variable(c) => state[cid(c)], } } fn recursive( idx: usize, total: i64, state: [i64; 4], exprs: &[Expr], mem: &mut HashMap<(usize, [i64; 4]), Option<i64>>, ) -> Option<i64> { if idx == exprs.len() { return if state[3] == 0 { dbg!(Some(total)) } else { None }; } if let Some(o) = mem.get(&(idx, state)) { return *o; } let mut nstate = state; let result = match exprs[idx] { Expr::Input(n) => (0..=9) .rev() .filter_map(|d| { nstate[cid(n)] = d; recursive(idx + 1, total * 10 + d, nstate, exprs, mem) }) .next(), Expr::Eql(c, p) => { nstate[cid(c)] = (nstate[cid(c)] == param(p, &nstate)) as i64; recursive(idx + 1, total, nstate, exprs, mem) } Expr::Add(c, p) => { nstate[cid(c)] = nstate[cid(c)] + param(p, &nstate); recursive(idx + 1, total, nstate, exprs, mem) } Expr::Mul(c, p) => { nstate[cid(c)] = nstate[cid(c)] * param(p, &nstate); recursive(idx + 1, total, nstate, exprs, mem) } Expr::Div(c, p) => { nstate[cid(c)] = nstate[cid(c)] / param(p, &nstate); recursive(idx + 1, total, nstate, exprs, mem) } Expr::Mod(c, p) => { nstate[cid(c)] = nstate[cid(c)] % param(p, &nstate); recursive(idx + 1, total, nstate, exprs, mem) } }; mem.insert((idx, state), result); result } recursive(0, 0, [0, 0, 0, 0], exprs, &mut HashMap::new()) } #[test] fn example1() { let parsed = instructions_parser::list(&std::fs::read_to_string("input/day24/example1.txt").unwrap()); dbg!(&parsed); processr(&parsed.unwrap()); } #[test] fn example2() { let parsed = instructions_parser::list(&std::fs::read_to_string("input/day24/example2.txt").unwrap()); dbg!(&parsed); processr(&parsed.unwrap()); } #[test] fn input() { let parsed = instructions_parser::list(&std::fs::read_to_string("input/day24/input.txt").unwrap()); dbg!(&parsed); processr(&parsed.unwrap()); }
fn val(state: [i64; 4], p: Param) -> i64 { match p { Param::Number(n) => n, Param::Variable(c) => state[cid(c)], } }
function_block-full_function
[ { "content": "pub fn run(input: &str) -> Result<()> {\n\n let (a, b) = input.split_once(',').context(\"\")?;\n\n\n\n let p1_state = PlayerState {\n\n position: a.parse::<u64>()? - 1,\n\n score: 0,\n\n rollcount: 0,\n\n };\n\n\n\n let p2_state = PlayerState {\n\n position:...
Rust
src/ir/mod.rs
playXE/rcc
7f95c3d5b14f6912f04e9ce2baeb2bc3f29990ed
mod expr; mod static_init; mod stmt; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass}; use crate::utils; use cranelift::codegen::{ self, ir::{ entities::StackSlot, function::Function, stackslot::{StackSlotData, StackSlotKind}, ExternalName, InstBuilder, MemFlags, }, settings, }; use cranelift::frontend::Switch; use cranelift::prelude::{Block, FunctionBuilder, FunctionBuilderContext, Signature}; use cranelift_module::{self, Backend, DataId, FuncId, Linkage, Module}; enum Id { Function(FuncId), Global(DataId), Local(StackSlot), } struct Compiler<T: Backend> { module: Module<T>, scope: Scope<InternedStr, Id>, debug: bool, last_saw_loop: bool, strings: HashMap<Vec<u8>, DataId>, loops: Vec<(Block, Block)>, switches: Vec<(Switch, Option<Block>, Block)>, labels: HashMap<InternedStr, Block>, error_handler: ErrorHandler, } pub(crate) fn compile<B: Backend>( module: Module<B>, program: Vec<Locatable<Declaration>>, debug: bool, ) -> (Result<Module<B>, CompileError>, VecDeque<CompileWarning>) { let mut err = None; let mut compiler = Compiler::<B>::new(module, debug); for decl in program { let current = match (decl.data.symbol.ctype.clone(), decl.data.init) { (Type::Function(func_type), None) => compiler .declare_func( decl.data.symbol.id, &func_type.signature(compiler.module.isa()), decl.data.symbol.storage_class, false, ) .map(|_| ()), (Type::Void, _) => unreachable!("parser let an incomplete type through"), (Type::Function(func_type), Some(Initializer::FunctionBody(stmts))) => compiler .compile_func( decl.data.symbol.id, func_type, decl.data.symbol.storage_class, stmts, decl.location, ), (_, Some(Initializer::FunctionBody(_))) => { unreachable!("only functions should have a function body") } (_, init) => compiler.store_static(decl.data.symbol, init, decl.location), }; if let Err(e) = current { err = Some(e); break; } } let warns = compiler.error_handler.warnings; if let Some(err) = err { (Err(err), warns) } else { (Ok(compiler.module), warns) } } impl<B: Backend> Compiler<B> { fn new(module: Module<B>, debug: bool) -> Compiler<B> { Compiler { module, scope: Scope::new(), loops: Vec::new(), switches: Vec::new(), labels: HashMap::new(), last_saw_loop: true, strings: Default::default(), error_handler: Default::default(), debug, } } fn declare_func( &mut self, id: InternedStr, signature: &Signature, sc: StorageClass, is_definition: bool, ) -> CompileResult<FuncId> { use crate::get_str; if !is_definition { if let Some(Id::Function(func_id)) = self.scope.get(&id) { return Ok(*func_id); } } let linkage = match sc { StorageClass::Auto | StorageClass::Extern if is_definition => Linkage::Export, StorageClass::Auto | StorageClass::Extern => Linkage::Import, StorageClass::Static => Linkage::Local, StorageClass::Register | StorageClass::Typedef => unreachable!(), }; let func_id = self .module .declare_function(get_str!(id), linkage, &signature) .unwrap_or_else(|err| utils::fatal(err, 6)); self.scope.insert(id, Id::Function(func_id)); Ok(func_id) } fn declare_stack( &mut self, decl: Declaration, location: Location, builder: &mut FunctionBuilder, ) -> CompileResult<()> { if let Type::Function(ftype) = decl.symbol.ctype { self.declare_func( decl.symbol.id, &ftype.signature(self.module.isa()), decl.symbol.storage_class, false, )?; return Ok(()); } let u64_size = match decl.symbol.ctype.sizeof() { Ok(size) => size, Err(err) => { return Err(CompileError::semantic(Locatable { data: err.into(), location, })) } }; let kind = StackSlotKind::ExplicitSlot; let size = match u32::try_from(u64_size) { Ok(size) => size, Err(_) => return Err(CompileError::semantic(Locatable { data: "cannot store items on the stack that are more than 4 GB, it will overflow the stack".into(), location, })) }; let data = StackSlotData { kind, size, offset: None, }; let stack_slot = builder.create_stack_slot(data); self.scope.insert(decl.symbol.id, Id::Local(stack_slot)); if let Some(init) = decl.init { self.store_stack(init, stack_slot, builder)?; } Ok(()) } fn store_stack( &mut self, init: Initializer, stack_slot: StackSlot, builder: &mut FunctionBuilder, ) -> CompileResult<()> { match init { Initializer::Scalar(expr) => { let val = self.compile_expr(*expr, builder)?; let addr = builder.ins().stack_addr(Type::ptr_type(), stack_slot, 0); builder.ins().store(MemFlags::new(), val.ir_val, addr, 0); } Initializer::InitializerList(_) => unimplemented!("aggregate dynamic initialization"), Initializer::FunctionBody(_) => unreachable!("functions can't be stored on the stack"), } Ok(()) } fn store_stack_params( &mut self, params: Vec<Symbol>, func_start: Block, location: &Location, builder: &mut FunctionBuilder, ) -> CompileResult<()> { let ir_vals: Vec<_> = params .iter() .map(|param| { let ir_type = param.ctype.as_ir_type(); Ok(builder.append_block_param(func_start, ir_type)) }) .collect::<CompileResult<_>>()?; for (param, ir_val) in params.into_iter().zip(ir_vals) { let u64_size = match param.ctype.sizeof() { Err(data) => semantic_err!(data.into(), *location), Ok(size) => size, }; let u32_size = match u32::try_from(u64_size) { Err(_) => semantic_err!( format!( "size {} is too large for stack (can only handle 32-bit values)", u64_size ), *location ), Ok(size) => size, }; let stack_data = StackSlotData { kind: StackSlotKind::ExplicitSlot, size: u32_size, offset: None, }; let slot = builder.create_stack_slot(stack_data); let addr = builder.ins().stack_addr(Type::ptr_type(), slot, 0); builder.ins().store(MemFlags::new(), ir_val, addr, 0); self.scope.insert(param.id, Id::Local(slot)); } Ok(()) } fn compile_func( &mut self, id: InternedStr, func_type: FunctionType, sc: StorageClass, stmts: Vec<Stmt>, location: Location, ) -> CompileResult<()> { let signature = func_type.signature(self.module.isa()); let func_id = self.declare_func(id.clone(), &signature, sc, true)?; self.scope.enter(); let mut func = Function::with_name_signature(ExternalName::user(0, 0), signature); let mut ctx = FunctionBuilderContext::new(); let mut builder = FunctionBuilder::new(&mut func, &mut ctx); let func_start = builder.create_block(); builder.switch_to_block(func_start); let should_ret = func_type.should_return(); if func_type.has_params() { self.store_stack_params(func_type.params, func_start, &location, &mut builder)?; } self.compile_all(stmts, &mut builder)?; if !builder.is_filled() { if id == InternedStr::get_or_intern("main") { let ir_int = func_type.return_type.as_ir_type(); let zero = [builder.ins().iconst(ir_int, 0)]; builder.ins().return_(&zero); } else if should_ret { semantic_err!( format!( "expected a return statement before end of function '{}' returning {}", id, func_type.return_type ), location ); } else { builder.ins().return_(&[]); } } self.scope.exit(); builder.seal_all_blocks(); builder.finalize(); let flags = settings::Flags::new(settings::builder()); if self.debug { println!("{}", func); } if let Err(err) = codegen::verify_function(&func, &flags) { println!("{}", func); utils::fatal(err, 3); } let mut ctx = codegen::Context::for_function(func); if let Err(err) = self.module.define_function(func_id, &mut ctx) { println!("{}", ctx.func); utils::fatal(err, 4); } Ok(()) } } impl FunctionType { fn has_params(&self) -> bool { !(self.params.len() == 1 && self.params[0].ctype == Type::Void) } }
mod expr; mod static_init; mod stmt; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass}; use crate::utils; use cranelift::codegen::{ self, ir::{ entities::StackSlot, function::Function, stackslot::{StackSlotData, StackSlotKind}, ExternalName, InstBuilder, MemFlags, }, settings, }; use cranelift::frontend::Switch; use cranelift::prelude::{Block, FunctionBuilder, FunctionBuilderContext, Signature}; use cranelift_module::{self, Backend, DataId, FuncId, Linkage, Module}; enum Id { Function(FuncId), Global(DataId), Local(StackSlot), } struct Compiler<T: Backend> { module: Module<T>, scope: Scope<InternedStr, Id>, debug: bool, last_saw_loop: bool, strings: HashMap<Vec<u8>, DataId>, loops: Vec<(Block, Block)>, switches: Vec<(Switch, Option<Block>, Block)>, labels: HashMap<InternedStr, Block>, error_handler: ErrorHandler, } pub(crate) fn compile<B: Backend>( module: Module<B>, program: Vec<Locatable<Declaration>>, debug: bool, ) -> (Result<Module<B>, CompileError>, VecDeque<CompileWarning>) { let mut err = None; let mut compiler = Compiler::<B>::new(module, debug); for decl in program { let current = match (decl.data.symbol.ctype.clone(), decl.data.init) { (Type::Function(func_type), None) => compiler .declare_func( decl.data.symbol.id, &func_type.signature(compiler.module.isa()), decl.data.symbol.storage_class, false, ) .map(|_| ()), (Type::Void, _) => unreachable!("parser let an incomplete type through"), (Type::Function(func_type), Some(Initializer::FunctionBody(stmts))) => compiler .compile_func( decl.data.symbol.id, func_type, decl.data.symbol.storage_class, stmts, decl.location, ), (_, Some(Initializer::FunctionBody(_))) => { unreachable!("only functions should have a function body") } (_, init) => compiler.store_static(decl.data.symbol, init, decl.location), }; if let Err(e) = current { err = Some(e); break; } } let warns = compiler.error_handler.warnings; if let Some(err) = err { (Err(err), warns) } else { (Ok(compiler.module), warns) } } impl<B: Backend> Compiler<B> { fn new(module: Module<B>, debug: bool) -> Compiler<B> { Compiler { module, scope: Scope::new(), loops: Vec::new(), switches: Vec::new(), labels: HashMap::new(), last_saw_loop: true, strings: Default::default(), error_handler: Default::default(), debug, } }
fn declare_stack( &mut self, decl: Declaration, location: Location, builder: &mut FunctionBuilder, ) -> CompileResult<()> { if let Type::Function(ftype) = decl.symbol.ctype { self.declare_func( decl.symbol.id, &ftype.signature(self.module.isa()), decl.symbol.storage_class, false, )?; return Ok(()); } let u64_size = match decl.symbol.ctype.sizeof() { Ok(size) => size, Err(err) => { return Err(CompileError::semantic(Locatable { data: err.into(), location, })) } }; let kind = StackSlotKind::ExplicitSlot; let size = match u32::try_from(u64_size) { Ok(size) => size, Err(_) => return Err(CompileError::semantic(Locatable { data: "cannot store items on the stack that are more than 4 GB, it will overflow the stack".into(), location, })) }; let data = StackSlotData { kind, size, offset: None, }; let stack_slot = builder.create_stack_slot(data); self.scope.insert(decl.symbol.id, Id::Local(stack_slot)); if let Some(init) = decl.init { self.store_stack(init, stack_slot, builder)?; } Ok(()) } fn store_stack( &mut self, init: Initializer, stack_slot: StackSlot, builder: &mut FunctionBuilder, ) -> CompileResult<()> { match init { Initializer::Scalar(expr) => { let val = self.compile_expr(*expr, builder)?; let addr = builder.ins().stack_addr(Type::ptr_type(), stack_slot, 0); builder.ins().store(MemFlags::new(), val.ir_val, addr, 0); } Initializer::InitializerList(_) => unimplemented!("aggregate dynamic initialization"), Initializer::FunctionBody(_) => unreachable!("functions can't be stored on the stack"), } Ok(()) } fn store_stack_params( &mut self, params: Vec<Symbol>, func_start: Block, location: &Location, builder: &mut FunctionBuilder, ) -> CompileResult<()> { let ir_vals: Vec<_> = params .iter() .map(|param| { let ir_type = param.ctype.as_ir_type(); Ok(builder.append_block_param(func_start, ir_type)) }) .collect::<CompileResult<_>>()?; for (param, ir_val) in params.into_iter().zip(ir_vals) { let u64_size = match param.ctype.sizeof() { Err(data) => semantic_err!(data.into(), *location), Ok(size) => size, }; let u32_size = match u32::try_from(u64_size) { Err(_) => semantic_err!( format!( "size {} is too large for stack (can only handle 32-bit values)", u64_size ), *location ), Ok(size) => size, }; let stack_data = StackSlotData { kind: StackSlotKind::ExplicitSlot, size: u32_size, offset: None, }; let slot = builder.create_stack_slot(stack_data); let addr = builder.ins().stack_addr(Type::ptr_type(), slot, 0); builder.ins().store(MemFlags::new(), ir_val, addr, 0); self.scope.insert(param.id, Id::Local(slot)); } Ok(()) } fn compile_func( &mut self, id: InternedStr, func_type: FunctionType, sc: StorageClass, stmts: Vec<Stmt>, location: Location, ) -> CompileResult<()> { let signature = func_type.signature(self.module.isa()); let func_id = self.declare_func(id.clone(), &signature, sc, true)?; self.scope.enter(); let mut func = Function::with_name_signature(ExternalName::user(0, 0), signature); let mut ctx = FunctionBuilderContext::new(); let mut builder = FunctionBuilder::new(&mut func, &mut ctx); let func_start = builder.create_block(); builder.switch_to_block(func_start); let should_ret = func_type.should_return(); if func_type.has_params() { self.store_stack_params(func_type.params, func_start, &location, &mut builder)?; } self.compile_all(stmts, &mut builder)?; if !builder.is_filled() { if id == InternedStr::get_or_intern("main") { let ir_int = func_type.return_type.as_ir_type(); let zero = [builder.ins().iconst(ir_int, 0)]; builder.ins().return_(&zero); } else if should_ret { semantic_err!( format!( "expected a return statement before end of function '{}' returning {}", id, func_type.return_type ), location ); } else { builder.ins().return_(&[]); } } self.scope.exit(); builder.seal_all_blocks(); builder.finalize(); let flags = settings::Flags::new(settings::builder()); if self.debug { println!("{}", func); } if let Err(err) = codegen::verify_function(&func, &flags) { println!("{}", func); utils::fatal(err, 3); } let mut ctx = codegen::Context::for_function(func); if let Err(err) = self.module.define_function(func_id, &mut ctx) { println!("{}", ctx.func); utils::fatal(err, 4); } Ok(()) } } impl FunctionType { fn has_params(&self) -> bool { !(self.params.len() == 1 && self.params[0].ctype == Type::Void) } }
fn declare_func( &mut self, id: InternedStr, signature: &Signature, sc: StorageClass, is_definition: bool, ) -> CompileResult<FuncId> { use crate::get_str; if !is_definition { if let Some(Id::Function(func_id)) = self.scope.get(&id) { return Ok(*func_id); } } let linkage = match sc { StorageClass::Auto | StorageClass::Extern if is_definition => Linkage::Export, StorageClass::Auto | StorageClass::Extern => Linkage::Import, StorageClass::Static => Linkage::Local, StorageClass::Register | StorageClass::Typedef => unreachable!(), }; let func_id = self .module .declare_function(get_str!(id), linkage, &signature) .unwrap_or_else(|err| utils::fatal(err, 6)); self.scope.insert(id, Id::Function(func_id)); Ok(func_id) }
function_block-full_function
[]
Rust
src/lib.rs
Ujang360/py-udp-loop
73bd587a64d262bc98a4d0784eb77d95a1141282
use crossbeam_queue::ArrayQueue; use pyo3::prelude::*; use pyo3::types::PyByteArray; use std::net::{SocketAddr, UdpSocket}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::{sleep, spawn as spawn_thread, JoinHandle}; use std::time::Duration; pub const LOOP_GRACE_DURATION_MS: u64 = 1; pub const MAX_PENDING_TX: usize = 128; pub const MAX_PENDING_RX: usize = 128; pub const MAX_PACKET_SIZE: usize = 1460; #[pyclass(freelist = 1024)] #[derive(Clone, Debug)] pub struct UdpPacket { pub peer: SocketAddr, pub data: Vec<u8>, } #[pymethods] impl UdpPacket { #[new] pub fn new(peer_ip_address: &str, peer_port: u16) -> Self { Self { peer: SocketAddr::new(peer_ip_address.parse().unwrap(), peer_port), data: Vec::new(), } } #[getter] pub fn get_data<'a>(&self, py: Python<'a>) -> PyResult<&'a PyByteArray> { Ok(PyByteArray::new(py, &self.data[..])) } #[setter] pub fn set_data(&mut self, raw_bytes: &PyByteArray) -> PyResult<()> { self.data = raw_bytes.to_vec(); Ok(()) } } #[pyclass] pub struct UdpLoop { stop_flag: Arc<AtomicBool>, pending_tx: Arc<ArrayQueue<UdpPacket>>, pending_rx: Arc<ArrayQueue<UdpPacket>>, loop_handle: Mutex<Option<JoinHandle<()>>>, } impl Default for UdpLoop { fn default() -> Self { Self { stop_flag: Arc::new(AtomicBool::new(false)), pending_tx: Arc::new(ArrayQueue::new(MAX_PENDING_TX)), pending_rx: Arc::new(ArrayQueue::new(MAX_PENDING_RX)), loop_handle: Mutex::new(None), } } } #[pymethods] impl UdpLoop { #[new] pub fn new() -> Self { Default::default() } pub fn try_receive(&self) -> PyResult<Option<UdpPacket>> { match self.pending_rx.pop() { Err(_) => Ok(None), Ok(packet) => Ok(Some(packet)), } } pub fn transmit(&self, packet: UdpPacket) -> PyResult<bool> { if let Err(_) = self.pending_tx.push(packet) { return Ok(false); } Ok(true) } pub fn start(&mut self, listen_address: &str, listen_port: u16) -> PyResult<bool> { let stop_flag = self.stop_flag.clone(); let pending_tx = self.pending_tx.clone(); let pending_rx = self.pending_rx.clone(); let listen_address = listen_address.to_string(); let mut loop_handle = self.loop_handle.lock().unwrap(); if loop_handle.is_some() { return Ok(false); } (*loop_handle) = Some(spawn_thread(move || { let loop_grace_duration = Duration::from_millis(LOOP_GRACE_DURATION_MS); let mut buffer_rx = [0u8; MAX_PACKET_SIZE]; let binding_socket = SocketAddr::new(listen_address.parse().unwrap(), listen_port); let udp_socket = UdpSocket::bind(binding_socket).unwrap(); udp_socket.set_nonblocking(true).unwrap(); let pending_tx = pending_tx; let pending_rx = pending_rx; while !stop_flag.load(Ordering::Relaxed) { if let Ok(new_tx_packet) = pending_tx.pop() { let _ = udp_socket.send_to(&new_tx_packet.data, new_tx_packet.peer); } match udp_socket.recv_from(&mut buffer_rx) { Err(_) => { if pending_tx.is_empty() { sleep(loop_grace_duration); } } Ok((rx_length, peer)) => { if rx_length > buffer_rx.len() { eprintln!("Received packet beyond maximum size of {}", MAX_PACKET_SIZE); } else { let new_rx_packet = UdpPacket { peer, data: (&buffer_rx[0..rx_length]).to_vec(), }; let _ = pending_rx.push(new_rx_packet); } } } } })); Ok(true) } pub fn stop(&mut self) -> PyResult<bool> { match self.loop_handle.lock().unwrap().take() { None => Ok(false), Some(loop_handle) => { self.stop_flag.store(true, Ordering::Relaxed); let _ = loop_handle.join(); Ok(true) } } } } #[pymodule] fn py_udp_loop(_: Python, m: &PyModule) -> PyResult<()> { m.add_class::<UdpPacket>()?; m.add_class::<UdpLoop>()?; Ok(()) }
use crossbeam_queue::ArrayQueue; use pyo3::prelude::*; use pyo3::types::PyByteArray; use std::net::{SocketAddr, UdpSocket}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::{sleep, spawn as spawn_thread, JoinHandle}; use std::time::Duration; pub const LOOP_GRACE_DURATION_MS: u64 = 1; pub const MAX_PENDING_TX: usize = 128; pub const MAX_PENDING_RX: usize = 128; pub const MAX_PACKET_SIZE: usize = 1460; #[pyclass(freelist = 1024)] #[derive(Clone, Debug)] pub struct UdpPacket { pub peer: SocketAddr, pub data: Vec<u8>, } #[pymethods] impl UdpPacket { #[new] pub fn new(peer_ip_address: &str, peer_port: u16) -> Self { Self { peer: SocketAddr::new(peer_ip_address.parse().unwrap(), peer_port), data: Vec::new(), } } #[getter] pub fn get_data<'a>(&self, py: Python<'a>) -> PyResult<&'a PyByteArray> { Ok(PyByteArray::new(py, &self.data[..])) } #[setter] pub fn set_data(&mut self, raw_bytes: &PyByteArray) -> PyResult<()> { self.data = raw_bytes.to_vec(); Ok(()) } } #[pyclass] pub struct UdpLoop { stop_flag: Arc<AtomicBool>, pending_tx: Arc<ArrayQueue<UdpPacket>>, pending_rx: Arc<ArrayQueue<UdpPacket>>, loop_handle: Mutex<Option<JoinHandle<()>>>, } impl Default for UdpLoop { fn default() -> Self { Self { stop_flag: Arc::new(AtomicBool::new(false)), pending_tx: Arc::new(ArrayQueue::new(MAX_PENDING_TX)), pending_rx: Arc::new(ArrayQueue::new(MAX_PENDING_RX)), loop_handle: Mutex::new(None), } } } #[pymethods] impl UdpLoop { #[new] pub fn new() -> Self { Default::default() } pub fn try_receive(&self) -> PyResult<Option<UdpPacket>> { match self.pending_rx.pop() { Err(_) => Ok(None), Ok(packet) => Ok(Some(packet)), } } pub fn transmit(&self, packet: UdpPacket) -> PyResult<bool> { if let Err(_) = self.pending_tx.push(packet) { return Ok(false); } Ok(true) } pub fn start(&mut self, listen_address: &str, listen_port: u16) -> PyResult<bool> { let stop_flag = self.stop_flag.clone(); let pending_tx = self.pending_tx.clone(); let pending_rx = self.pending_rx.clone(); let listen_address = listen_address.to_string(); let mut loop_handle = self.loop_handle.lock().unwrap(); if loop_handle.is_some() { return Ok(false); } (*loop_handle) =
; Ok(true) } pub fn stop(&mut self) -> PyResult<bool> { match self.loop_handle.lock().unwrap().take() { None => Ok(false), Some(loop_handle) => { self.stop_flag.store(true, Ordering::Relaxed); let _ = loop_handle.join(); Ok(true) } } } } #[pymodule] fn py_udp_loop(_: Python, m: &PyModule) -> PyResult<()> { m.add_class::<UdpPacket>()?; m.add_class::<UdpLoop>()?; Ok(()) }
Some(spawn_thread(move || { let loop_grace_duration = Duration::from_millis(LOOP_GRACE_DURATION_MS); let mut buffer_rx = [0u8; MAX_PACKET_SIZE]; let binding_socket = SocketAddr::new(listen_address.parse().unwrap(), listen_port); let udp_socket = UdpSocket::bind(binding_socket).unwrap(); udp_socket.set_nonblocking(true).unwrap(); let pending_tx = pending_tx; let pending_rx = pending_rx; while !stop_flag.load(Ordering::Relaxed) { if let Ok(new_tx_packet) = pending_tx.pop() { let _ = udp_socket.send_to(&new_tx_packet.data, new_tx_packet.peer); } match udp_socket.recv_from(&mut buffer_rx) { Err(_) => { if pending_tx.is_empty() { sleep(loop_grace_duration); } } Ok((rx_length, peer)) => { if rx_length > buffer_rx.len() { eprintln!("Received packet beyond maximum size of {}", MAX_PACKET_SIZE); } else { let new_rx_packet = UdpPacket { peer, data: (&buffer_rx[0..rx_length]).to_vec(), }; let _ = pending_rx.push(new_rx_packet); } } } } }))
call_expression
[]
Rust
machine_manager/src/config/machine_config.rs
ican2002/stratorvirt
b8e9b675ae0fac9e359a2096cc818f92c4f11c30
extern crate serde; extern crate serde_json; use std::str::FromStr; use serde::{Deserialize, Serialize}; use super::errors::{ErrorKind, Result, ResultExt}; use crate::config::{CmdParser, ConfigCheck, ExBool, VmConfig}; const DEFAULT_CPUS: u8 = 1; const DEFAULT_MEMSIZE: u64 = 256; const MAX_NR_CPUS: u64 = 254; const MIN_NR_CPUS: u64 = 1; const MAX_MEMSIZE: u64 = 549_755_813_888; const MIN_MEMSIZE: u64 = 268_435_456; const M: u64 = 1024 * 1024; const G: u64 = 1024 * 1024 * 1024; #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)] pub enum MachineType { None, MicroVm, StandardVm, } impl FromStr for MachineType { type Err = (); fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { match s.to_lowercase().as_str() { "none" => Ok(MachineType::None), "microvm" => Ok(MachineType::MicroVm), #[cfg(target_arch = "x86_64")] "q35" => Ok(MachineType::StandardVm), #[cfg(target_arch = "aarch64")] "virt" => Ok(MachineType::StandardVm), _ => Err(()), } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MachineMemConfig { pub mem_size: u64, pub mem_path: Option<String>, pub dump_guest_core: bool, pub mem_share: bool, } impl Default for MachineMemConfig { fn default() -> Self { MachineMemConfig { mem_size: DEFAULT_MEMSIZE * M, mem_path: None, dump_guest_core: true, mem_share: false, } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MachineConfig { pub mach_type: MachineType, pub nr_cpus: u8, pub mem_config: MachineMemConfig, } impl Default for MachineConfig { fn default() -> Self { MachineConfig { mach_type: MachineType::MicroVm, nr_cpus: DEFAULT_CPUS, mem_config: MachineMemConfig::default(), } } } impl ConfigCheck for MachineConfig { fn check(&self) -> Result<()> { if self.mem_config.mem_size < MIN_MEMSIZE || self.mem_config.mem_size > MAX_MEMSIZE { bail!("Memory size must >= 256MiB and <= 512GiB, default unit: MiB, current memory size: {:?} bytes", &self.mem_config.mem_size); } Ok(()) } } impl VmConfig { pub fn add_machine(&mut self, mach_config: &str) -> Result<()> { let mut cmd_parser = CmdParser::new("machine"); cmd_parser .push("") .push("type") .push("accel") .push("usb") .push("dump-guest-core") .push("mem-share"); #[cfg(target_arch = "aarch64")] cmd_parser.push("gic-version"); cmd_parser.parse(mach_config)?; #[cfg(target_arch = "aarch64")] if let Some(gic_version) = cmd_parser.get_value::<u8>("gic-version")? { if gic_version != 3 { bail!("Unsupported gic version, only gicv3 is supported"); } } if let Some(accel) = cmd_parser.get_value::<String>("accel")? { if accel.ne("kvm:tcg") && accel.ne("tcg") && accel.ne("kvm") { bail!("Only \'kvm\', \'kvm:tcg\' and \'tcg\' are supported for \'accel\' of \'machine\'"); } } if let Some(usb) = cmd_parser.get_value::<ExBool>("usb")? { if usb.into() { bail!("Argument \'usb\' should be set to \'off\'"); } } if let Some(mach_type) = cmd_parser .get_value::<MachineType>("") .chain_err(|| "Unrecognized machine type")? { self.machine_config.mach_type = mach_type; } if let Some(mach_type) = cmd_parser .get_value::<MachineType>("type") .chain_err(|| "Unrecognized machine type")? { self.machine_config.mach_type = mach_type; } if let Some(dump_guest) = cmd_parser.get_value::<ExBool>("dump-guest-core")? { self.machine_config.mem_config.dump_guest_core = dump_guest.into(); } if let Some(mem_share) = cmd_parser.get_value::<ExBool>("mem-share")? { self.machine_config.mem_config.mem_share = mem_share.into(); } Ok(()) } pub fn add_memory(&mut self, mem_config: &str) -> Result<()> { let mut cmd_parser = CmdParser::new("m"); cmd_parser.push("").push("size"); cmd_parser.parse(mem_config)?; let mem = if let Some(mem_size) = cmd_parser.get_value::<String>("")? { memory_unit_conversion(&mem_size)? } else if let Some(mem_size) = cmd_parser.get_value::<String>("size")? { memory_unit_conversion(&mem_size)? } else { return Err(ErrorKind::FieldIsMissing("size", "memory").into()); }; self.machine_config.mem_config.mem_size = mem; Ok(()) } pub fn add_cpu(&mut self, cpu_config: &str) -> Result<()> { let mut cmd_parser = CmdParser::new("smp"); cmd_parser .push("") .push("sockets") .push("cores") .push("threads") .push("cpus"); cmd_parser.parse(cpu_config)?; let cpu = if let Some(cpu) = cmd_parser.get_value::<u64>("")? { cpu } else if let Some(cpu) = cmd_parser.get_value::<u64>("cpus")? { cpu } else { return Err(ErrorKind::FieldIsMissing("cpus", "smp").into()); }; if let Some(sockets) = cmd_parser.get_value::<u64>("sockets")? { if sockets.ne(&cpu) { bail!("Invalid \'sockets\' arguments for \'smp\', it should equal to the number of cpus"); } } if let Some(cores) = cmd_parser.get_value::<u64>("cores")? { if cores.ne(&1) { bail!("Invalid \'cores\' arguments for \'smp\', it should be \'1\'"); } } if let Some(threads) = cmd_parser.get_value::<u64>("threads")? { if threads.ne(&1) { bail!("Invalid \'threads\' arguments for \'smp\', it should be \'1\'"); } } if !(MIN_NR_CPUS..=MAX_NR_CPUS).contains(&cpu) { return Err(ErrorKind::IllegalValue( "CPU number".to_string(), MIN_NR_CPUS, true, MAX_NR_CPUS, true, ) .into()); } self.machine_config.nr_cpus = cpu as u8; Ok(()) } pub fn add_mem_path(&mut self, mem_path: &str) -> Result<()> { self.machine_config.mem_config.mem_path = Some(mem_path.replace("\"", "")); Ok(()) } } fn memory_unit_conversion(origin_value: &str) -> Result<u64> { if (origin_value.ends_with('M') | origin_value.ends_with('m')) && (origin_value.contains('M') ^ origin_value.contains('m')) { let value = origin_value.replacen("M", "", 1); let value = value.replacen("m", "", 1); get_inner( value .parse::<u64>() .map_err(|_| { ErrorKind::ConvertValueFailed(origin_value.to_string(), String::from("u64")) })? .checked_mul(M), ) } else if (origin_value.ends_with('G') | origin_value.ends_with('g')) && (origin_value.contains('G') ^ origin_value.contains('g')) { let value = origin_value.replacen("G", "", 1); let value = value.replacen("g", "", 1); get_inner( value .parse::<u64>() .map_err(|_| { ErrorKind::ConvertValueFailed(origin_value.to_string(), String::from("u64")) })? .checked_mul(G), ) } else { let size = origin_value.parse::<u64>().map_err(|_| { ErrorKind::ConvertValueFailed(origin_value.to_string(), String::from("u64")) })?; let memory_size = size.checked_mul(M); get_inner(memory_size) } } fn get_inner<T>(outer: Option<T>) -> Result<T> { if let Some(x) = outer { Ok(x) } else { Err(ErrorKind::IntegerOverflow("-m".to_string()).into()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_health_check() { let memory_config = MachineMemConfig { mem_size: MIN_MEMSIZE, mem_path: None, mem_share: false, dump_guest_core: false, }; let mut machine_config = MachineConfig { mach_type: MachineType::MicroVm, nr_cpus: MIN_NR_CPUS as u8, mem_config: memory_config, }; assert!(machine_config.check().is_ok()); machine_config.nr_cpus = MAX_NR_CPUS as u8; machine_config.mem_config.mem_size = MAX_MEMSIZE; assert!(machine_config.check().is_ok()); machine_config.nr_cpus = MIN_NR_CPUS as u8; machine_config.mem_config.mem_size = MIN_MEMSIZE - 1; assert!(!machine_config.check().is_ok()); machine_config.mem_config.mem_size = MAX_MEMSIZE + 1; assert!(!machine_config.check().is_ok()); machine_config.mem_config.mem_size = MIN_MEMSIZE; assert!(machine_config.check().is_ok()); } }
extern crate serde; extern crate serde_json; use std::str::FromStr; use serde::{Deserialize, Serialize}; use super::errors::{ErrorKind, Result, ResultExt}; use crate::config::{CmdParser, ConfigCheck, ExBool, VmConfig}; const DEFAULT_CPUS: u8 = 1; const DEFAULT_MEMSIZE: u64 = 256; const MAX_NR_CPUS: u64 = 254; const MIN_NR_CPUS: u64 = 1; const MAX_MEMSIZE: u64 = 549_755_813_888; const MIN_MEMSIZE: u64 = 268_435_456; const M: u64 = 1024 * 1024; const G: u64 = 1024 * 1024 * 1024; #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)] pub enum MachineType { None, MicroVm, StandardVm, } impl FromStr for MachineType { type Err = (); fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { match s.to_lowercase().as_str() { "none" => Ok(MachineType::None), "microvm" => Ok(MachineType::MicroVm), #[cfg(target_arch = "x86_64")] "q35" => Ok(MachineType::StandardVm), #[cfg(target_arch = "aarch64")] "virt" => Ok(MachineType::StandardVm), _ => Err(()), } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MachineMemConfig { pub mem_size: u64, pub mem_path: Option<String>, pub dump_guest_core: bool, pub mem_share: bool, } impl Default for MachineMemConfig { fn default() -> Self { MachineMemConfig { mem_size: DEFAULT_MEMSIZE * M, mem_path: None, dump_guest_core: true, mem_share: false, } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MachineConfig { pub mach_type: MachineType, pub nr_cpus: u8, pub mem_config: MachineMemConfig, } impl Default for MachineConfig { fn default() -> Self { MachineConfig { mach_type: MachineType::MicroVm, nr_cpus: DEFAULT_CPUS, mem_config: MachineMemConfig::default(), } } } impl ConfigCheck for MachineConfig { fn check(&self) -> Result<()> { if self.mem_config.mem_size < MIN_MEMSIZE || self.mem_config.mem_size > MAX_MEMSIZE { bail!("Memory size must >= 256MiB and <= 512GiB, default unit: MiB, current memory size: {:?} bytes", &self.mem_config.mem_size); } Ok(()) } } impl VmConfig { pub fn add_machine(&mut self, mach_config: &str) -> Result<()> { let mut cmd_parser = CmdParser::new("machine"); cmd_parser .push("") .push("type") .push("accel") .push("usb") .push("dump-guest-core") .push("mem-share"); #[cfg(target_arch = "aarch64")] cmd_parser.push("gic-version"); cmd_parser.parse(mach_config)?; #[cfg(target_arch = "aarch64")] if let Some(gic_version) = cmd_parser.get_value::<u8>("gic-version")? { if gic_version != 3 { bail!("Unsupported gic version, only gicv3 is supported"); } } if let Some(accel) = cmd_parser.get_value::<String>("accel")? { if accel.ne("kvm:tcg") && accel.ne("tcg") && accel.ne("kvm") { bail!("Only \'kvm\', \'kvm:tcg\' and \'tcg\' are supported for \'accel\' of \'machine\'"); } } if let Some(usb) = cmd_parser.get_value::<ExBool>("usb")? { if usb.into() { bail!("Argument \'usb\' should be set to \'off\'"); } } if let Some(mach_type) = cmd_parser .get_value::<MachineType>("") .chain_err(|| "Unrecognized machine type")? { self.machine_config.mach_type = mach_type; } if let Some(mach_type) = cmd_parser .get_value::<MachineType>("type") .chain_err(|| "Unrecognized machine type")? { self.machine_config.mach_type = mach_type; } if let Some(dump_guest) = cmd_parser.get_value::<ExBool>("dump-guest-core")? { self.machine_config.mem_config.dump_guest_core = dump_guest.into(); } if let Some(mem_share) = cmd_parser.get_value::<ExBool>("mem-share")? { self.machine_config.mem_config.mem_share = mem_share.into(); } Ok(()) } pub fn add_memory(&mut self, mem_config: &str) -> Result<()> { let mut cmd_parser = CmdParser::new("m"); cmd_parser.push("").push("size"); cmd_parser.parse(mem_config)?; let mem = if let Some(mem_size) = cmd_parser.get_value::<String>("")? { memory_unit_conversion(&mem_size)? } else if let Some(mem_size) = cmd_parser.get_value::<String>("size")? { memory_unit_conversion(&mem_size)? } else { return Err(ErrorKind::FieldIsMissing("size", "memory").into()); }; self.machine_config.mem_config.mem_size = mem; Ok(()) } pub fn add_cpu(&mut self, cpu_config: &str) -> Result<()> { let mut cmd_parser = CmdParser::new("smp"); cmd_parser .push("") .push("sockets") .push("cores") .push("threads") .push("cpus"); cmd_parser.parse(cpu_config)?; let cpu = if let Some(cpu) = cmd_parser.get_value::<u64>("")? { cpu } else if let Some(cpu) = cmd_parser.get_value::<u64>("cpus")? { cpu } else { return Err(ErrorKind::FieldIsMissing("cpus", "smp").into()); }; if let Some(sockets) = cmd_parser.get_value::<u64>("sockets")? { if sockets.ne(&cpu) { bail!("Invalid \'sockets\' arguments for \'smp\', it should equal to the number of cpus"); } } if let Some(cores) = cmd_parser.get_value::<u64>("cores")? { if cores.ne(&1) { bail!("Invalid \'cores\' arguments for \'smp\', it should be \'1\'"); } } if let Some(threads) = cmd_parser.get_value::<u64>("threads")? { if threads.ne(&1) { bail!("Invalid \'threads\' arguments for \'smp\', it should be \'1\'"); } } if !(MIN_NR_CPUS..=MAX_NR_CPUS).contains(&cpu) { return Err(ErrorKind::IllegalValue( "CPU number".to_string(), MIN_NR_CPUS, true, MAX_NR_CPUS, true, ) .into()); } self.machine_config.nr_cpus = cpu as u8; Ok(()) } pub fn add_mem_path(&mut self, mem_path: &str) -> Result<()> { self.machine_config.mem_config.mem_path = Some(mem_path.replace("\"", "")); Ok(()) } } fn memory_unit_conversion(origin_value: &str) -> Result<u64> { if (origin_value.ends_with('M') | origin_value.ends_with('m')) && (origin_value.contains('M') ^ origin_value.contains('m')) { let value = origin_value.replacen("M", "", 1); let value = value.replacen("m", "", 1);
} else if (origin_value.ends_with('G') | origin_value.ends_with('g')) && (origin_value.contains('G') ^ origin_value.contains('g')) { let value = origin_value.replacen("G", "", 1); let value = value.replacen("g", "", 1); get_inner( value .parse::<u64>() .map_err(|_| { ErrorKind::ConvertValueFailed(origin_value.to_string(), String::from("u64")) })? .checked_mul(G), ) } else { let size = origin_value.parse::<u64>().map_err(|_| { ErrorKind::ConvertValueFailed(origin_value.to_string(), String::from("u64")) })?; let memory_size = size.checked_mul(M); get_inner(memory_size) } } fn get_inner<T>(outer: Option<T>) -> Result<T> { if let Some(x) = outer { Ok(x) } else { Err(ErrorKind::IntegerOverflow("-m".to_string()).into()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_health_check() { let memory_config = MachineMemConfig { mem_size: MIN_MEMSIZE, mem_path: None, mem_share: false, dump_guest_core: false, }; let mut machine_config = MachineConfig { mach_type: MachineType::MicroVm, nr_cpus: MIN_NR_CPUS as u8, mem_config: memory_config, }; assert!(machine_config.check().is_ok()); machine_config.nr_cpus = MAX_NR_CPUS as u8; machine_config.mem_config.mem_size = MAX_MEMSIZE; assert!(machine_config.check().is_ok()); machine_config.nr_cpus = MIN_NR_CPUS as u8; machine_config.mem_config.mem_size = MIN_MEMSIZE - 1; assert!(!machine_config.check().is_ok()); machine_config.mem_config.mem_size = MAX_MEMSIZE + 1; assert!(!machine_config.check().is_ok()); machine_config.mem_config.mem_size = MIN_MEMSIZE; assert!(machine_config.check().is_ok()); } }
get_inner( value .parse::<u64>() .map_err(|_| { ErrorKind::ConvertValueFailed(origin_value.to_string(), String::from("u64")) })? .checked_mul(M), )
call_expression
[ { "content": "/// Sets the value of one register for this vCPU.\n\n///\n\n/// The id of the register is encoded as specified in the kernel documentation\n\n/// for `KVM_SET_ONE_REG`.\n\n///\n\n/// Max register size is 256 Bytes.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `reg_id` - ID of the register for which w...
Rust
npk/src/dm_verity.rs
AmoghAJ/northstar
06e087df238bd9fc45026ecaf48e2642266ac7c5
use rand::RngCore; use sha2::{Digest, Sha256}; use std::{ fs::{File, OpenOptions}, io::{BufReader, Read, Seek, SeekFrom::Start, Write}, path::Path, }; use thiserror::Error; use uuid::Uuid; pub const SHA256_SIZE: usize = 32; pub const BLOCK_SIZE: usize = 4096; pub type Sha256Digest = [u8; SHA256_SIZE]; pub type Salt = Sha256Digest; #[derive(Error, Debug)] pub enum Error { #[error("Error generating hash tree: {0}")] HashTree(String), #[error("Error creating valid uuid")] Uuid, #[error("OS error: {context}")] Os { context: String, #[source] error: std::io::Error, }, } pub fn append_dm_verity_block(fsimg_path: &Path, fsimg_size: u64) -> Result<Sha256Digest, Error> { let (level_offsets, tree_size) = calc_hash_tree_level_offsets(fsimg_size as usize, BLOCK_SIZE, SHA256_SIZE as usize); let (salt, root_hash, hash_tree) = gen_hash_tree(&fsimg_path, fsimg_size, &level_offsets, tree_size)?; append_superblock_and_hashtree(&fsimg_path, fsimg_size, &salt, &hash_tree)?; Ok(root_hash) } fn gen_salt() -> Salt { let mut salt: Salt = [0u8; SHA256_SIZE]; rand::thread_rng().fill_bytes(&mut salt); salt } fn calc_hash_tree_level_offsets( image_size: usize, block_size: usize, digest_size: usize, ) -> (Vec<usize>, usize) { let mut level_offsets: Vec<usize> = vec![]; let mut level_sizes: Vec<usize> = vec![]; let mut tree_size = 0; let mut num_levels = 0; let mut rem_size = image_size; while rem_size > block_size { let num_blocks = (rem_size + block_size - 1) / block_size; let level_size = round_up_to_multiple(num_blocks * digest_size, block_size); level_sizes.push(level_size); tree_size += level_size; num_levels += 1; rem_size = level_size; } for n in 0..num_levels { let mut offset = 0; #[allow(clippy::needless_range_loop)] for m in (n + 1)..num_levels { offset += level_sizes[m]; } level_offsets.push(offset); } (level_offsets, tree_size) } fn gen_hash_tree( fsimg_path: &Path, image_size: u64, level_offsets: &[usize], tree_size: usize, ) -> Result<(Salt, Sha256Digest, Vec<u8>), Error> { let image = &File::open(&fsimg_path).map_err(|e| Error::Os { context: format!("Cannot open '{}'", &fsimg_path.display()), error: e, })?; let mut hashes: Vec<[u8; SHA256_SIZE]> = vec![]; let mut level_num = 0; let mut level_size = image_size; let mut hash_tree = vec![0_u8; tree_size]; if image_size % BLOCK_SIZE as u64 != 0 { return Err(Error::HashTree(format!("Failed to generate verity has tree. The image size {} is not a multiple of the block size {}", image_size, BLOCK_SIZE) )); } let salt = gen_salt(); loop { hashes.clear(); let mut rem_size = level_size; while rem_size > 0 { let mut sha256 = Sha256::new(); sha256.update(salt); if level_num == 0 { let offset = level_size - rem_size; let mut data = vec![0_u8; BLOCK_SIZE]; let mut image_reader = BufReader::new(image); image_reader.seek(Start(offset)).map_err(|e| Error::Os { context: format!("Failed to seek in file {}", &fsimg_path.display()), error: e, })?; image_reader.read_exact(&mut data).map_err(|e| Error::Os { context: "Failed to read from fs-image".to_string(), error: e, })?; sha256.update(&data); } else { let offset = level_offsets[level_num - 1] + level_size as usize - rem_size as usize; sha256.update(&hash_tree[offset..offset + BLOCK_SIZE]); } rem_size -= BLOCK_SIZE as u64; hashes.push(sha256.finalize().into()); } if hashes.len() == 1 { break; } let mut level = hashes.iter().flat_map(|s| s.iter().copied()).collect(); pad_to_block_size(&mut level); let offset = level_offsets[level_num]; hash_tree[offset..offset + level.len()].copy_from_slice(level.as_slice()); level_size = level.len() as u64; level_num += 1; } let root_hash = hashes[0]; Ok((salt, root_hash, hash_tree)) } fn append_superblock_and_hashtree( fsimg_path: &Path, fsimg_size: u64, salt: &Salt, hash_tree: &[u8], ) -> Result<(), Error> { let uuid = Uuid::new_v4(); assert_eq!(fsimg_size % BLOCK_SIZE as u64, 0); let data_blocks = fsimg_size / BLOCK_SIZE as u64; let mut fsimg = OpenOptions::new() .write(true) .append(true) .open(&fsimg_path) .map_err(|e| Error::Os { context: format!("Cannot open '{}'", &fsimg_path.display()), error: e, })?; const VERITY_SIGNATURE: &[u8; 8] = b"verity\x00\x00"; const HASH_ALG_NAME: &[u8; 6] = b"sha256"; let mut raw_sb: Vec<u8> = vec![]; raw_sb.extend(VERITY_SIGNATURE); raw_sb.extend(&1_u32.to_ne_bytes()); raw_sb.extend(&1_u32.to_ne_bytes()); raw_sb.extend(&hex::decode(uuid.to_string().replace("-", "")).map_err(|_e| Error::Uuid)?); raw_sb.extend(HASH_ALG_NAME); raw_sb.extend(&[0_u8; 26]); raw_sb.extend(&(BLOCK_SIZE as u32).to_ne_bytes()); raw_sb.extend(&(BLOCK_SIZE as u32).to_ne_bytes()); raw_sb.extend(&data_blocks.to_ne_bytes()); raw_sb.extend(&(SHA256_SIZE as u16).to_ne_bytes()); raw_sb.extend(&[0_u8; 6]); raw_sb.extend(salt); raw_sb.extend(&vec![0_u8; 256 - salt.len()]); || -> Result<(), std::io::Error> { fsimg.write_all(&raw_sb)?; fsimg.write_all(vec![0u8; BLOCK_SIZE - raw_sb.len()].as_slice())?; fsimg.write_all(&hash_tree) }() .map_err(|e| Error::Os { context: "Failed to write to fs-image".to_string(), error: e, })?; Ok(()) } fn pad_to_block_size(data: &mut Vec<u8>) { let pad_size = round_up_to_multiple(data.len(), BLOCK_SIZE) - data.len(); data.append(&mut vec![0_u8; pad_size]); } fn round_up_to_multiple(number: usize, multiple: usize) -> usize { number + ((multiple - (number % multiple)) % multiple) }
use rand::RngCore; use sha2::{Digest, Sha256}; use std::{ fs::{File, OpenOptions}, io::{BufReader, Read, Seek, SeekFrom::Start, Write}, path::Path, }; use thiserror::Error; use uuid::Uuid; pub const SHA256_SIZE: usize = 32; pub const BLOCK_SIZE: usize = 4096; pub type Sha256Digest = [u8; SHA256_SIZE]; pub type Salt = Sha256Digest; #[derive(Error, Debug)] pub enum Error { #[error("Error generating hash tree: {0}")] HashTree(String), #[error("Error creating valid uuid")] Uuid, #[error("OS error: {context}")] Os { context: String, #[source] error: std::io::Error, }, } pub fn append_dm_verity_block(fsimg_path: &Path, fsimg_size: u64) -> Result<Sha256Digest, Error> { let (level_offsets, tree_size) = calc_hash_tree_level_offsets(fsimg_size as usize, BLOCK_SIZE, SHA256_SIZE as usize); let (salt, root_hash, hash_tree) = gen_hash_tree(&fsimg_path, fsimg_size, &level_offsets, tree_size)?; append_superblock_and_hashtree(&fsimg_path, fsimg_size, &salt, &hash_tree)?; Ok(root_hash) } fn gen_salt() -> Salt { let mut salt: Salt = [0u8; SHA256_SIZE]; rand::thread_rng().fill_bytes(&mut salt); salt }
fn gen_hash_tree( fsimg_path: &Path, image_size: u64, level_offsets: &[usize], tree_size: usize, ) -> Result<(Salt, Sha256Digest, Vec<u8>), Error> { let image = &File::open(&fsimg_path).map_err(|e| Error::Os { context: format!("Cannot open '{}'", &fsimg_path.display()), error: e, })?; let mut hashes: Vec<[u8; SHA256_SIZE]> = vec![]; let mut level_num = 0; let mut level_size = image_size; let mut hash_tree = vec![0_u8; tree_size]; if image_size % BLOCK_SIZE as u64 != 0 { return Err(Error::HashTree(format!("Failed to generate verity has tree. The image size {} is not a multiple of the block size {}", image_size, BLOCK_SIZE) )); } let salt = gen_salt(); loop { hashes.clear(); let mut rem_size = level_size; while rem_size > 0 { let mut sha256 = Sha256::new(); sha256.update(salt); if level_num == 0 { let offset = level_size - rem_size; let mut data = vec![0_u8; BLOCK_SIZE]; let mut image_reader = BufReader::new(image); image_reader.seek(Start(offset)).map_err(|e| Error::Os { context: format!("Failed to seek in file {}", &fsimg_path.display()), error: e, })?; image_reader.read_exact(&mut data).map_err(|e| Error::Os { context: "Failed to read from fs-image".to_string(), error: e, })?; sha256.update(&data); } else { let offset = level_offsets[level_num - 1] + level_size as usize - rem_size as usize; sha256.update(&hash_tree[offset..offset + BLOCK_SIZE]); } rem_size -= BLOCK_SIZE as u64; hashes.push(sha256.finalize().into()); } if hashes.len() == 1 { break; } let mut level = hashes.iter().flat_map(|s| s.iter().copied()).collect(); pad_to_block_size(&mut level); let offset = level_offsets[level_num]; hash_tree[offset..offset + level.len()].copy_from_slice(level.as_slice()); level_size = level.len() as u64; level_num += 1; } let root_hash = hashes[0]; Ok((salt, root_hash, hash_tree)) } fn append_superblock_and_hashtree( fsimg_path: &Path, fsimg_size: u64, salt: &Salt, hash_tree: &[u8], ) -> Result<(), Error> { let uuid = Uuid::new_v4(); assert_eq!(fsimg_size % BLOCK_SIZE as u64, 0); let data_blocks = fsimg_size / BLOCK_SIZE as u64; let mut fsimg = OpenOptions::new() .write(true) .append(true) .open(&fsimg_path) .map_err(|e| Error::Os { context: format!("Cannot open '{}'", &fsimg_path.display()), error: e, })?; const VERITY_SIGNATURE: &[u8; 8] = b"verity\x00\x00"; const HASH_ALG_NAME: &[u8; 6] = b"sha256"; let mut raw_sb: Vec<u8> = vec![]; raw_sb.extend(VERITY_SIGNATURE); raw_sb.extend(&1_u32.to_ne_bytes()); raw_sb.extend(&1_u32.to_ne_bytes()); raw_sb.extend(&hex::decode(uuid.to_string().replace("-", "")).map_err(|_e| Error::Uuid)?); raw_sb.extend(HASH_ALG_NAME); raw_sb.extend(&[0_u8; 26]); raw_sb.extend(&(BLOCK_SIZE as u32).to_ne_bytes()); raw_sb.extend(&(BLOCK_SIZE as u32).to_ne_bytes()); raw_sb.extend(&data_blocks.to_ne_bytes()); raw_sb.extend(&(SHA256_SIZE as u16).to_ne_bytes()); raw_sb.extend(&[0_u8; 6]); raw_sb.extend(salt); raw_sb.extend(&vec![0_u8; 256 - salt.len()]); || -> Result<(), std::io::Error> { fsimg.write_all(&raw_sb)?; fsimg.write_all(vec![0u8; BLOCK_SIZE - raw_sb.len()].as_slice())?; fsimg.write_all(&hash_tree) }() .map_err(|e| Error::Os { context: "Failed to write to fs-image".to_string(), error: e, })?; Ok(()) } fn pad_to_block_size(data: &mut Vec<u8>) { let pad_size = round_up_to_multiple(data.len(), BLOCK_SIZE) - data.len(); data.append(&mut vec![0_u8; pad_size]); } fn round_up_to_multiple(number: usize, multiple: usize) -> usize { number + ((multiple - (number % multiple)) % multiple) }
fn calc_hash_tree_level_offsets( image_size: usize, block_size: usize, digest_size: usize, ) -> (Vec<usize>, usize) { let mut level_offsets: Vec<usize> = vec![]; let mut level_sizes: Vec<usize> = vec![]; let mut tree_size = 0; let mut num_levels = 0; let mut rem_size = image_size; while rem_size > block_size { let num_blocks = (rem_size + block_size - 1) / block_size; let level_size = round_up_to_multiple(num_blocks * digest_size, block_size); level_sizes.push(level_size); tree_size += level_size; num_levels += 1; rem_size = level_size; } for n in 0..num_levels { let mut offset = 0; #[allow(clippy::needless_range_loop)] for m in (n + 1)..num_levels { offset += level_sizes[m]; } level_offsets.push(offset); } (level_offsets, tree_size) }
function_block-full_function
[ { "content": "fn create_squashfs(out: &Path, src: &Path, pseudo_dirs: &[(String, u32)]) -> Result<(), Error> {\n\n #[cfg(target_os = \"linux\")]\n\n let compression_alg = \"gzip\";\n\n #[cfg(not(target_os = \"linux\"))]\n\n let compression_alg = \"zstd\";\n\n\n\n if which::which(&MKSQUASHFS_BIN)....
Rust
src/dovi/general_read_write.rs
amsokol/dovi_tool
458aadecf266575f199814a0479deb2dbe0fc95c
use std::io::{stdout, BufRead, BufReader, BufWriter, Write}; use std::path::PathBuf; use std::{fs::File, path::Path}; use anyhow::{bail, Result}; use indicatif::ProgressBar; use hevc_parser::hevc::{NALUnit, NAL_SEI_PREFIX, NAL_UNSPEC62, NAL_UNSPEC63}; use hevc_parser::io::{processor, IoFormat, IoProcessor}; use hevc_parser::{HevcParser, NALUStartCode}; use processor::{HevcProcessor, HevcProcessorOpts}; use super::{convert_encoded_from_opts, is_st2094_40_sei, CliOptions}; pub struct DoviProcessor { input: PathBuf, options: CliOptions, rpu_nals: Vec<RpuNal>, previous_rpu_index: u64, progress_bar: ProgressBar, dovi_writer: DoviWriter, } pub struct DoviWriter { bl_writer: Option<BufWriter<File>>, el_writer: Option<BufWriter<File>>, rpu_writer: Option<BufWriter<File>>, sl_writer: Option<BufWriter<File>>, } #[derive(Debug)] pub struct RpuNal { decoded_index: usize, presentation_number: usize, data: Vec<u8>, } impl DoviWriter { pub fn new( bl_out: Option<&Path>, el_out: Option<&Path>, rpu_out: Option<&Path>, single_layer_out: Option<&Path>, ) -> DoviWriter { let chunk_size = 100_000; let bl_writer = bl_out.map(|bl_out| { BufWriter::with_capacity( chunk_size, File::create(bl_out).expect("Can't create file for BL"), ) }); let el_writer = el_out.map(|el_out| { BufWriter::with_capacity( chunk_size, File::create(el_out).expect("Can't create file for EL"), ) }); let rpu_writer = rpu_out.map(|rpu_out| { BufWriter::with_capacity( chunk_size, File::create(rpu_out).expect("Can't create file for RPU"), ) }); let sl_writer = single_layer_out.map(|single_layer_out| { BufWriter::with_capacity( chunk_size, File::create(single_layer_out).expect("Can't create file for SL output"), ) }); DoviWriter { bl_writer, el_writer, rpu_writer, sl_writer, } } } impl DoviProcessor { pub fn new( options: CliOptions, input: PathBuf, dovi_writer: DoviWriter, progress_bar: ProgressBar, ) -> DoviProcessor { DoviProcessor { input, options, rpu_nals: Vec::new(), previous_rpu_index: 0, progress_bar, dovi_writer, } } pub fn read_write_from_io(&mut self, format: &IoFormat) -> Result<()> { let chunk_size = 100_000; let parse_nals = self.dovi_writer.rpu_writer.is_some(); let processor_opts = HevcProcessorOpts { parse_nals, ..Default::default() }; let mut processor = HevcProcessor::new(format.clone(), processor_opts, chunk_size); let stdin = std::io::stdin(); let mut reader = Box::new(stdin.lock()) as Box<dyn BufRead>; if let IoFormat::Raw = format { let file = File::open(&self.input)?; reader = Box::new(BufReader::with_capacity(100_000, file)); } processor.process_io(&mut reader, self) } pub fn write_nals(&mut self, chunk: &[u8], nals: &[NALUnit]) -> Result<()> { for nal in nals { if self.options.drop_hdr10plus && nal.nal_type == NAL_SEI_PREFIX && is_st2094_40_sei(&chunk[nal.start..nal.end])? { continue; } if self.previous_rpu_index > 0 && nal.nal_type == NAL_UNSPEC62 && nal.decoded_frame_index == self.previous_rpu_index { println!( "Warning: Unexpected RPU NALU found for frame {}. Discarding.", self.previous_rpu_index ); continue; } if let Some(ref mut sl_writer) = self.dovi_writer.sl_writer { if nal.nal_type == NAL_UNSPEC63 && self.options.discard_el { continue; } sl_writer.write_all(hevc_parser::NALUStartCode::Length4.slice())?; if nal.nal_type == NAL_UNSPEC62 && (self.options.mode.is_some() || self.options.edit_config.is_some()) { let modified_data = convert_encoded_from_opts(&self.options, &chunk[nal.start..nal.end])?; sl_writer.write_all(&modified_data)?; continue; } sl_writer.write_all(&chunk[nal.start..nal.end])?; continue; } match nal.nal_type { NAL_UNSPEC63 => { if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.write_all(NALUStartCode::Length4.slice())?; el_writer.write_all(&chunk[nal.start + 2..nal.end])?; } } NAL_UNSPEC62 => { self.previous_rpu_index = nal.decoded_frame_index; if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.write_all(NALUStartCode::Length4.slice())?; } let rpu_data = &chunk[nal.start..nal.end]; if self.options.mode.is_some() || self.options.edit_config.is_some() { let modified_data = convert_encoded_from_opts(&self.options, rpu_data)?; if let Some(ref mut _rpu_writer) = self.dovi_writer.rpu_writer { self.rpu_nals.push(RpuNal { decoded_index: self.rpu_nals.len(), presentation_number: 0, data: modified_data[2..].to_owned(), }); } else if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.write_all(&modified_data)?; } } else if let Some(ref mut _rpu_writer) = self.dovi_writer.rpu_writer { self.rpu_nals.push(RpuNal { decoded_index: self.rpu_nals.len(), presentation_number: 0, data: rpu_data[2..].to_vec(), }); } else if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.write_all(rpu_data)?; } } _ => { if let Some(ref mut bl_writer) = self.dovi_writer.bl_writer { bl_writer.write_all(NALUStartCode::Length4.slice())?; bl_writer.write_all(&chunk[nal.start..nal.end])?; } } } } Ok(()) } fn flush_writer(&mut self, parser: &HevcParser) -> Result<()> { if let Some(ref mut bl_writer) = self.dovi_writer.bl_writer { bl_writer.flush()?; } if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.flush()?; } if let Some(ref mut rpu_writer) = self.dovi_writer.rpu_writer { let frames = parser.ordered_frames(); if frames.is_empty() { bail!("No frames parsed!"); } print!("Reordering metadata... "); stdout().flush().ok(); self.rpu_nals.sort_by_cached_key(|rpu| { let matching_index = frames .iter() .position(|f| rpu.decoded_index == f.decoded_number as usize); if let Some(i) = matching_index { frames[i].presentation_number } else { panic!( "Missing frame/slices for metadata! Decoded index {}", rpu.decoded_index ); } }); self.rpu_nals .iter_mut() .enumerate() .for_each(|(idx, rpu)| rpu.presentation_number = idx); println!("Done."); for rpu in self.rpu_nals.iter_mut() { rpu_writer.write_all(NALUStartCode::Length4.slice())?; rpu_writer.write_all(&rpu.data)?; } rpu_writer.flush()?; } Ok(()) } } impl IoProcessor for DoviProcessor { fn input(&self) -> &std::path::PathBuf { &self.input } fn update_progress(&mut self, delta: u64) { self.progress_bar.inc(delta); } fn process_nals(&mut self, _parser: &HevcParser, nals: &[NALUnit], chunk: &[u8]) -> Result<()> { self.write_nals(chunk, nals) } fn finalize(&mut self, parser: &HevcParser) -> Result<()> { self.progress_bar.finish_and_clear(); self.flush_writer(parser) } }
use std::io::{stdout, BufRead, BufReader, BufWriter, Write}; use std::path::PathBuf; use std::{fs::File, path::Path}; use anyhow::{bail, Result}; use indicatif::ProgressBar; use hevc_parser::hevc::{NALUnit, NAL_SEI_PREFIX, NAL_UNSPEC62, NAL_UNSPEC63}; use hevc_parser::io::{processor, IoFormat, IoProcessor}; use hevc_parser::{HevcParser, NALUStartCode}; use processor::{HevcProcessor, HevcProcessorOpts}; use super::{convert_encoded_from_opts, is_st2094_40_sei, CliOptions}; pub struct DoviProcessor { input: PathBuf, options: CliOptions, rpu_nals: Vec<RpuNal>, previous_rpu_index: u64, progress_bar: ProgressBar, dovi_writer: DoviWriter, } pub struct DoviWriter { bl_writer: Option<BufWriter<File>>, el_writer: Option<BufWriter<File>>, rpu_writer: Option<BufWriter<File>>, sl_writer: Option<BufWriter<File>>, } #[derive(Debug)] pub struct RpuNal { decoded_index: usize, presentation_number: usize, data: Vec<u8>, } impl DoviWriter { pub fn new( bl_out: Option<&Path>, el_out: Option<&Path>, rpu_out: Option<&Path>, single_layer_out: Option<&Path>, ) -> DoviWriter { let chunk_size = 100_000; let bl_writer = bl_out.map(|bl_out| { BufWriter::with_capacity( chunk_size, File::create(bl_out).expect("Can't create file for BL"), ) }); let el_writer = el_out.map(|el_out| { BufWriter::with_capacity( chunk_size, File::create(el_out).expect("Can't create file for EL"), ) }); let rpu_writer = rpu_out.map(|rpu_out| { BufWriter::with_capacity( chunk_size, File::create(rpu_out).expect("Can't create file for RPU"), ) }); let sl_writer = single_layer_out.map(|single_layer_out| { BufWriter::with_capacity( chunk_size, File::create(single_layer_out).expect("Can't create file for SL output"), ) }); DoviWriter { bl_writer, el_writer, rpu_writer, sl_writer, } } } impl DoviProcessor { pub fn new( options: CliOptions, input: PathBuf, dovi_writer: DoviWriter, progress_bar: ProgressBar, ) -> DoviProcessor { DoviProcessor { input, options, rpu_nals: Vec::new(), previous_rpu_index: 0, progress_bar, dovi_writer, } } pub fn read_write_from_io(&mut self, format: &IoFormat) -> Result<()> { let chunk_size = 100_000; let parse_nals = self.dovi_writer.rpu_writer.is_some(); let processor_opts = HevcProcessorOpts { parse_nals, ..Default::default() }; let mut processor = HevcProcessor::new(format.clone(), processor_opts, chunk_size); let stdin = std::io::stdin(); let mut reader = Box::new(stdin.lock()) as Box<dyn BufRead>; if let IoFormat::Raw = format { let file = File::open(&self.input)?; reader = Box::new(BufReader::with_capacity(100_000, file)); } processor.process_io(&mut reader, self) } pub fn write_nals(&mut self, chunk: &[u8], nals: &[NALUnit]) -> Result<()> { for nal in nals { if self.options.drop_hdr10plus && nal.nal_type == NAL_SEI_PREFIX && is_st2094_40_sei(&chunk[nal.start..nal.end])? { continue; } if self.previous_rpu_index > 0 && nal.nal_type == NAL_UNSPEC62 && nal.decoded_frame_index == self.previous_rpu_index { println!( "Warning: Unexpected RPU NALU found for frame {}. Discarding.", self.previous_rpu_index ); continue; } if let Some(ref mut sl_writer) = self.dovi_writer.sl_writer { if nal.nal_type == NAL_UNSPEC63 && self.options.discard_el { continue; } sl_writer.write_all(hevc_parser::NALUStartCode::Length4.slice())?; if nal.nal_type == NAL_UNSPEC62 && (self.options.mode.is_some() || self.options.edit_config.is_some()) { let modified_data = convert_encoded_from_opts(&self.options, &chunk[nal.start..nal.end])?; sl_writer.write_all(&modified_data)?; continue; } sl_writer.write_all(&chunk[nal.start..nal.end])?; continue; } match nal.nal_type { NAL_UNSPEC63 => { if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.write_all(NALUStartCode::Length4.slice())?; el_writer.write_all(&chunk[nal.start + 2..nal.end])?; } } NAL_UNSPEC62 => { self.previous_rpu_index = nal.decoded_frame_index; if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.write_all(NALUStartCode::Length4.slice())?; } let rpu_data = &chunk[nal.start..nal.end]; if self.options.mode.is_some() || self.options.edit_config.is_some() { let modified_data = convert_encoded_from_opts(&self.options, rpu_data)?; if let Some(ref mut _rpu_writer) = self.dovi_writer.rpu_writer { self.rpu_nals.push(RpuNal { decoded_index: self.rpu_nals.len(), presentation_number: 0, data: modified_data[2..].to_owned(), }); } else if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.write_all(&modified_data)?; } } else if let Some(ref mut _rpu_writer) = self.dovi_writer.rpu_writer { self.rpu_nals.push(RpuNal { decoded_index: self.rpu_nals.len(), presentation_number: 0, data: rpu_data[2..].to_vec(), }); } else if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.write_all(rpu_data)?; } } _ => { if let Some(ref mut bl_writer) = self.dovi_writer.bl_writer { bl_writer.write_all(NALUStartCode::Length4.slice())?; bl_writer.write_all(&chunk[nal.start..nal.end])?; } } } } Ok(()) }
} impl IoProcessor for DoviProcessor { fn input(&self) -> &std::path::PathBuf { &self.input } fn update_progress(&mut self, delta: u64) { self.progress_bar.inc(delta); } fn process_nals(&mut self, _parser: &HevcParser, nals: &[NALUnit], chunk: &[u8]) -> Result<()> { self.write_nals(chunk, nals) } fn finalize(&mut self, parser: &HevcParser) -> Result<()> { self.progress_bar.finish_and_clear(); self.flush_writer(parser) } }
fn flush_writer(&mut self, parser: &HevcParser) -> Result<()> { if let Some(ref mut bl_writer) = self.dovi_writer.bl_writer { bl_writer.flush()?; } if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.flush()?; } if let Some(ref mut rpu_writer) = self.dovi_writer.rpu_writer { let frames = parser.ordered_frames(); if frames.is_empty() { bail!("No frames parsed!"); } print!("Reordering metadata... "); stdout().flush().ok(); self.rpu_nals.sort_by_cached_key(|rpu| { let matching_index = frames .iter() .position(|f| rpu.decoded_index == f.decoded_number as usize); if let Some(i) = matching_index { frames[i].presentation_number } else { panic!( "Missing frame/slices for metadata! Decoded index {}", rpu.decoded_index ); } }); self.rpu_nals .iter_mut() .enumerate() .for_each(|(idx, rpu)| rpu.presentation_number = idx); println!("Done."); for rpu in self.rpu_nals.iter_mut() { rpu_writer.write_all(NALUStartCode::Length4.slice())?; rpu_writer.write_all(&rpu.data)?; } rpu_writer.flush()?; } Ok(()) }
function_block-full_function
[ { "content": "pub fn write_rpu_file(output_path: &Path, data: Vec<Vec<u8>>) -> Result<()> {\n\n println!(\"Writing RPU file...\");\n\n let mut writer = BufWriter::with_capacity(\n\n 100_000,\n\n File::create(output_path).expect(\"Can't create file\"),\n\n );\n\n\n\n for encoded_rpu in ...
Rust
xdr-codec/src/record.rs
Voronar/rust-xdr
a1fa344e6cd0fce72585388b9b5145aa21d569fc
use std::io::{self, BufRead, Read, Write}; use std::cmp::min; use crate::error::*; use super::{Error, pack, unpack}; const LAST_REC: u32 = 1u32 << 31; fn mapioerr(xdrerr: Error) -> io::Error { match xdrerr { Error(ErrorKind::IOError(ioerr), _) => ioerr, other => io::Error::new(io::ErrorKind::Other, other), } } #[derive(Debug)] pub struct XdrRecordReader<R: BufRead> { size: usize, consumed: usize, eor: bool, reader: R, } impl<R: BufRead> XdrRecordReader<R> { pub fn new(rd: R) -> XdrRecordReader<R> { XdrRecordReader { size: 0, consumed: 0, eor: false, reader: rd, } } fn nextrec(&mut self) -> io::Result<bool> { assert_eq!(self.consumed, self.size); let rechdr: u32 = match unpack(&mut self.reader) { Ok(v) => v, Err(Error(ErrorKind::IOError(ref err), _)) if err.kind() == io::ErrorKind::UnexpectedEof => return Ok(true), Err(e) => return Err(mapioerr(e)), }; self.size = (rechdr & !LAST_REC) as usize; self.consumed = 0; self.eor = (rechdr & LAST_REC) != 0; Ok(false) } fn totremains(&self) -> usize { self.size - self.consumed } pub fn eor(&self) -> bool { self.eor } } impl<R: BufRead> Read for XdrRecordReader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let nread = { let data = self.fill_buf()?; let len = min(buf.len(), data.len()); (&data[..len]).read(buf)? }; self.consume(nread); Ok(nread) } } impl<R: BufRead> BufRead for XdrRecordReader<R> { fn fill_buf(&mut self) -> io::Result<&[u8]> { while self.totremains() == 0 { if self.nextrec()? { return Ok(&[]); } } let remains = self.totremains(); let data = self.reader.fill_buf()?; Ok(&data[..min(data.len(), remains)]) } fn consume(&mut self, sz: usize) { assert!(sz <= self.totremains()); self.consumed += sz; self.reader.consume(sz); } } impl<R: BufRead> IntoIterator for XdrRecordReader<R> { type Item = io::Result<Vec<u8>>; type IntoIter = XdrRecordReaderIter<R>; fn into_iter(self) -> Self::IntoIter { XdrRecordReaderIter(Some(self)) } } #[derive(Debug)] pub struct XdrRecordReaderIter<R: BufRead>(Option<XdrRecordReader<R>>); impl<R: BufRead> Iterator for XdrRecordReaderIter<R> { type Item = io::Result<Vec<u8>>; fn next(&mut self) -> Option<Self::Item> { if let Some(mut rr) = self.0.take() { let mut buf = Vec::new(); loop { if rr.totremains() == 0 { match rr.nextrec() { Err(e) => return Some(Err(e)), Ok(true) => return None, Ok(false) => (), } } let remains = rr.totremains(); let eor = rr.eor(); match rr.by_ref().take(remains as u64).read_to_end(&mut buf) { Ok(sz) if sz == remains => (), Ok(_) => return None, Err(e) => return Some(Err(e)), }; if eor { break; } } self.0 = Some(rr); Some(Ok(buf)) } else { None } } } const WRBUF: usize = 65536; pub struct XdrRecordWriter<W: Write> { buf: Vec<u8>, bufsz: usize, eor: bool, writer: W, } impl<W: Write> XdrRecordWriter<W> { pub fn new(w: W) -> XdrRecordWriter<W> { XdrRecordWriter::with_buffer(w, WRBUF) } pub fn with_buffer(w: W, bufsz: usize) -> XdrRecordWriter<W> { if bufsz == 0 { panic!("bufsz must be non-zero") } XdrRecordWriter { buf: Vec::with_capacity(bufsz), bufsz: bufsz, eor: false, writer: w, } } pub fn flush_eor(&mut self, eor: bool) -> io::Result<()> { if !eor && self.buf.len() == 0 { return Ok(()); } let rechdr = self.buf.len() as u32 | (if eor { LAST_REC } else { 0 }); pack(&rechdr, &mut self.writer).map_err(mapioerr)?; let _ = self.writer.write_all(&self.buf).map(|_| ())?; self.buf.truncate(0); self.eor = eor; self.writer.flush() } } impl<W: Write> Drop for XdrRecordWriter<W> { fn drop(&mut self) { if self.buf.len() > 0 || !self.eor { let _ = self.flush_eor(true); } } } impl<W: Write> Write for XdrRecordWriter<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut off = 0; while off < buf.len() { let chunk = &buf[off..off + min(buf.len() - off, self.bufsz)]; if self.buf.len() + chunk.len() > self.bufsz { self.flush()?; } self.buf.extend(chunk); off += chunk.len(); } Ok(off) } fn flush(&mut self) -> io::Result<()> { self.flush_eor(false) } }
use std::io::{self, BufRead, Read, Write}; use std::cmp::min; use crate::error::*; use super::{Error, pack, unpack}; const LAST_REC: u32 = 1u32 << 31; fn mapioerr(xdrerr: Error) -> io::Error { match xdrerr { Error(ErrorKind::IOError(ioerr), _) => ioerr, other => io::Error::new(io::ErrorKind::Other, other), } } #[derive(Debug)] pub struct XdrRecordReader<R: BufRead> { size: usize, consumed: usize, eor: bool, reader: R, } impl<R: BufRead> XdrRecordReader<R> { pub fn new(rd: R) -> XdrRecordReader<R> { XdrRecordReader { size: 0, consumed: 0, eor: false, reader: rd, } } fn nextrec(&mut self) -> io::Result<bool> { assert_eq!(self.consumed, self.size); let rechdr: u32 = match unpack(&mut self.reader) { Ok(v) => v, Err(Error(ErrorKind::IOError(ref err), _)) if err.kind() == io::ErrorKind::UnexpectedEof => return Ok(true), Err(e) => return Err(mapioerr(e)), }; self.size = (rechdr & !LAST_REC) as usize; self.consumed = 0; self.eor = (rechdr & LAST_REC) != 0; Ok(false) } fn totremains(&self) -> usize { self.size - self.consumed } pub fn eor(&self) -> bool { self.eor } } impl<R: BufRead> Read for XdrRecordReader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let nread = { let data = self.fill_buf()?; let len = min(buf.len(), data.len()); (&data[..len]).read(buf)? }; self.consume(nread); Ok(nread) } } impl<R: BufRead> BufRead for XdrRecordReader<R> { fn fill_buf(&mut self) -> io::Result<&[u8]> { while self.totremains() == 0 { if self.nextrec()? { return Ok(&[]); } } let remains = self.totremains(); let data = self.reader.fill_buf()?; Ok(&data[..min(data.len(), remains)]) } fn consume(&mut self, sz: usize) { assert!(sz <= self.totremains()); self.consumed += sz; self.reader.consume(sz); } } impl<R: BufRead> IntoIterator for XdrRecordReader<R> { type Item = io::Result<Vec<u8>>; type IntoIter = XdrRecordReaderIter<R>; fn into_iter(self) -> Self::IntoIter { XdrRecordReaderIter(Some(self)) } } #[derive(Debug)] pub struct XdrRecordReaderIter<R: BufRead>(Option<XdrRecordReader<R>>); impl<R: BufRead> Iterator for XdrRecordReaderIter<R> { type Item = io::Result<Vec<u8>>; fn next(&mut self) -> Option<Self::Item> { if let Some(mut rr) = self.0.take() { let mut buf = Vec::new(); loop { if rr.totremains() == 0 { match rr.nextrec() { Err(e) => return Some(Err(e)), Ok(true) => return None, Ok(false) => (), } } let remains = rr.totremains(); let eor = rr.eor(); match rr.by_ref().take(remains as u64).read_to_end(&mut buf) { Ok(sz) if sz == remains => (), Ok(_) => return None, Err(e) => return Some(Err(e)), }; if eor { brea
} const WRBUF: usize = 65536; pub struct XdrRecordWriter<W: Write> { buf: Vec<u8>, bufsz: usize, eor: bool, writer: W, } impl<W: Write> XdrRecordWriter<W> { pub fn new(w: W) -> XdrRecordWriter<W> { XdrRecordWriter::with_buffer(w, WRBUF) } pub fn with_buffer(w: W, bufsz: usize) -> XdrRecordWriter<W> { if bufsz == 0 { panic!("bufsz must be non-zero") } XdrRecordWriter { buf: Vec::with_capacity(bufsz), bufsz: bufsz, eor: false, writer: w, } } pub fn flush_eor(&mut self, eor: bool) -> io::Result<()> { if !eor && self.buf.len() == 0 { return Ok(()); } let rechdr = self.buf.len() as u32 | (if eor { LAST_REC } else { 0 }); pack(&rechdr, &mut self.writer).map_err(mapioerr)?; let _ = self.writer.write_all(&self.buf).map(|_| ())?; self.buf.truncate(0); self.eor = eor; self.writer.flush() } } impl<W: Write> Drop for XdrRecordWriter<W> { fn drop(&mut self) { if self.buf.len() > 0 || !self.eor { let _ = self.flush_eor(true); } } } impl<W: Write> Write for XdrRecordWriter<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut off = 0; while off < buf.len() { let chunk = &buf[off..off + min(buf.len() - off, self.bufsz)]; if self.buf.len() + chunk.len() > self.bufsz { self.flush()?; } self.buf.extend(chunk); off += chunk.len(); } Ok(off) } fn flush(&mut self) -> io::Result<()> { self.flush_eor(false) } }
k; } } self.0 = Some(rr); Some(Ok(buf)) } else { None } }
function_block-function_prefixed
[ { "content": "/// Pack a fixed-size byte array\n\n///\n\n/// As size is fixed, it doesn't need to be encoded. `sz` is in bytes (and array elements, which are u8)\n\n/// If the array is too large, it is truncated; if its too small its padded with `0x00`.\n\npub fn pack_opaque_array<Out: Write>(val: &[u8], sz: us...
Rust
pac/atsam4sd32c/src/spi/ier.rs
haata/atsam4-pac
849dd8fcf3be0074d98b8fc65e4fb03fdfd4b6b1
#[doc = "Writer for register IER"] pub type W = crate::W<u32, super::IER>; #[doc = "Write proxy for field `RDRF`"] pub struct RDRF_W<'a> { w: &'a mut W, } impl<'a> RDRF_W<'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 = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Write proxy for field `TDRE`"] pub struct TDRE_W<'a> { w: &'a mut W, } impl<'a> TDRE_W<'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 = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `MODF`"] pub struct MODF_W<'a> { w: &'a mut W, } impl<'a> MODF_W<'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 = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Write proxy for field `OVRES`"] pub struct OVRES_W<'a> { w: &'a mut W, } impl<'a> OVRES_W<'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 = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `ENDRX`"] pub struct ENDRX_W<'a> { w: &'a mut W, } impl<'a> ENDRX_W<'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 = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Write proxy for field `ENDTX`"] pub struct ENDTX_W<'a> { w: &'a mut W, } impl<'a> ENDTX_W<'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 = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Write proxy for field `RXBUFF`"] pub struct RXBUFF_W<'a> { w: &'a mut W, } impl<'a> RXBUFF_W<'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 = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Write proxy for field `TXBUFE`"] pub struct TXBUFE_W<'a> { w: &'a mut W, } impl<'a> TXBUFE_W<'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 = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Write proxy for field `NSSR`"] pub struct NSSR_W<'a> { w: &'a mut W, } impl<'a> NSSR_W<'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 = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Write proxy for field `TXEMPTY`"] pub struct TXEMPTY_W<'a> { w: &'a mut W, } impl<'a> TXEMPTY_W<'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 = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Write proxy for field `UNDES`"] pub struct UNDES_W<'a> { w: &'a mut W, } impl<'a> UNDES_W<'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 = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } impl W { #[doc = "Bit 0 - Receive Data Register Full Interrupt Enable"] #[inline(always)] pub fn rdrf(&mut self) -> RDRF_W { RDRF_W { w: self } } #[doc = "Bit 1 - SPI Transmit Data Register Empty Interrupt Enable"] #[inline(always)] pub fn tdre(&mut self) -> TDRE_W { TDRE_W { w: self } } #[doc = "Bit 2 - Mode Fault Error Interrupt Enable"] #[inline(always)] pub fn modf(&mut self) -> MODF_W { MODF_W { w: self } } #[doc = "Bit 3 - Overrun Error Interrupt Enable"] #[inline(always)] pub fn ovres(&mut self) -> OVRES_W { OVRES_W { w: self } } #[doc = "Bit 4 - End of Receive Buffer Interrupt Enable"] #[inline(always)] pub fn endrx(&mut self) -> ENDRX_W { ENDRX_W { w: self } } #[doc = "Bit 5 - End of Transmit Buffer Interrupt Enable"] #[inline(always)] pub fn endtx(&mut self) -> ENDTX_W { ENDTX_W { w: self } } #[doc = "Bit 6 - Receive Buffer Full Interrupt Enable"] #[inline(always)] pub fn rxbuff(&mut self) -> RXBUFF_W { RXBUFF_W { w: self } } #[doc = "Bit 7 - Transmit Buffer Empty Interrupt Enable"] #[inline(always)] pub fn txbufe(&mut self) -> TXBUFE_W { TXBUFE_W { w: self } } #[doc = "Bit 8 - NSS Rising Interrupt Enable"] #[inline(always)] pub fn nssr(&mut self) -> NSSR_W { NSSR_W { w: self } } #[doc = "Bit 9 - Transmission Registers Empty Enable"] #[inline(always)] pub fn txempty(&mut self) -> TXEMPTY_W { TXEMPTY_W { w: self } } #[doc = "Bit 10 - Underrun Error Interrupt Enable"] #[inline(always)] pub fn undes(&mut self) -> UNDES_W { UNDES_W { w: self } } }
#[doc = "Writer for register IER"] pub type W = crate::W<u32, super::IER>; #[doc = "Write proxy for field `RDRF`"] pub struct RDRF_W<'a> { w: &'a mut W, } impl<'a> RDRF_W<'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 = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Write proxy for field `TDRE`"] pub struct TDRE_W<'a> { w: &'a mut W, } impl<'a> TDRE_W<'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 = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `MODF`"] pub struct MODF_W<'a> { w: &'a mut W, } impl<'a> MODF_W<'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 = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Write proxy for field `OVRES`"] pub struct OVRES_W<'a> { w: &'a mut W, } impl<'a> OVRES_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r
#[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 = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } impl W { #[doc = "Bit 0 - Receive Data Register Full Interrupt Enable"] #[inline(always)] pub fn rdrf(&mut self) -> RDRF_W { RDRF_W { w: self } } #[doc = "Bit 1 - SPI Transmit Data Register Empty Interrupt Enable"] #[inline(always)] pub fn tdre(&mut self) -> TDRE_W { TDRE_W { w: self } } #[doc = "Bit 2 - Mode Fault Error Interrupt Enable"] #[inline(always)] pub fn modf(&mut self) -> MODF_W { MODF_W { w: self } } #[doc = "Bit 3 - Overrun Error Interrupt Enable"] #[inline(always)] pub fn ovres(&mut self) -> OVRES_W { OVRES_W { w: self } } #[doc = "Bit 4 - End of Receive Buffer Interrupt Enable"] #[inline(always)] pub fn endrx(&mut self) -> ENDRX_W { ENDRX_W { w: self } } #[doc = "Bit 5 - End of Transmit Buffer Interrupt Enable"] #[inline(always)] pub fn endtx(&mut self) -> ENDTX_W { ENDTX_W { w: self } } #[doc = "Bit 6 - Receive Buffer Full Interrupt Enable"] #[inline(always)] pub fn rxbuff(&mut self) -> RXBUFF_W { RXBUFF_W { w: self } } #[doc = "Bit 7 - Transmit Buffer Empty Interrupt Enable"] #[inline(always)] pub fn txbufe(&mut self) -> TXBUFE_W { TXBUFE_W { w: self } } #[doc = "Bit 8 - NSS Rising Interrupt Enable"] #[inline(always)] pub fn nssr(&mut self) -> NSSR_W { NSSR_W { w: self } } #[doc = "Bit 9 - Transmission Registers Empty Enable"] #[inline(always)] pub fn txempty(&mut self) -> TXEMPTY_W { TXEMPTY_W { w: self } } #[doc = "Bit 10 - Underrun Error Interrupt Enable"] #[inline(always)] pub fn undes(&mut self) -> UNDES_W { UNDES_W { w: self } } }
"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 = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `ENDRX`"] pub struct ENDRX_W<'a> { w: &'a mut W, } impl<'a> ENDRX_W<'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 = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Write proxy for field `ENDTX`"] pub struct ENDTX_W<'a> { w: &'a mut W, } impl<'a> ENDTX_W<'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 = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Write proxy for field `RXBUFF`"] pub struct RXBUFF_W<'a> { w: &'a mut W, } impl<'a> RXBUFF_W<'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 = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Write proxy for field `TXBUFE`"] pub struct TXBUFE_W<'a> { w: &'a mut W, } impl<'a> TXBUFE_W<'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 = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Write proxy for field `NSSR`"] pub struct NSSR_W<'a> { w: &'a mut W, } impl<'a> NSSR_W<'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 = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Write proxy for field `TXEMPTY`"] pub struct TXEMPTY_W<'a> { w: &'a mut W, } impl<'a> TXEMPTY_W<'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 = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Write proxy for field `UNDES`"] pub struct UNDES_W<'a> { w: &'a mut W, } impl<'a> UNDES_W<'a> {
random
[]
Rust
graphdb/rust/src/generated.rs
jordan-rash/actor-interfaces
e4679488148ff4f1e11a0c7b87a8d9c8b32e24e8
extern crate rmp_serde as rmps; use rmps::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use std::io::Cursor; extern crate log; #[cfg(feature = "guest")] extern crate wapc_guest as guest; #[cfg(feature = "guest")] use guest::prelude::*; #[cfg(feature = "guest")] use lazy_static::lazy_static; #[cfg(feature = "guest")] use std::sync::RwLock; #[cfg(feature = "guest")] pub struct Host { binding: String, } #[cfg(feature = "guest")] impl Default for Host { fn default() -> Self { Host { binding: "default".to_string(), } } } #[cfg(feature = "guest")] pub fn host(binding: &str) -> Host { Host { binding: binding.to_string(), } } #[cfg(feature = "guest")] pub fn default() -> Host { Host::default() } #[cfg(feature = "guest")] impl Host { pub(crate) fn query(&self, graphName: String, query: String) -> HandlerResult<QueryResponse> { let input_args = QueryGraphArgs { graph_name: graphName, query: query, }; host_call( &self.binding, "wasmcloud:graphdb", "QueryGraph", &serialize(input_args)?, ) .map(|vec| { let resp = deserialize::<QueryResponse>(vec.as_ref()).unwrap(); resp }) .map_err(|e| e.into()) } pub fn delete_graph(&self, graphName: String) -> HandlerResult<DeleteResponse> { let input_args = DeleteGraphArgs { graph_name: graphName, }; host_call( &self.binding, "wasmcloud:graphdb", "DeleteGraph", &serialize(input_args)?, ) .map(|vec| { let resp = deserialize::<DeleteResponse>(vec.as_ref()).unwrap(); resp }) .map_err(|e| e.into()) } } #[cfg(feature = "guest")] pub struct Handlers {} #[cfg(feature = "guest")] impl Handlers { pub fn register_query_graph(f: fn(String, String) -> HandlerResult<QueryResponse>) { *QUERY_GRAPH.write().unwrap() = Some(f); register_function(&"QueryGraph", query_graph_wrapper); } pub fn register_delete_graph(f: fn(String) -> HandlerResult<DeleteResponse>) { *DELETE_GRAPH.write().unwrap() = Some(f); register_function(&"DeleteGraph", delete_graph_wrapper); } } #[cfg(feature = "guest")] lazy_static! { static ref QUERY_GRAPH: RwLock<Option<fn(String, String) -> HandlerResult<QueryResponse>>> = RwLock::new(None); static ref DELETE_GRAPH: RwLock<Option<fn(String) -> HandlerResult<DeleteResponse>>> = RwLock::new(None); } #[cfg(feature = "guest")] fn query_graph_wrapper(input_payload: &[u8]) -> CallResult { let input = deserialize::<QueryGraphArgs>(input_payload)?; let lock = QUERY_GRAPH.read().unwrap().unwrap(); let result = lock(input.graph_name, input.query)?; Ok(serialize(result)?) } #[cfg(feature = "guest")] fn delete_graph_wrapper(input_payload: &[u8]) -> CallResult { let input = deserialize::<DeleteGraphArgs>(input_payload)?; let lock = DELETE_GRAPH.read().unwrap().unwrap(); let result = lock(input.graph_name)?; Ok(serialize(result)?) } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct QueryGraphArgs { #[serde(rename = "graphName")] pub graph_name: String, #[serde(rename = "query")] pub query: String, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct DeleteGraphArgs { #[serde(rename = "graphName")] pub graph_name: String, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct QueryResponse { #[serde(rename = "resultSet")] pub result_set: ResultSet, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct DeleteResponse { #[serde(rename = "success")] pub success: bool, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct ResultSet { #[serde(rename = "columns")] pub columns: Vec<Column>, #[serde(rename = "statistics")] pub statistics: Vec<String>, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct Column { #[serde(rename = "scalars")] pub scalars: Option<Vec<Scalar>>, #[serde(rename = "nodes")] pub nodes: Option<Vec<Node>>, #[serde(rename = "relations")] pub relations: Option<Vec<Relation>>, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct Scalar { #[serde(rename = "boolValue")] pub bool_value: Option<bool>, #[serde(rename = "intValue")] pub int_value: Option<i64>, #[serde(rename = "doubleValue")] pub double_value: Option<f64>, #[serde(rename = "stringValue")] pub string_value: Option<String>, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct Node { #[serde(rename = "labels")] pub labels: Vec<String>, #[serde(rename = "properties")] pub properties: std::collections::HashMap<String, Scalar>, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct Relation { #[serde(rename = "typeName")] pub type_name: String, #[serde(rename = "properties")] pub properties: std::collections::HashMap<String, Scalar>, } pub fn serialize<T>( item: T, ) -> ::std::result::Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> where T: Serialize, { let mut buf = Vec::new(); item.serialize(&mut Serializer::new(&mut buf).with_struct_map())?; Ok(buf) } pub fn deserialize<'de, T: Deserialize<'de>>( buf: &[u8], ) -> ::std::result::Result<T, Box<dyn std::error::Error + Send + Sync>> { let mut de = Deserializer::new(Cursor::new(buf)); match Deserialize::deserialize(&mut de) { Ok(t) => Ok(t), Err(e) => Err(format!("Failed to de-serialize: {}", e).into()), } }
extern crate rmp_serde as rmps; use rmps::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use std::io::Cursor; extern crate log; #[cfg(feature = "guest")] extern crate wapc_guest as guest; #[cfg(feature = "guest")] use guest::prelude::*; #[cfg(feature = "guest")] use lazy_static::lazy_static; #[cfg(feature = "guest")] use std::sync::RwLock; #[cfg(feature = "guest")] pub struct Host { binding: String, } #[cfg(feature = "guest")] impl Default for Host { fn default() -> Self { Host { binding: "default".to_string(), } } } #[cfg(feature = "guest")] pub fn host(binding: &str) -> Host { Host { binding: binding.to_string(), } } #[cfg(feature = "guest")] pub fn default() -> Host { Host::default() } #[cfg(feature = "guest")] impl Host { pub(crate) fn query(&self, graphName: String, query: String) -> HandlerResult<QueryResponse> { let input_args = QueryGraphArgs { graph_name: graphName, query: query, }; host_call( &self.binding, "wasmcloud:graphdb", "QueryGraph", &serialize(input_args)?, ) .map(|vec| { let resp = deserialize::<QueryResponse>(vec.as_ref()).unwrap(); resp })
erialize<'de>>( buf: &[u8], ) -> ::std::result::Result<T, Box<dyn std::error::Error + Send + Sync>> { let mut de = Deserializer::new(Cursor::new(buf)); match Deserialize::deserialize(&mut de) { Ok(t) => Ok(t), Err(e) => Err(format!("Failed to de-serialize: {}", e).into()), } }
.map_err(|e| e.into()) } pub fn delete_graph(&self, graphName: String) -> HandlerResult<DeleteResponse> { let input_args = DeleteGraphArgs { graph_name: graphName, }; host_call( &self.binding, "wasmcloud:graphdb", "DeleteGraph", &serialize(input_args)?, ) .map(|vec| { let resp = deserialize::<DeleteResponse>(vec.as_ref()).unwrap(); resp }) .map_err(|e| e.into()) } } #[cfg(feature = "guest")] pub struct Handlers {} #[cfg(feature = "guest")] impl Handlers { pub fn register_query_graph(f: fn(String, String) -> HandlerResult<QueryResponse>) { *QUERY_GRAPH.write().unwrap() = Some(f); register_function(&"QueryGraph", query_graph_wrapper); } pub fn register_delete_graph(f: fn(String) -> HandlerResult<DeleteResponse>) { *DELETE_GRAPH.write().unwrap() = Some(f); register_function(&"DeleteGraph", delete_graph_wrapper); } } #[cfg(feature = "guest")] lazy_static! { static ref QUERY_GRAPH: RwLock<Option<fn(String, String) -> HandlerResult<QueryResponse>>> = RwLock::new(None); static ref DELETE_GRAPH: RwLock<Option<fn(String) -> HandlerResult<DeleteResponse>>> = RwLock::new(None); } #[cfg(feature = "guest")] fn query_graph_wrapper(input_payload: &[u8]) -> CallResult { let input = deserialize::<QueryGraphArgs>(input_payload)?; let lock = QUERY_GRAPH.read().unwrap().unwrap(); let result = lock(input.graph_name, input.query)?; Ok(serialize(result)?) } #[cfg(feature = "guest")] fn delete_graph_wrapper(input_payload: &[u8]) -> CallResult { let input = deserialize::<DeleteGraphArgs>(input_payload)?; let lock = DELETE_GRAPH.read().unwrap().unwrap(); let result = lock(input.graph_name)?; Ok(serialize(result)?) } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct QueryGraphArgs { #[serde(rename = "graphName")] pub graph_name: String, #[serde(rename = "query")] pub query: String, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct DeleteGraphArgs { #[serde(rename = "graphName")] pub graph_name: String, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct QueryResponse { #[serde(rename = "resultSet")] pub result_set: ResultSet, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct DeleteResponse { #[serde(rename = "success")] pub success: bool, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct ResultSet { #[serde(rename = "columns")] pub columns: Vec<Column>, #[serde(rename = "statistics")] pub statistics: Vec<String>, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct Column { #[serde(rename = "scalars")] pub scalars: Option<Vec<Scalar>>, #[serde(rename = "nodes")] pub nodes: Option<Vec<Node>>, #[serde(rename = "relations")] pub relations: Option<Vec<Relation>>, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct Scalar { #[serde(rename = "boolValue")] pub bool_value: Option<bool>, #[serde(rename = "intValue")] pub int_value: Option<i64>, #[serde(rename = "doubleValue")] pub double_value: Option<f64>, #[serde(rename = "stringValue")] pub string_value: Option<String>, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct Node { #[serde(rename = "labels")] pub labels: Vec<String>, #[serde(rename = "properties")] pub properties: std::collections::HashMap<String, Scalar>, } #[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)] pub struct Relation { #[serde(rename = "typeName")] pub type_name: String, #[serde(rename = "properties")] pub properties: std::collections::HashMap<String, Scalar>, } pub fn serialize<T>( item: T, ) -> ::std::result::Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> where T: Serialize, { let mut buf = Vec::new(); item.serialize(&mut Serializer::new(&mut buf).with_struct_map())?; Ok(buf) } pub fn deserialize<'de, T: Des
random
[ { "content": "#[cfg(feature = \"guest\")]\n\npub fn host(binding: &str) -> Host {\n\n set_binding(binding);\n\n Host {}\n\n}\n\n\n\n/// Creates the default host binding\n", "file_path": "logging/rust/src/generated.rs", "rank": 0, "score": 288951.3958429548 }, { "content": "#[cfg(featur...