text
stringlengths
8
4.13M
use std::error::Error; use std::result::Result; use serde_derive::{Deserialize, Serialize}; use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; use serde::de::{Deserialize, Deserializer}; use serde_json::Value; #[derive(Clone, Debug, Serialize, PartialEq, Eq)] pub struct FileTask { pub input : String, pub processing : String, pub completed : Option<String>, pub failed : Option<String> } fn normalizePath<P>(path: P) -> PathBuf where P : AsRef<Path> + Copy { let mut buffer = PathBuf::new(); for comp in path.as_ref().components() { buffer.push(comp); } buffer } impl<'de> Deserialize<'de> for FileTask { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { fn join(root: &str, leaf: &str) -> Option<String> { normalizePath(root) .join(leaf) .to_str() .map(|x| x.to_owned()) } let nodeValue:Value = Deserialize::deserialize(deserializer)?; if let Some(pathToRoot) = nodeValue.as_str() { Ok(FileTask { input: join(&pathToRoot, "input") .ok_or_else(|| serde::de::Error::custom("Bad input path"))?, processing: join(&pathToRoot, "processing") .ok_or_else(|| serde::de::Error::custom("Bad processing path"))?, completed: None, failed: None }) } else if let Some(nodeObject) = nodeValue.as_object() { let extractField = |fieldName| nodeObject .get(fieldName) .map(|value| value.as_str()) .and_then(|x| x) .map(|x| x.to_owned()) .ok_or_else(|| -> D::Error {serde::de::Error::missing_field(fieldName)}); Ok(FileTask { input: extractField("input")?, processing: extractField("processing")?, completed: extractField("completed").ok(), failed: extractField("failed").ok() }) } else { Err(serde::de::Error::custom("unable to deserialize FileTask")) } } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct Location { pub file : FileTask, pub readinessDelay : u32, pub process : String, pub shell_command : bool, pub processing_timestamp : bool, pub complete_timestamp : bool, pub current_dir: Option<String> } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Locations { pub locations : Vec<Location>, pub polling_delay : u32 } impl Locations { pub fn fromString(data: &str) -> Result<Self, Box<dyn Error>> { let cfg = serde_json::from_str(data)?; Ok(cfg) } pub fn fromFile<P: AsRef<Path>>(path: P) -> Result<Self, Box<dyn Error>> { let file = File::open(path)?; let reader = BufReader::new(file); let cfg = serde_json::from_reader(reader)?; Ok(cfg) } pub fn toString(&self) -> Result<String, Box<dyn Error>> { let s = serde_json::to_string(self)?; Ok(s) } pub fn toBytes(&self) -> Result<Vec<u8>, Box<dyn Error>> { let s = serde_json::to_vec(self)?; Ok(s) } pub fn toFile<P: AsRef<Path>>(&self, path: P) -> Result<(), Box<dyn Error>> { let buffer = File::create(path)?; serde_json::to_writer(buffer, self)?; Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_fromFile() { let loc = Locations::fromFile("./test_data/locations_test.json").unwrap(); assert_eq!(5, loc.locations.len()); assert_eq!(Location { readinessDelay: 1000, process: "command".to_owned(), shell_command: true, processing_timestamp: false, complete_timestamp: false, current_dir: Some("current_dir".to_owned()), file: FileTask { input:"input".to_string(), processing: "processing".to_string(), completed: Some("completed".to_string()), failed: Some("failed".to_string()) } }, loc.locations[0]); assert_eq!(FileTask { input:"input".to_string(), processing: "processing".to_string(), completed: None, failed: Some("failed".to_string()) }, loc.locations[1].file); assert_eq!(FileTask { input:"input".to_string(), processing: "processing".to_string(), completed: Some("completed".to_string()), failed: None }, loc.locations[2].file); let expected = FileTask { input:normalizePath("/test/path/to/folder/input").to_str().unwrap().to_owned(), processing:normalizePath("/test/path/to/folder/processing").to_str().unwrap().to_owned(), completed: None, failed: None }; assert_eq!(expected, loc.locations[3].file); assert_eq!(expected, loc.locations[4].file); } #[test] fn test_normalize_path() { assert_eq!(Path::new(""), normalizePath("")); assert_eq!(Path::new(&format!("{}", std::path::MAIN_SEPARATOR)), normalizePath(&format!("{}", std::path::MAIN_SEPARATOR))); assert_eq!(Path::new("abc"), normalizePath("abc")); assert_eq!(Path::new(".abc"), normalizePath(".abc")); assert_eq!(Path::new(&format!("abc{}xxx", std::path::MAIN_SEPARATOR)), normalizePath(&format!("abc{}xxx", std::path::MAIN_SEPARATOR))); //assert_eq!(Path::new(&format!("abc{}xxx", std::path::MAIN_SEPARATOR)), // normalizePath("abc\\xxx")); assert_eq!(Path::new(&format!("abc{}xxx", std::path::MAIN_SEPARATOR)), normalizePath("abc/xxx")); } }
use std::io; use std::mem; use super::file_loader; pub fn run(part: i32) { let input = file_loader::load_file("5.input"); let input_fn = || { println!("Your input is required. Please neter number: "); let mut input = String::new(); match io::stdin().read_line(&mut input) { Ok(n) => { println!("{} bytes read", n); println!("Input was: '{}'", input.trim()); } Err(error) => panic!(error), } return input.trim().parse::<i32>().unwrap(); }; let output_fn = |x| println!("\nOutput: {}", x); let result = day_five(&input, part as u32, input_fn, output_fn); println!("Result is {}", result) } fn day_five(input: &str, _part: u32, input_fn: fn() -> i32, output_fn: fn(i32) -> ()) -> i32 { let intcode: Vec<i32> = input.split(",") .map(|number| number.parse::<i32>().unwrap()) .collect(); run_intcode(intcode.to_vec(), input_fn, output_fn); return 0; } fn run_intcode(mut intcode: Vec<i32>, input_fn: fn() -> i32, output_fn: fn(i32) -> ()) -> Vec<i32> { let mut ptr: usize = 0; loop { let result = next_operation(&mut intcode, &mut ptr, input_fn, output_fn); //println!("ptr: {}", ptr); if result == 0 { break; } } return intcode; } fn next_operation(intcode: &mut Vec<i32>, ptr: &mut usize, input_fn: fn() -> i32, output_fn: fn(i32) -> ()) -> i32 { let opcode = intcode[*ptr]; let operation = operation_from_opcode(opcode); match operation { 1 => add(intcode, ptr, opcode), 2 => multiply(intcode, ptr, opcode), 3 => input(intcode, ptr, opcode, input_fn), 4 => output(intcode, ptr, opcode, output_fn), 5 => jump_if_true(intcode, ptr, opcode), 6 => jump_if_false(intcode, ptr, opcode), 7 => less_then(intcode, ptr, opcode), 8 => equals(intcode, ptr, opcode), 99 => return 0, _ => panic!("Unknown opcode {}. Something went wrong", opcode) } return 1; } fn operation_from_opcode(opcode: i32) -> i32 { return opcode % 100; } fn add(intcode: &mut Vec<i32>, ptr: &mut usize, opcode: i32) { let parameter_modes = modes_from_opcode(opcode, 3); let value1: i32 = value_from_parameter(parameter_modes[0], intcode, *ptr + 1); let value2: i32 = value_from_parameter(parameter_modes[1], intcode, *ptr + 2); let result_address: usize = intcode[*ptr + 3] as usize; let result: i32 = value1 + value2; //println!("Adding {} and {} to get {} to put at index {}", value1, value2, result, result_address); mem::replace(&mut intcode[result_address], result); *ptr = *ptr + 4; } fn multiply(intcode: &mut Vec<i32>, ptr: &mut usize, opcode: i32) { let parameter_modes = modes_from_opcode(opcode, 3); let value1: i32 = value_from_parameter(parameter_modes[0], intcode, *ptr + 1); let value2: i32 = value_from_parameter(parameter_modes[1], intcode, *ptr + 2); let result_address: usize = intcode[*ptr + 3] as usize; let result: i32 = value1 * value2; //println!("Adding {} and {} to get {} to put at index {}", value1, value2, result, result_address); mem::replace(&mut intcode[result_address], result); *ptr = *ptr + 4; } fn input(intcode: &mut Vec<i32>, ptr: &mut usize, _opcode: i32, input_fn: fn() -> i32) { let result_address: usize = intcode[*ptr + 1] as usize; let input = input_fn(); //println!("Inputting {} to address {}", input, result_address); mem::replace(&mut intcode[result_address], input); *ptr = *ptr + 2; } fn output(intcode: &mut Vec<i32>, ptr: &mut usize, opcode: i32, output_fn: fn(i32) -> ()) { let parameter_modes = modes_from_opcode(opcode, 1); let output = value_from_parameter(parameter_modes[0], intcode, *ptr + 1); //let result_address: usize = intcode[*ptr + 1] as usize; //println!("Outputting {} from address {}", output, result_address); output_fn(output); *ptr = *ptr + 2; } fn jump_if_true(intcode: &mut Vec<i32>, ptr: &mut usize, opcode: i32) { let parameter_modes = modes_from_opcode(opcode, 2); let value1: i32 = value_from_parameter(parameter_modes[0], intcode, *ptr + 1); let value2: i32 = value_from_parameter(parameter_modes[1], intcode, *ptr + 2); //println!("Jump if true: Value1 {}, Value2: {}, intcode: {:?}", value1, value2, intcode); if value1 != 0 { *ptr = value2 as usize; } else { *ptr += 3; } } fn jump_if_false(intcode: &mut Vec<i32>, ptr: &mut usize, opcode: i32) { let parameter_modes = modes_from_opcode(opcode, 2); let value1: i32 = value_from_parameter(parameter_modes[0], intcode, *ptr + 1); let value2: i32 = value_from_parameter(parameter_modes[1], intcode, *ptr + 2); //println!("Jump if false: Value1 {}, Value2: {}, intcode: {:?}", value1, value2, intcode); if value1 == 0 { *ptr = value2 as usize; } else { *ptr += 3; } } fn less_then(intcode: &mut Vec<i32>, ptr: &mut usize, opcode: i32) { let parameter_modes = modes_from_opcode(opcode, 3); let value1: i32 = value_from_parameter(parameter_modes[0], intcode, *ptr + 1); let value2: i32 = value_from_parameter(parameter_modes[1], intcode, *ptr + 2); let value3: usize = intcode[*ptr + 3] as usize; //println!("Less than: Value1 {}, Value2: {}, Value3: {}, intcode: {:?}", value1, value2, value3, intcode); if value1 < value2 { mem::replace(&mut intcode[value3], 1); } else { mem::replace(&mut intcode[value3], 0); } *ptr = *ptr + 4; } fn equals(intcode: &mut Vec<i32>, ptr: &mut usize, opcode: i32) { let parameter_modes = modes_from_opcode(opcode, 3); let value1: i32 = value_from_parameter(parameter_modes[0], intcode, *ptr + 1); let value2: i32 = value_from_parameter(parameter_modes[1], intcode, *ptr + 2); let value3: usize = intcode[*ptr + 3] as usize; //println!("Equals: Value1 {}, Value2: {}, Value 3: {}, intcode: {:?}", value1, value2, value3, intcode); if value1 == value2 { mem::replace(&mut intcode[value3], 1); } else { mem::replace(&mut intcode[value3], 0); } *ptr = *ptr + 4; } fn modes_from_opcode(opcode: i32, parameters: usize) -> Vec<i32> { let params = opcode / 100; let mut results = vec![]; let base: i32 = 10; for i in 0..parameters { let power = (i + 1) as u32; results.push((params % base.pow(power)) / base.pow(power-1)); } return results; } fn value_from_parameter(parameter: i32, intcode: &Vec<i32>, ptr: usize) -> i32 { return match parameter { 0 => { let value_at_pointer = intcode[ptr]; assert!(value_at_pointer >= 0); intcode[value_at_pointer as usize] }, 1 => intcode[ptr], _ => panic!("parameter value {} not understood", parameter) }; } #[cfg(test)] mod tests { use super::*; #[test] fn test_run_intcode_example1() { let intcode: Vec<i32> = vec![1,0,0,0,99]; let end = vec![2,0,0,0,99]; assert_eq!(run_intcode(intcode, || 0, |_| ()), end); } #[test] fn test_run_intcode_example2() { let intcode: Vec<i32> = vec![2,3,0,3,99]; let end = vec![2,3,0,6,99]; assert_eq!(run_intcode(intcode, || 0, |_| ()), end); } #[test] fn test_run_intcode_example3() { let intcode: Vec<i32> = vec![2,4,4,5,99,0]; let end = vec![2,4,4,5,99,9801]; assert_eq!(run_intcode(intcode, || 0, |_| ()), end); } #[test] fn test_run_intcode_example4() { let intcode: Vec<i32> = vec![1,1,1,4,99,5,6,0,99]; let end = vec![30,1,1,4,2,5,6,0,99]; assert_eq!(run_intcode(intcode, || 0, |_| ()), end); } #[test] fn test_operation_from_opcode() { let opcode = 1002; assert_eq!(operation_from_opcode(opcode), 2); } #[test] fn test_modes_from_opcode() { let opcode = 11002; let parameters = 3; assert_eq!(modes_from_opcode(opcode, parameters), vec![0, 1, 1]); let opcode = 01002; let parameters = 3; assert_eq!(modes_from_opcode(opcode, parameters), vec![0, 1, 0]); } #[test] fn test_values_from_parameters() { let intcode: Vec<i32> = vec![1002,4,3,4,33]; let ptr = 1; let parameters: Vec<i32> = vec![0, 1, 0]; let expected = vec![33, 3, 33]; for (index, param) in parameters.iter().enumerate() { assert_eq!( value_from_parameter(*param, &intcode, ptr + index), expected[index], "\nFailed at index {} on value {}\n\n", index, param); } } #[test] fn test_add() { let mut intcode: Vec<i32> = vec![1001,4,3,4,33]; let opcode = intcode[0]; let mut ptr = 0; let expected = vec![1001,4,3,4,36]; add(&mut intcode, &mut ptr, opcode); assert_eq!(intcode, expected); assert_eq!(ptr, 4); } #[test] fn test_multiply() { let mut intcode: Vec<i32> = vec![1002,4,3,4,33]; let opcode = intcode[0]; let mut ptr = 0; let expected = vec![1002,4,3,4,99]; multiply(&mut intcode, &mut ptr, opcode); assert_eq!(intcode, expected); assert_eq!(ptr, 4); } #[test] fn test_input() { let mut intcode: Vec<i32> = vec![3,5,0,0,0,0]; let opcode = intcode[0]; let mut ptr = 0; let expected = vec![3,5,0,0,0,44]; let input_fn = || 44; input(&mut intcode, &mut ptr, opcode, input_fn); assert_eq!(intcode, expected); assert_eq!(ptr, 2); } #[test] fn test_input_example1() { let mut intcode: Vec<i32> = vec![3,9,8,9,10,9,4,9,99,-1,8]; let opcode = intcode[0]; let mut ptr = 0; let expected = vec![3,9,8,9,10,9,4,9,99,8,8]; let input_fn = || 8; input(&mut intcode, &mut ptr, opcode, input_fn); assert_eq!(intcode, expected); assert_eq!(ptr, 2); } #[test] fn test_output() { let mut intcode: Vec<i32> = vec![4,5,0,0,0,33]; let opcode = intcode[0]; let mut ptr = 0; let expected = vec![4,5,0,0,0,33]; let output_fn = |x| -> () { assert_eq!(x, 33); () }; output(&mut intcode, &mut ptr, opcode, output_fn); assert_eq!(intcode, expected); assert_eq!(ptr, 2); } #[test] fn test_jump_if_true_mode_position_is_true() { let mut intcode: Vec<i32> = vec![5,3,6,2,0,33,12]; let opcode = intcode[0]; let mut ptr = 0; let expected = 12; jump_if_true(&mut intcode, &mut ptr, opcode); assert_eq!(ptr, expected); } #[test] fn test_jump_if_true_mode_immidiate_is_true() { let mut intcode: Vec<i32> = vec![1105,1,6,0,0,33,12]; let opcode = intcode[0]; let mut ptr = 0; let expected = 6; jump_if_true(&mut intcode, &mut ptr, opcode); assert_eq!(ptr, expected); } #[test] fn test_jump_if_true_example6() { let mut intcode: Vec<i32> = vec![3,3,1105,-1,9,1101,0,0,12,4,12,99,1]; let opcode = intcode[2]; let mut ptr = 2; let expected = 9; jump_if_true(&mut intcode, &mut ptr, opcode); assert_eq!(ptr, expected); } #[test] fn test_jump_if_false_mode_position_is_false() { let mut intcode: Vec<i32> = vec![6,3,6,0,0,33,12]; let opcode = intcode[0]; let mut ptr = 0; let expected = 12; jump_if_false(&mut intcode, &mut ptr, opcode); assert_eq!(ptr, expected); } #[test] fn test_jump_if_false_mode_immidiate_is_false() { let mut intcode: Vec<i32> = vec![1106,0,6,0,0,33]; let opcode = intcode[0]; let mut ptr = 0; let expected = 6; jump_if_false(&mut intcode, &mut ptr, opcode); assert_eq!(ptr, expected); } #[test] fn test_less_than_mode_position() { let mut intcode: Vec<i32> = vec![7,4,5,6,6,7,7,24]; let opcode = intcode[0]; let mut ptr = 0; let expected = vec![7,4,5,6,6,7,1,24]; let expected_ptr = 4; less_then(&mut intcode, &mut ptr, opcode); assert_eq!(intcode, expected); assert_eq!(ptr, expected_ptr, "\nPointer is incorrect\n"); } #[test] fn test_less_than_mode_immidiate() { let mut intcode: Vec<i32> = vec![11107,3,6,5,5,33]; let opcode = intcode[0]; let mut ptr = 0; let expected = vec![11107,3,6,5,5,1]; let expected_ptr = 4; less_then(&mut intcode, &mut ptr, opcode); assert_eq!(intcode, expected); assert_eq!(ptr, expected_ptr); } #[test] fn test_equals_example1() { let mut intcode: Vec<i32> = vec![3,9,8,9,10,9,4,9,99,8,8]; let opcode = intcode[2]; let mut ptr = 2; let expected = vec![3,9,8,9,10,9,4,9,99,1,8]; let expected_ptr = 6; equals(&mut intcode, &mut ptr, opcode); assert_eq!(intcode, expected); assert_eq!(ptr, expected_ptr); } #[test] fn test_part2_example1() { let intcode: Vec<i32> = vec![3,9,8,9,10,9,4,9,99,-1,8]; let input_fn = || { 8 }; let output_fn = |x| assert_eq!(x, 1); run_intcode(intcode.to_vec(), input_fn, output_fn); let input_fn = || { 7 }; let output_fn = |x| assert_eq!(x, 0); run_intcode(intcode.to_vec(), input_fn, output_fn); } #[test] fn test_part2_example2() { let intcode: Vec<i32> = vec![3,9,7,9,10,9,4,9,99,-1,8]; let input_fn = || { 7 }; let output_fn = |x| assert_eq!(x, 1); run_intcode(intcode.to_vec(), input_fn, output_fn); let input_fn = || { 8 }; let output_fn = |x| assert_eq!(x, 0); run_intcode(intcode.to_vec(), input_fn, output_fn); } #[test] fn test_part2_example3() { let intcode: Vec<i32> = vec![3,3,1108,-1,8,3,4,3,99]; let input_fn = || { 8 }; let output_fn = |x| assert_eq!(x, 1); run_intcode(intcode.to_vec(), input_fn, output_fn); let input_fn = || { 9 }; let output_fn = |x| assert_eq!(x, 0); run_intcode(intcode.to_vec(), input_fn, output_fn); } #[test] fn test_part2_example4() { let intcode: Vec<i32> = vec![3,3,1107,-1,8,3,4,3,99]; let input_fn = || { 3 }; let output_fn = |x| assert_eq!(x, 1); run_intcode(intcode.to_vec(), input_fn, output_fn); let input_fn = || { 8 }; let output_fn = |x| assert_eq!(x, 0); run_intcode(intcode.to_vec(), input_fn, output_fn); } #[test] fn test_part2_example5() { let intcode: Vec<i32> = vec![3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]; let input_fn = || { 0 }; let output_fn = |x| assert_eq!(x, 0); run_intcode(intcode.to_vec(), input_fn, output_fn); let input_fn = || { 8 }; let output_fn = |x| assert_eq!(x, 1); run_intcode(intcode.to_vec(), input_fn, output_fn); } #[test] fn test_part2_example6() { let intcode: Vec<i32> = vec![3,3,1105,-1,9,1101,0,0,12,4,12,99,1]; let input_fn = || { 0 }; let output_fn = |x| assert_eq!(x, 0); run_intcode(intcode.to_vec(), input_fn, output_fn); let input_fn = || { 8 }; let output_fn = |x| assert_eq!(x, 1); run_intcode(intcode.to_vec(), input_fn, output_fn); } #[test] fn test_part2_example7() { let intcode: Vec<i32> = vec![3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31, 1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104, 999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99]; let input_fn = || { 0 }; let output_fn = |x| assert_eq!(x, 999); run_intcode(intcode.to_vec(), input_fn, output_fn); let input_fn = || { 8 }; let output_fn = |x| assert_eq!(x, 1000); run_intcode(intcode.to_vec(), input_fn, output_fn); let input_fn = || { 26 }; let output_fn = |x| assert_eq!(x, 1001); run_intcode(intcode.to_vec(), input_fn, output_fn); } }
#[doc = "Register `FLTINR1` reader"] pub type R = crate::R<FLTINR1_SPEC>; #[doc = "Register `FLTINR1` writer"] pub type W = crate::W<FLTINR1_SPEC>; #[doc = "Field `FLT1E` reader - FLT1E"] pub type FLT1E_R = crate::BitReader<FLT1E_A>; #[doc = "FLT1E\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FLT1E_A { #[doc = "0: Fault input disabled"] Disabled = 0, #[doc = "1: Fault input enabled"] Enabled = 1, } impl From<FLT1E_A> for bool { #[inline(always)] fn from(variant: FLT1E_A) -> Self { variant as u8 != 0 } } impl FLT1E_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FLT1E_A { match self.bits { false => FLT1E_A::Disabled, true => FLT1E_A::Enabled, } } #[doc = "Fault input disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == FLT1E_A::Disabled } #[doc = "Fault input enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == FLT1E_A::Enabled } } #[doc = "Field `FLT1E` writer - FLT1E"] pub type FLT1E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FLT1E_A>; impl<'a, REG, const O: u8> FLT1E_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Fault input disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(FLT1E_A::Disabled) } #[doc = "Fault input enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(FLT1E_A::Enabled) } } #[doc = "Field `FLT1P` reader - FLT1P"] pub type FLT1P_R = crate::BitReader<FLT1P_A>; #[doc = "FLT1P\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FLT1P_A { #[doc = "0: Fault input is active low"] ActiveLow = 0, #[doc = "1: Fault input is active high"] ActiveHigh = 1, } impl From<FLT1P_A> for bool { #[inline(always)] fn from(variant: FLT1P_A) -> Self { variant as u8 != 0 } } impl FLT1P_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FLT1P_A { match self.bits { false => FLT1P_A::ActiveLow, true => FLT1P_A::ActiveHigh, } } #[doc = "Fault input is active low"] #[inline(always)] pub fn is_active_low(&self) -> bool { *self == FLT1P_A::ActiveLow } #[doc = "Fault input is active high"] #[inline(always)] pub fn is_active_high(&self) -> bool { *self == FLT1P_A::ActiveHigh } } #[doc = "Field `FLT1P` writer - FLT1P"] pub type FLT1P_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FLT1P_A>; impl<'a, REG, const O: u8> FLT1P_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Fault input is active low"] #[inline(always)] pub fn active_low(self) -> &'a mut crate::W<REG> { self.variant(FLT1P_A::ActiveLow) } #[doc = "Fault input is active high"] #[inline(always)] pub fn active_high(self) -> &'a mut crate::W<REG> { self.variant(FLT1P_A::ActiveHigh) } } #[doc = "Field `FLT1SRC` reader - FLT1SRC"] pub type FLT1SRC_R = crate::BitReader<FLT1SRC_A>; #[doc = "FLT1SRC\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FLT1SRC_A { #[doc = "0: Fault input is FLTx input pin"] Input = 0, #[doc = "1: Fault input is FLTn_Int signal"] Internal = 1, } impl From<FLT1SRC_A> for bool { #[inline(always)] fn from(variant: FLT1SRC_A) -> Self { variant as u8 != 0 } } impl FLT1SRC_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FLT1SRC_A { match self.bits { false => FLT1SRC_A::Input, true => FLT1SRC_A::Internal, } } #[doc = "Fault input is FLTx input pin"] #[inline(always)] pub fn is_input(&self) -> bool { *self == FLT1SRC_A::Input } #[doc = "Fault input is FLTn_Int signal"] #[inline(always)] pub fn is_internal(&self) -> bool { *self == FLT1SRC_A::Internal } } #[doc = "Field `FLT1SRC` writer - FLT1SRC"] pub type FLT1SRC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FLT1SRC_A>; impl<'a, REG, const O: u8> FLT1SRC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Fault input is FLTx input pin"] #[inline(always)] pub fn input(self) -> &'a mut crate::W<REG> { self.variant(FLT1SRC_A::Input) } #[doc = "Fault input is FLTn_Int signal"] #[inline(always)] pub fn internal(self) -> &'a mut crate::W<REG> { self.variant(FLT1SRC_A::Internal) } } #[doc = "Field `FLT1F` reader - FLT1F"] pub type FLT1F_R = crate::FieldReader<FLT1F_A>; #[doc = "FLT1F\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum FLT1F_A { #[doc = "0: No filter, FLTx acts asynchronously"] Disabled = 0, #[doc = "1: f_SAMPLING=f_HRTIM, N=2"] Div1N2 = 1, #[doc = "2: f_SAMPLING=f_HRTIM, N=4"] Div1N4 = 2, #[doc = "3: f_SAMPLING=f_HRTIM, N=8"] Div1N8 = 3, #[doc = "4: f_SAMPLING=f_HRTIM/2, N=6"] Div2N6 = 4, #[doc = "5: f_SAMPLING=f_HRTIM/2, N=8"] Div2N8 = 5, #[doc = "6: f_SAMPLING=f_HRTIM/4, N=6"] Div4N6 = 6, #[doc = "7: f_SAMPLING=f_HRTIM/4, N=8"] Div4N8 = 7, #[doc = "8: f_SAMPLING=f_HRTIM/8, N=6"] Div8N6 = 8, #[doc = "9: f_SAMPLING=f_HRTIM/8, N=8"] Div8N8 = 9, #[doc = "10: f_SAMPLING=f_HRTIM/16, N=5"] Div16N5 = 10, #[doc = "11: f_SAMPLING=f_HRTIM/16, N=6"] Div16N6 = 11, #[doc = "12: f_SAMPLING=f_HRTIM/16, N=8"] Div16N8 = 12, #[doc = "13: f_SAMPLING=f_HRTIM/32, N=5"] Div32N5 = 13, #[doc = "14: f_SAMPLING=f_HRTIM/32, N=6"] Div32N6 = 14, #[doc = "15: f_SAMPLING=f_HRTIM/32, N=8"] Div32N8 = 15, } impl From<FLT1F_A> for u8 { #[inline(always)] fn from(variant: FLT1F_A) -> Self { variant as _ } } impl crate::FieldSpec for FLT1F_A { type Ux = u8; } impl FLT1F_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FLT1F_A { match self.bits { 0 => FLT1F_A::Disabled, 1 => FLT1F_A::Div1N2, 2 => FLT1F_A::Div1N4, 3 => FLT1F_A::Div1N8, 4 => FLT1F_A::Div2N6, 5 => FLT1F_A::Div2N8, 6 => FLT1F_A::Div4N6, 7 => FLT1F_A::Div4N8, 8 => FLT1F_A::Div8N6, 9 => FLT1F_A::Div8N8, 10 => FLT1F_A::Div16N5, 11 => FLT1F_A::Div16N6, 12 => FLT1F_A::Div16N8, 13 => FLT1F_A::Div32N5, 14 => FLT1F_A::Div32N6, 15 => FLT1F_A::Div32N8, _ => unreachable!(), } } #[doc = "No filter, FLTx acts asynchronously"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == FLT1F_A::Disabled } #[doc = "f_SAMPLING=f_HRTIM, N=2"] #[inline(always)] pub fn is_div1_n2(&self) -> bool { *self == FLT1F_A::Div1N2 } #[doc = "f_SAMPLING=f_HRTIM, N=4"] #[inline(always)] pub fn is_div1_n4(&self) -> bool { *self == FLT1F_A::Div1N4 } #[doc = "f_SAMPLING=f_HRTIM, N=8"] #[inline(always)] pub fn is_div1_n8(&self) -> bool { *self == FLT1F_A::Div1N8 } #[doc = "f_SAMPLING=f_HRTIM/2, N=6"] #[inline(always)] pub fn is_div2_n6(&self) -> bool { *self == FLT1F_A::Div2N6 } #[doc = "f_SAMPLING=f_HRTIM/2, N=8"] #[inline(always)] pub fn is_div2_n8(&self) -> bool { *self == FLT1F_A::Div2N8 } #[doc = "f_SAMPLING=f_HRTIM/4, N=6"] #[inline(always)] pub fn is_div4_n6(&self) -> bool { *self == FLT1F_A::Div4N6 } #[doc = "f_SAMPLING=f_HRTIM/4, N=8"] #[inline(always)] pub fn is_div4_n8(&self) -> bool { *self == FLT1F_A::Div4N8 } #[doc = "f_SAMPLING=f_HRTIM/8, N=6"] #[inline(always)] pub fn is_div8_n6(&self) -> bool { *self == FLT1F_A::Div8N6 } #[doc = "f_SAMPLING=f_HRTIM/8, N=8"] #[inline(always)] pub fn is_div8_n8(&self) -> bool { *self == FLT1F_A::Div8N8 } #[doc = "f_SAMPLING=f_HRTIM/16, N=5"] #[inline(always)] pub fn is_div16_n5(&self) -> bool { *self == FLT1F_A::Div16N5 } #[doc = "f_SAMPLING=f_HRTIM/16, N=6"] #[inline(always)] pub fn is_div16_n6(&self) -> bool { *self == FLT1F_A::Div16N6 } #[doc = "f_SAMPLING=f_HRTIM/16, N=8"] #[inline(always)] pub fn is_div16_n8(&self) -> bool { *self == FLT1F_A::Div16N8 } #[doc = "f_SAMPLING=f_HRTIM/32, N=5"] #[inline(always)] pub fn is_div32_n5(&self) -> bool { *self == FLT1F_A::Div32N5 } #[doc = "f_SAMPLING=f_HRTIM/32, N=6"] #[inline(always)] pub fn is_div32_n6(&self) -> bool { *self == FLT1F_A::Div32N6 } #[doc = "f_SAMPLING=f_HRTIM/32, N=8"] #[inline(always)] pub fn is_div32_n8(&self) -> bool { *self == FLT1F_A::Div32N8 } } #[doc = "Field `FLT1F` writer - FLT1F"] pub type FLT1F_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O, FLT1F_A>; impl<'a, REG, const O: u8> FLT1F_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "No filter, FLTx acts asynchronously"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Disabled) } #[doc = "f_SAMPLING=f_HRTIM, N=2"] #[inline(always)] pub fn div1_n2(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div1N2) } #[doc = "f_SAMPLING=f_HRTIM, N=4"] #[inline(always)] pub fn div1_n4(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div1N4) } #[doc = "f_SAMPLING=f_HRTIM, N=8"] #[inline(always)] pub fn div1_n8(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div1N8) } #[doc = "f_SAMPLING=f_HRTIM/2, N=6"] #[inline(always)] pub fn div2_n6(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div2N6) } #[doc = "f_SAMPLING=f_HRTIM/2, N=8"] #[inline(always)] pub fn div2_n8(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div2N8) } #[doc = "f_SAMPLING=f_HRTIM/4, N=6"] #[inline(always)] pub fn div4_n6(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div4N6) } #[doc = "f_SAMPLING=f_HRTIM/4, N=8"] #[inline(always)] pub fn div4_n8(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div4N8) } #[doc = "f_SAMPLING=f_HRTIM/8, N=6"] #[inline(always)] pub fn div8_n6(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div8N6) } #[doc = "f_SAMPLING=f_HRTIM/8, N=8"] #[inline(always)] pub fn div8_n8(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div8N8) } #[doc = "f_SAMPLING=f_HRTIM/16, N=5"] #[inline(always)] pub fn div16_n5(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div16N5) } #[doc = "f_SAMPLING=f_HRTIM/16, N=6"] #[inline(always)] pub fn div16_n6(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div16N6) } #[doc = "f_SAMPLING=f_HRTIM/16, N=8"] #[inline(always)] pub fn div16_n8(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div16N8) } #[doc = "f_SAMPLING=f_HRTIM/32, N=5"] #[inline(always)] pub fn div32_n5(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div32N5) } #[doc = "f_SAMPLING=f_HRTIM/32, N=6"] #[inline(always)] pub fn div32_n6(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div32N6) } #[doc = "f_SAMPLING=f_HRTIM/32, N=8"] #[inline(always)] pub fn div32_n8(self) -> &'a mut crate::W<REG> { self.variant(FLT1F_A::Div32N8) } } #[doc = "Field `FLT1LCK` reader - FLT1LCK"] pub type FLT1LCK_R = crate::BitReader<FLT1LCKR_A>; #[doc = "FLT1LCK\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FLT1LCKR_A { #[doc = "0: Fault bits are read/write"] Unlocked = 0, #[doc = "1: Fault bits are read-only"] Locked = 1, } impl From<FLT1LCKR_A> for bool { #[inline(always)] fn from(variant: FLT1LCKR_A) -> Self { variant as u8 != 0 } } impl FLT1LCK_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FLT1LCKR_A { match self.bits { false => FLT1LCKR_A::Unlocked, true => FLT1LCKR_A::Locked, } } #[doc = "Fault bits are read/write"] #[inline(always)] pub fn is_unlocked(&self) -> bool { *self == FLT1LCKR_A::Unlocked } #[doc = "Fault bits are read-only"] #[inline(always)] pub fn is_locked(&self) -> bool { *self == FLT1LCKR_A::Locked } } #[doc = "FLT1LCK\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FLT1LCKW_AW { #[doc = "1: Lock corresponding fault bits"] Lock = 1, } impl From<FLT1LCKW_AW> for bool { #[inline(always)] fn from(variant: FLT1LCKW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `FLT1LCK` writer - FLT1LCK"] pub type FLT1LCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FLT1LCKW_AW>; impl<'a, REG, const O: u8> FLT1LCK_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Lock corresponding fault bits"] #[inline(always)] pub fn lock(self) -> &'a mut crate::W<REG> { self.variant(FLT1LCKW_AW::Lock) } } #[doc = "Field `FLT2E` reader - FLT2E"] pub use FLT1E_R as FLT2E_R; #[doc = "Field `FLT3E` reader - FLT3E"] pub use FLT1E_R as FLT3E_R; #[doc = "Field `FLT4E` reader - FLT4E"] pub use FLT1E_R as FLT4E_R; #[doc = "Field `FLT2E` writer - FLT2E"] pub use FLT1E_W as FLT2E_W; #[doc = "Field `FLT3E` writer - FLT3E"] pub use FLT1E_W as FLT3E_W; #[doc = "Field `FLT4E` writer - FLT4E"] pub use FLT1E_W as FLT4E_W; #[doc = "Field `FLT2F` reader - FLT2F"] pub use FLT1F_R as FLT2F_R; #[doc = "Field `FLT3F` reader - FLT3F"] pub use FLT1F_R as FLT3F_R; #[doc = "Field `FLT4F` reader - FLT4F"] pub use FLT1F_R as FLT4F_R; #[doc = "Field `FLT2F` writer - FLT2F"] pub use FLT1F_W as FLT2F_W; #[doc = "Field `FLT3F` writer - FLT3F"] pub use FLT1F_W as FLT3F_W; #[doc = "Field `FLT4F` writer - FLT4F"] pub use FLT1F_W as FLT4F_W; #[doc = "Field `FLT2LCK` reader - FLT2LCK"] pub use FLT1LCK_R as FLT2LCK_R; #[doc = "Field `FLT3LCK` reader - FLT3LCK"] pub use FLT1LCK_R as FLT3LCK_R; #[doc = "Field `FLT4LCK` reader - FLT4LCK"] pub use FLT1LCK_R as FLT4LCK_R; #[doc = "Field `FLT2LCK` writer - FLT2LCK"] pub use FLT1LCK_W as FLT2LCK_W; #[doc = "Field `FLT3LCK` writer - FLT3LCK"] pub use FLT1LCK_W as FLT3LCK_W; #[doc = "Field `FLT4LCK` writer - FLT4LCK"] pub use FLT1LCK_W as FLT4LCK_W; #[doc = "Field `FLT2P` reader - FLT2P"] pub use FLT1P_R as FLT2P_R; #[doc = "Field `FLT3P` reader - FLT3P"] pub use FLT1P_R as FLT3P_R; #[doc = "Field `FLT4P` reader - FLT4P"] pub use FLT1P_R as FLT4P_R; #[doc = "Field `FLT2P` writer - FLT2P"] pub use FLT1P_W as FLT2P_W; #[doc = "Field `FLT3P` writer - FLT3P"] pub use FLT1P_W as FLT3P_W; #[doc = "Field `FLT4P` writer - FLT4P"] pub use FLT1P_W as FLT4P_W; #[doc = "Field `FLT2SRC` reader - FLT2SRC"] pub use FLT1SRC_R as FLT2SRC_R; #[doc = "Field `FLT3SRC` reader - FLT3SRC"] pub use FLT1SRC_R as FLT3SRC_R; #[doc = "Field `FLT4SRC` reader - FLT4SRC"] pub use FLT1SRC_R as FLT4SRC_R; #[doc = "Field `FLT2SRC` writer - FLT2SRC"] pub use FLT1SRC_W as FLT2SRC_W; #[doc = "Field `FLT3SRC` writer - FLT3SRC"] pub use FLT1SRC_W as FLT3SRC_W; #[doc = "Field `FLT4SRC` writer - FLT4SRC"] pub use FLT1SRC_W as FLT4SRC_W; impl R { #[doc = "Bit 0 - FLT1E"] #[inline(always)] pub fn flt1e(&self) -> FLT1E_R { FLT1E_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - FLT1P"] #[inline(always)] pub fn flt1p(&self) -> FLT1P_R { FLT1P_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - FLT1SRC"] #[inline(always)] pub fn flt1src(&self) -> FLT1SRC_R { FLT1SRC_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bits 3:6 - FLT1F"] #[inline(always)] pub fn flt1f(&self) -> FLT1F_R { FLT1F_R::new(((self.bits >> 3) & 0x0f) as u8) } #[doc = "Bit 7 - FLT1LCK"] #[inline(always)] pub fn flt1lck(&self) -> FLT1LCK_R { FLT1LCK_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - FLT2E"] #[inline(always)] pub fn flt2e(&self) -> FLT2E_R { FLT2E_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - FLT2P"] #[inline(always)] pub fn flt2p(&self) -> FLT2P_R { FLT2P_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - FLT2SRC"] #[inline(always)] pub fn flt2src(&self) -> FLT2SRC_R { FLT2SRC_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bits 11:14 - FLT2F"] #[inline(always)] pub fn flt2f(&self) -> FLT2F_R { FLT2F_R::new(((self.bits >> 11) & 0x0f) as u8) } #[doc = "Bit 15 - FLT2LCK"] #[inline(always)] pub fn flt2lck(&self) -> FLT2LCK_R { FLT2LCK_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - FLT3E"] #[inline(always)] pub fn flt3e(&self) -> FLT3E_R { FLT3E_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - FLT3P"] #[inline(always)] pub fn flt3p(&self) -> FLT3P_R { FLT3P_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - FLT3SRC"] #[inline(always)] pub fn flt3src(&self) -> FLT3SRC_R { FLT3SRC_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bits 19:22 - FLT3F"] #[inline(always)] pub fn flt3f(&self) -> FLT3F_R { FLT3F_R::new(((self.bits >> 19) & 0x0f) as u8) } #[doc = "Bit 23 - FLT3LCK"] #[inline(always)] pub fn flt3lck(&self) -> FLT3LCK_R { FLT3LCK_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - FLT4E"] #[inline(always)] pub fn flt4e(&self) -> FLT4E_R { FLT4E_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - FLT4P"] #[inline(always)] pub fn flt4p(&self) -> FLT4P_R { FLT4P_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - FLT4SRC"] #[inline(always)] pub fn flt4src(&self) -> FLT4SRC_R { FLT4SRC_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bits 27:30 - FLT4F"] #[inline(always)] pub fn flt4f(&self) -> FLT4F_R { FLT4F_R::new(((self.bits >> 27) & 0x0f) as u8) } #[doc = "Bit 31 - FLT4LCK"] #[inline(always)] pub fn flt4lck(&self) -> FLT4LCK_R { FLT4LCK_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - FLT1E"] #[inline(always)] #[must_use] pub fn flt1e(&mut self) -> FLT1E_W<FLTINR1_SPEC, 0> { FLT1E_W::new(self) } #[doc = "Bit 1 - FLT1P"] #[inline(always)] #[must_use] pub fn flt1p(&mut self) -> FLT1P_W<FLTINR1_SPEC, 1> { FLT1P_W::new(self) } #[doc = "Bit 2 - FLT1SRC"] #[inline(always)] #[must_use] pub fn flt1src(&mut self) -> FLT1SRC_W<FLTINR1_SPEC, 2> { FLT1SRC_W::new(self) } #[doc = "Bits 3:6 - FLT1F"] #[inline(always)] #[must_use] pub fn flt1f(&mut self) -> FLT1F_W<FLTINR1_SPEC, 3> { FLT1F_W::new(self) } #[doc = "Bit 7 - FLT1LCK"] #[inline(always)] #[must_use] pub fn flt1lck(&mut self) -> FLT1LCK_W<FLTINR1_SPEC, 7> { FLT1LCK_W::new(self) } #[doc = "Bit 8 - FLT2E"] #[inline(always)] #[must_use] pub fn flt2e(&mut self) -> FLT2E_W<FLTINR1_SPEC, 8> { FLT2E_W::new(self) } #[doc = "Bit 9 - FLT2P"] #[inline(always)] #[must_use] pub fn flt2p(&mut self) -> FLT2P_W<FLTINR1_SPEC, 9> { FLT2P_W::new(self) } #[doc = "Bit 10 - FLT2SRC"] #[inline(always)] #[must_use] pub fn flt2src(&mut self) -> FLT2SRC_W<FLTINR1_SPEC, 10> { FLT2SRC_W::new(self) } #[doc = "Bits 11:14 - FLT2F"] #[inline(always)] #[must_use] pub fn flt2f(&mut self) -> FLT2F_W<FLTINR1_SPEC, 11> { FLT2F_W::new(self) } #[doc = "Bit 15 - FLT2LCK"] #[inline(always)] #[must_use] pub fn flt2lck(&mut self) -> FLT2LCK_W<FLTINR1_SPEC, 15> { FLT2LCK_W::new(self) } #[doc = "Bit 16 - FLT3E"] #[inline(always)] #[must_use] pub fn flt3e(&mut self) -> FLT3E_W<FLTINR1_SPEC, 16> { FLT3E_W::new(self) } #[doc = "Bit 17 - FLT3P"] #[inline(always)] #[must_use] pub fn flt3p(&mut self) -> FLT3P_W<FLTINR1_SPEC, 17> { FLT3P_W::new(self) } #[doc = "Bit 18 - FLT3SRC"] #[inline(always)] #[must_use] pub fn flt3src(&mut self) -> FLT3SRC_W<FLTINR1_SPEC, 18> { FLT3SRC_W::new(self) } #[doc = "Bits 19:22 - FLT3F"] #[inline(always)] #[must_use] pub fn flt3f(&mut self) -> FLT3F_W<FLTINR1_SPEC, 19> { FLT3F_W::new(self) } #[doc = "Bit 23 - FLT3LCK"] #[inline(always)] #[must_use] pub fn flt3lck(&mut self) -> FLT3LCK_W<FLTINR1_SPEC, 23> { FLT3LCK_W::new(self) } #[doc = "Bit 24 - FLT4E"] #[inline(always)] #[must_use] pub fn flt4e(&mut self) -> FLT4E_W<FLTINR1_SPEC, 24> { FLT4E_W::new(self) } #[doc = "Bit 25 - FLT4P"] #[inline(always)] #[must_use] pub fn flt4p(&mut self) -> FLT4P_W<FLTINR1_SPEC, 25> { FLT4P_W::new(self) } #[doc = "Bit 26 - FLT4SRC"] #[inline(always)] #[must_use] pub fn flt4src(&mut self) -> FLT4SRC_W<FLTINR1_SPEC, 26> { FLT4SRC_W::new(self) } #[doc = "Bits 27:30 - FLT4F"] #[inline(always)] #[must_use] pub fn flt4f(&mut self) -> FLT4F_W<FLTINR1_SPEC, 27> { FLT4F_W::new(self) } #[doc = "Bit 31 - FLT4LCK"] #[inline(always)] #[must_use] pub fn flt4lck(&mut self) -> FLT4LCK_W<FLTINR1_SPEC, 31> { FLT4LCK_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "HRTIM Fault Input Register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fltinr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fltinr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FLTINR1_SPEC; impl crate::RegisterSpec for FLTINR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fltinr1::R`](R) reader structure"] impl crate::Readable for FLTINR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`fltinr1::W`](W) writer structure"] impl crate::Writable for FLTINR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets FLTINR1 to value 0"] impl crate::Resettable for FLTINR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
// In this file are all the helper functions used by the UI when decoding Loc PackedFiles. extern crate gtk; extern crate gio; extern crate failure; use std::cell::RefCell; use std::rc::Rc; use failure::Error; use gio::prelude::*; use gio::SimpleAction; use gtk::prelude::*; use gtk::{ TreeView, ListStore, ScrolledWindow, Popover, Entry, ModelButton, FileChooserAction, CellRendererText, TreeViewColumn, CellRendererToggle, Separator, Orientation, Grid, TreeViewColumnSizing, TreeViewGridLines, EntryIconPosition, Application }; use packfile::update_packed_file_data_loc; use settings::*; use ui::*; use AppUI; use packedfile::SerializableToTSV; /// Struct `PackedFileLocTreeView`: contains all the stuff we need to give to the program to show a /// `TreeView` with the data of a Loc PackedFile, allowing us to manipulate it. #[derive(Clone)] pub struct PackedFileLocTreeView { pub tree_view: TreeView, pub list_store: ListStore, pub cell_key: CellRendererText, pub cell_text: CellRendererText, pub cell_tooltip: CellRendererToggle, pub context_menu: Popover, pub add_rows_entry: Entry, } /// Implementation of `PackedFileLocTreeView`. impl PackedFileLocTreeView{ /// This function creates a new `TreeView` with `packed_file_data_display` as father and returns a /// `PackedFileLocTreeView` with all his data. pub fn create_tree_view( application: &Application, app_ui: &AppUI, pack_file: &Rc<RefCell<PackFile>>, packed_file_decoded_index: &usize, is_packedfile_opened: &Rc<RefCell<bool>>, settings: &Settings ) -> Result<(), Error> { // Here we define the `Accept` response for GTK, as it seems Restson causes it to fail to compile // if we get them to i32 directly in the `if` statement. // NOTE: For some bizarre reason, GTKFileChoosers return `Ok`, while native ones return `Accept`. let gtk_response_accept: i32 = ResponseType::Accept.into(); // Get the table's path, so we can use it despite changing the selected file in the main TreeView. let tree_path = get_tree_path_from_selection(&app_ui.folder_tree_selection, false); // We try to decode it as a Loc PackedFile. match Loc::read(&*pack_file.borrow().data.packed_files[*packed_file_decoded_index].data) { // If we succeed... Ok(packed_file_decoded) => { // We create the new `TreeView` and his `ListStore`. let tree_view = TreeView::new(); let list_store = ListStore::new(&[String::static_type(), String::static_type(), String::static_type(), gtk::Type::Bool]); // Config the `TreeView`. tree_view.set_model(Some(&list_store)); tree_view.set_grid_lines(TreeViewGridLines::Both); tree_view.set_rubber_banding(true); tree_view.set_enable_search(false); tree_view.set_search_column(1); tree_view.set_margin_bottom(10); // We enable "Multiple" selection mode, so we can do multi-row operations. tree_view.get_selection().set_mode(gtk::SelectionMode::Multiple); // Create the four type of cells we are going to use. let cell_index = CellRendererText::new(); let cell_key = CellRendererText::new(); let cell_text = CellRendererText::new(); let cell_tooltip = CellRendererToggle::new(); // Config the cells. cell_key.set_property_editable(true); cell_text.set_property_editable(true); cell_tooltip.set_activatable(true); // Reduce the size of the checkbox to 160% the size of the font used (yes, 160% is less that his normal size). cell_tooltip.set_property_indicator_size((settings.font.split(' ').filter_map(|x| x.parse::<f32>().ok()).collect::<Vec<f32>>()[0] * 1.6) as i32); // Create the four columns we are going to use. let column_index = TreeViewColumn::new(); let column_key = TreeViewColumn::new(); let column_text = TreeViewColumn::new(); let column_tooltip = TreeViewColumn::new(); // Set the column's titles. column_index.set_title("Index"); column_key.set_title("Key"); column_text.set_title("Text"); column_tooltip.set_title("Tooltip"); // Make the headers clickable. column_index.set_clickable(true); column_key.set_clickable(true); column_text.set_clickable(true); column_tooltip.set_clickable(true); // Allow the user to move the columns. Because why not? column_key.set_reorderable(true); column_text.set_reorderable(true); column_tooltip.set_reorderable(true); // Allow the user to resize the "key" and "text" columns. column_key.set_resizable(true); column_text.set_resizable(true); // Set a minimal width for the columns, so they can't be fully hidden. column_index.set_max_width(60); column_key.set_min_width(50); column_text.set_min_width(50); column_tooltip.set_min_width(50); // Make both "key" and "text" columns be able to grow from his minimum size. column_key.set_sizing(TreeViewColumnSizing::GrowOnly); column_text.set_sizing(TreeViewColumnSizing::GrowOnly); // Center the column's titles. column_index.set_alignment(0.5); column_key.set_alignment(0.5); column_text.set_alignment(0.5); column_tooltip.set_alignment(0.5); // Set the ID's to short the columns. column_index.set_sort_column_id(0); column_key.set_sort_column_id(1); column_text.set_sort_column_id(2); column_tooltip.set_sort_column_id(3); // Add the cells to the columns. column_index.pack_start(&cell_index, true); column_key.pack_start(&cell_key, true); column_text.pack_start(&cell_text, true); column_tooltip.pack_start(&cell_tooltip, true); // Set their attributes, so we can manipulate their contents. column_index.add_attribute(&cell_index, "text", 0); column_key.add_attribute(&cell_key, "text", 1); column_text.add_attribute(&cell_text, "text", 2); column_tooltip.add_attribute(&cell_tooltip, "active", 3); // Add the four columns to the `TreeView`. tree_view.append_column(&column_index); tree_view.append_column(&column_key); tree_view.append_column(&column_text); tree_view.append_column(&column_tooltip); // Make an extra "Dummy" column that will expand to fill the space between the last column and // the right border of the window. let cell_dummy = CellRendererText::new(); let column_dummy = TreeViewColumn::new(); column_dummy.pack_start(&cell_dummy, true); tree_view.append_column(&column_dummy); // Here we create the Popover menu. It's created and destroyed with the table because otherwise // it'll start crashing when changing tables and trying to delete stuff. Stupid menu. Also, it can't // be created from a `MenuModel` like the rest, because `MenuModel`s can't hold an `Entry`. let context_menu = Popover::new(&tree_view); // Create the `Grid` that'll hold all the buttons in the Contextual Menu. let context_menu_grid = Grid::new(); context_menu_grid.set_border_width(6); // Before setting up the actions, we clean the previous ones. remove_temporal_accelerators(&application); // Create the "Add row/s" button. let add_rows_button = ModelButton::new(); add_rows_button.set_property_text(Some("Add row/s:")); add_rows_button.set_action_name("app.packedfile_loc_add_rows"); // Create the entry to specify the amount of rows you want to add. let add_rows_entry = Entry::new(); let add_rows_entry_buffer = add_rows_entry.get_buffer(); add_rows_entry.set_alignment(1.0); add_rows_entry.set_width_chars(8); add_rows_entry.set_icon_from_icon_name(EntryIconPosition::Primary, Some("go-last")); add_rows_entry.set_has_frame(false); add_rows_entry_buffer.set_max_length(Some(4)); add_rows_entry_buffer.set_text("1"); // Create the "Delete row/s" button. let delete_rows_button = ModelButton::new(); delete_rows_button.set_property_text(Some("Delete row/s")); delete_rows_button.set_action_name("app.packedfile_loc_delete_rows"); // Create the separator between "Delete row/s" and the copy/paste buttons. let separator_1 = Separator::new(Orientation::Vertical); // Create the "Copy cell" button. let copy_cell_button = ModelButton::new(); copy_cell_button.set_property_text(Some("Copy cell")); copy_cell_button.set_action_name("app.packedfile_loc_copy_cell"); // Create the "Paste cell" button. let paste_cell_button = ModelButton::new(); paste_cell_button.set_property_text(Some("Paste cell")); paste_cell_button.set_action_name("app.packedfile_loc_paste_cell"); // Create the "Copy row/s" button. let copy_rows_button = ModelButton::new(); copy_rows_button.set_property_text(Some("Copy row/s")); copy_rows_button.set_action_name("app.packedfile_loc_copy_rows"); // Create the "Paste row/s" button. let paste_rows_button = ModelButton::new(); paste_rows_button.set_property_text(Some("Paste row/s")); paste_rows_button.set_action_name("app.packedfile_loc_paste_rows"); // Create the "Copy column/s" button. let copy_columns_button = ModelButton::new(); copy_columns_button.set_property_text(Some("Copy column/s")); copy_columns_button.set_action_name("app.packedfile_loc_copy_columns"); // Create the "Paste column/s" button. let paste_columns_button = ModelButton::new(); paste_columns_button.set_property_text(Some("Paste column/s")); paste_columns_button.set_action_name("app.packedfile_loc_paste_columns"); // Create the separator between the "Import/Export" buttons and the rest. let separator_2 = Separator::new(Orientation::Vertical); // Create the "Import from TSV" button. let import_tsv_button = ModelButton::new(); import_tsv_button.set_property_text(Some("Import from TSV")); import_tsv_button.set_action_name("app.packedfile_loc_import_tsv"); // Create the "Export to TSV" button. let export_tsv_button = ModelButton::new(); export_tsv_button.set_property_text(Some("Export to TSV")); export_tsv_button.set_action_name("app.packedfile_loc_export_tsv"); // Right-click menu actions. let add_rows = SimpleAction::new("packedfile_loc_add_rows", None); let delete_rows = SimpleAction::new("packedfile_loc_delete_rows", None); let copy_cell = SimpleAction::new("packedfile_loc_copy_cell", None); let paste_cell = SimpleAction::new("packedfile_loc_paste_cell", None); let copy_rows = SimpleAction::new("packedfile_loc_copy_rows", None); let paste_rows = SimpleAction::new("packedfile_loc_paste_rows", None); let copy_columns = SimpleAction::new("packedfile_loc_copy_columns", None); let paste_columns = SimpleAction::new("packedfile_loc_paste_columns", None); let import_tsv = SimpleAction::new("packedfile_loc_import_tsv", None); let export_tsv = SimpleAction::new("packedfile_loc_export_tsv", None); application.add_action(&add_rows); application.add_action(&delete_rows); application.add_action(&copy_cell); application.add_action(&paste_cell); application.add_action(&copy_rows); application.add_action(&paste_rows); application.add_action(&copy_columns); application.add_action(&paste_columns); application.add_action(&import_tsv); application.add_action(&export_tsv); // Accels for popovers need to be specified here. Don't know why, but otherwise they do not work. application.set_accels_for_action("app.packedfile_loc_add_rows", &["<Primary><Shift>a"]); application.set_accels_for_action("app.packedfile_loc_delete_rows", &["<Shift>Delete"]); application.set_accels_for_action("app.packedfile_loc_copy_cell", &["<Primary>c"]); application.set_accels_for_action("app.packedfile_loc_paste_cell", &["<Primary>v"]); application.set_accels_for_action("app.packedfile_loc_copy_rows", &["<Primary>z"]); application.set_accels_for_action("app.packedfile_loc_paste_rows", &["<Primary>x"]); application.set_accels_for_action("app.packedfile_loc_copy_columns", &["<Primary>k"]); application.set_accels_for_action("app.packedfile_loc_paste_columns", &["<Primary>l"]); application.set_accels_for_action("app.packedfile_loc_import_tsv", &["<Primary><Shift>i"]); application.set_accels_for_action("app.packedfile_loc_export_tsv", &["<Primary><Shift>e"]); // Some actions need to start disabled. delete_rows.set_enabled(false); copy_cell.set_enabled(false); copy_rows.set_enabled(false); paste_cell.set_enabled(false); paste_rows.set_enabled(true); paste_columns.set_enabled(true); // Attach all the stuff to the Context Menu `Grid`. context_menu_grid.attach(&add_rows_button, 0, 0, 1, 1); context_menu_grid.attach(&add_rows_entry, 1, 0, 1, 1); context_menu_grid.attach(&delete_rows_button, 0, 1, 2, 1); context_menu_grid.attach(&separator_1, 0, 2, 2, 1); context_menu_grid.attach(&copy_cell_button, 0, 3, 2, 1); context_menu_grid.attach(&paste_cell_button, 0, 4, 2, 1); context_menu_grid.attach(&copy_rows_button, 0, 5, 2, 1); context_menu_grid.attach(&paste_rows_button, 0, 6, 2, 1); context_menu_grid.attach(&copy_columns_button, 0, 7, 2, 1); context_menu_grid.attach(&paste_columns_button, 0, 8, 2, 1); context_menu_grid.attach(&separator_2, 0, 9, 2, 1); context_menu_grid.attach(&import_tsv_button, 0, 10, 2, 1); context_menu_grid.attach(&export_tsv_button, 0, 11, 2, 1); // Add the `Grid` to the Context Menu and show it. context_menu.add(&context_menu_grid); context_menu.show_all(); // Make a `ScrolledWindow` to put the `TreeView` into it. let packed_file_data_scroll = ScrolledWindow::new(None, None); packed_file_data_scroll.set_hexpand(true); packed_file_data_scroll.set_vexpand(true); // Add the `TreeView` to the `ScrolledWindow`, the `ScrolledWindow` to the main `Grid`, and show it. packed_file_data_scroll.add(&tree_view); app_ui.packed_file_data_display.attach(&packed_file_data_scroll, 0, 0, 1, 1); app_ui.packed_file_data_display.show_all(); // Hide the Context Menu by default. context_menu.hide(); // Return the struct with the Loc `TreeView` and all the stuff we want. let decoded_view = PackedFileLocTreeView { tree_view, list_store, cell_key, cell_text, cell_tooltip, context_menu, add_rows_entry, }; // Get the decoded Loc into an Rc<RefCell>, so we can pass it to the closures. let packed_file_decoded = Rc::new(RefCell::new(packed_file_decoded)); // Then we populate the TreeView with the entries of the Loc PackedFile. PackedFileLocTreeView::load_data_to_tree_view(&packed_file_decoded.borrow().data, &decoded_view.list_store); // When we destroy the `ScrolledWindow`, we need to tell the program we no longer have an open PackedFile. packed_file_data_scroll.connect_destroy(clone!( is_packedfile_opened => move |_| { *is_packedfile_opened.borrow_mut() = false; } )); // Contextual Menu actions. { // When we right-click the `TreeView`, show the Contextual Menu. // // NOTE: REMEMBER, WE OPEN THE POPUP HERE, BUT WE NEED TO CLOSED IT WHEN WE HIT HIS BUTTONS. decoded_view.tree_view.connect_button_release_event(clone!( app_ui, paste_rows, paste_columns, decoded_view => move |tree_view, button| { // If we clicked the right mouse button... if button.get_button() == 3 { // If we got text in the `Clipboard`... if app_ui.clipboard.wait_for_text().is_some() { // If the data in the clipboard is a valid row, we enable "Paste rows". if check_clipboard_row(&app_ui) { paste_rows.set_enabled(true); } // Otherwise, we disable the "Paste rows" action. else { paste_rows.set_enabled(false); } // If we have a column selected... if let Some(column) = decoded_view.tree_view.get_cursor().1 { // If the data in the clipboard is a valid column, we enable "Paste columns". if check_clipboard_column(&app_ui, &column) { paste_columns.set_enabled(true); } // Otherwise, we disable the "Paste columns" action. else { paste_columns.set_enabled(false); } } // Otherwise, we disable the "Paste columns" action. else { paste_columns.set_enabled(false); } } else { paste_rows.set_enabled(false); paste_columns.set_enabled(false); } // Point the popover to the place we clicked, and show it. decoded_view.context_menu.set_pointing_to(&get_rect_for_popover(tree_view, Some(button.get_position()))); decoded_view.context_menu.popup(); } Inhibit(false) } )); // When we close the Contextual Menu. decoded_view.context_menu.connect_closed(clone!( paste_rows, paste_columns => move |_| { // Enable both signals, as there are checks when they are emited to stop them if // it's not possible to paste anything. paste_rows.set_enabled(true); paste_columns.set_enabled(true); } )); // We we change the selection, we enable or disable the different actions of the Contextual Menu. decoded_view.tree_view.connect_cursor_changed(clone!( app_ui, copy_cell, copy_rows, paste_cell, copy_columns, delete_rows => move |tree_view| { // If we have something selected, enable these actions. if tree_view.get_selection().count_selected_rows() > 0 { copy_cell.set_enabled(true); copy_rows.set_enabled(true); copy_columns.set_enabled(true); delete_rows.set_enabled(true); } // Otherwise, disable them. else { copy_cell.set_enabled(false); copy_rows.set_enabled(false); copy_columns.set_enabled(false); delete_rows.set_enabled(false); } // If we got text in the `Clipboard`... if app_ui.clipboard.wait_for_text().is_some() { // Get the selected cell, if any. let selected_cell = tree_view.get_cursor(); // If we have a cell selected and it's not in the index column, enable "Paste Cell". if selected_cell.0.is_some() { if let Some(column) = selected_cell.1 { if column.get_sort_column_id() > 0 { paste_cell.set_enabled(true); } // If the cell is invalid, disable the copy for it. else if column.get_sort_column_id() <= 0 { copy_cell.set_enabled(false); copy_columns.set_enabled(false); paste_cell.set_enabled(false); } else { paste_cell.set_enabled(false); } } else { paste_cell.set_enabled(false); } } else { paste_cell.set_enabled(false); } } else { paste_cell.set_enabled(false); } } )); // When we hit the "Add row" button. add_rows.connect_activate(clone!( app_ui, decoded_view => move |_,_| { // We hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // First, we check if the input is a valid number, as I'm already seeing people // trying to add "two" rows. match decoded_view.add_rows_entry.get_buffer().get_text().parse::<u32>() { // If the number is valid... Ok(number_rows) => { // For each new row we want... for _ in 0..number_rows { // Add a new empty line. decoded_view.list_store.insert_with_values(None, &[0, 1, 2, 3], &[&"New".to_value(), &"".to_value(), &"".to_value(), &true.to_value()]); } } Err(error) => show_dialog(&app_ui.window, false, format!("You can only add an \"ENTIRE NUMBER\" of rows. Like 4, or 6. Maybe 5, who knows? But definetly not \"{}\".", Error::from(error).cause())), } } } )); // When we hit the "Delete row" button. delete_rows.connect_activate(clone!( app_ui, pack_file, packed_file_decoded, packed_file_decoded_index, decoded_view => move |_,_| { // We hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // Get the selected row's `TreePath`. let selected_rows = decoded_view.tree_view.get_selection().get_selected_rows().0; // If we have any row selected... if !selected_rows.is_empty() { // For each row (in reverse)... for row in (0..selected_rows.len()).rev() { // Remove it. decoded_view.list_store.remove(&decoded_view.list_store.get_iter(&selected_rows[row]).unwrap()); } // Replace the old encoded data with the new one. packed_file_decoded.borrow_mut().data = PackedFileLocTreeView::return_data_from_tree_view(&decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); } } } )); // When we hit the "Copy cell" button. copy_cell.connect_activate(clone!( app_ui, decoded_view => move |_,_| { // Hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // Get the the focused cell. let focused_cell = decoded_view.tree_view.get_cursor(); // If there is a focused `TreePath`... if let Some(tree_path) = focused_cell.0 { // And a focused `TreeViewColumn`... if let Some(column) = focused_cell.1 { // If the column is not a dummy one. if column.get_sort_column_id() >= 0 { // If the cell is the index... if column.get_sort_column_id() == 0 { // Get his value and put it into the `Clipboard`. app_ui.clipboard.set_text(&decoded_view.list_store.get_value(&decoded_view.list_store.get_iter(&tree_path).unwrap(), 0).get::<String>().unwrap()); } // If we are trying to copy the "tooltip" column... else if column.get_sort_column_id() == 3 { // Get the state of the toggle into an `&str`. let state = if decoded_view.list_store.get_value(&decoded_view.list_store.get_iter(&tree_path).unwrap(), 3).get().unwrap() { "true" } else { "false" }; // Put the state of the toggle into the `Clipboard`. app_ui.clipboard.set_text(state); } // Otherwise... else { // Get the text from the focused cell and put it into the `Clipboard`. app_ui.clipboard.set_text( decoded_view.list_store.get_value( &decoded_view.list_store.get_iter(&tree_path).unwrap(), column.get_sort_column_id(), ).get::<&str>().unwrap() ); } } } } } } )); // When we hit the "Paste cell" button. paste_cell.connect_activate(clone!( app_ui, pack_file, packed_file_decoded, packed_file_decoded_index, decoded_view => move |_,_| { // Hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // Get the the focused cell. let focused_cell = decoded_view.tree_view.get_cursor(); // If there is a focused `TreePath`... if let Some(tree_path) = focused_cell.0 { // And a focused `TreeViewColumn`... if let Some(column) = focused_cell.1 { // If the cell is the index... if column.get_sort_column_id() > 0 { // If we are trying to paste the "tooltip" column... if column.get_sort_column_id() == 3 { // If we got the state of the toggle from the `Clipboard`... if let Some(data) = app_ui.clipboard.wait_for_text() { // Get the state of the toggle into an `&str`. let state = if data == "true" { true } else if data == "false" { false } else { return show_dialog(&app_ui.window, false, "Error while trying to paste a cell to a Loc PackedFile:\n\nThe value provided is neither \"true\" nor \"false\".") }; // Set the state of the toggle of the cell. decoded_view.list_store.set_value(&decoded_view.list_store.get_iter(&tree_path).unwrap(), 3, &state.to_value()); // Replace the old encoded data with the new one. packed_file_decoded.borrow_mut().data = PackedFileLocTreeView::return_data_from_tree_view(&decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); } } // Otherwise, if we got the state of the toggle from the `Clipboard`... else if let Some(data) = app_ui.clipboard.wait_for_text() { // Update his value. decoded_view.list_store.set_value(&decoded_view.list_store.get_iter(&tree_path).unwrap(), column.get_sort_column_id() as u32, &data.to_value()); // Replace the old encoded data with the new one. packed_file_decoded.borrow_mut().data = PackedFileLocTreeView::return_data_from_tree_view(&decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); } } } } } } )); // When we hit the "Copy row" button. copy_rows.connect_activate(clone!( app_ui, decoded_view => move |_,_| { // Hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // Get the selected rows. let selected_rows = decoded_view.tree_view.get_selection().get_selected_rows().0; // If there is something selected... if !selected_rows.is_empty() { // Get the list of `TreeIter`s we want to copy. let tree_iter_list = selected_rows.iter().map(|row| decoded_view.list_store.get_iter(row).unwrap()).collect::<Vec<TreeIter>>(); // Create the `String` that will copy the row that will bring that shit of TLJ down. let mut copy_string = String::new(); // For each row... for row in &tree_iter_list { // Get the data from the three columns, and push it to our copy `String`. copy_string.push_str(decoded_view.list_store.get_value(row, 1).get::<&str>().unwrap()); copy_string.push('\t'); copy_string.push_str(decoded_view.list_store.get_value(row, 2).get::<&str>().unwrap()); copy_string.push('\t'); copy_string.push_str( match decoded_view.list_store.get_value(row, 3).get::<bool>().unwrap() { true => "true", false => "false", } ); copy_string.push('\n'); } // Pass all the copied rows to the clipboard. app_ui.clipboard.set_text(&copy_string); } } } )); // When we hit the "Paste row" button. paste_rows.connect_activate(clone!( app_ui, pack_file, packed_file_decoded, packed_file_decoded_index, decoded_view => move |_,_| { // Hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // Before anything else, we check if the data in the `Clipboard` includes ONLY valid rows. if check_clipboard_row(&app_ui) { // When it gets the data from the `Clipboard`.... if let Some(data) = app_ui.clipboard.wait_for_text() { // Store here all the decoded fields. let mut fields_data = vec![]; // For each row in the data we received... for row in data.lines() { // Get all the data from his fields. fields_data.push(row.split('\t').map(|x| x.to_owned()).collect::<Vec<String>>()); } // Get the selected row, if there is any. let selected_row = decoded_view.tree_view.get_selection().get_selected_rows().0; // If there is at least one line selected, use it as "base" to paste. let mut tree_iter = if !selected_row.is_empty() { decoded_view.list_store.get_iter(&selected_row[0]).unwrap() } // Otherwise, append a new `TreeIter` to the `TreeView`, and use it. else { decoded_view.list_store.append() }; // For each row in our fields_data vec... for (row_index, row) in fields_data.iter().enumerate() { // Fill the "Index" column with "New". decoded_view.list_store.set_value(&tree_iter, 0, &"New".to_value()); // Fill the "key" and "text" columns. decoded_view.list_store.set_value(&tree_iter, 1, &row[0].to_value()); decoded_view.list_store.set_value(&tree_iter, 2, &row[1].to_value()); // Fill the "tooltip" column. decoded_view.list_store.set_value(&tree_iter, 3, &(if row[2] == "true" { true } else {false}).to_value()); // Move to the next row. If it doesn't exist and it's not the last loop.... if !decoded_view.list_store.iter_next(&tree_iter) && row_index < (fields_data.len() - 1) { // Create it. tree_iter = decoded_view.list_store.append(); } } // Replace the old encoded data with the new one. packed_file_decoded.borrow_mut().data = PackedFileLocTreeView::return_data_from_tree_view(&decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); }; } } } )); // When we hit the "Copy column" button. copy_columns.connect_activate(clone!( app_ui, decoded_view => move |_,_| { // Hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // If there is a column selected... if let Some(column) = decoded_view.tree_view.get_cursor().1 { // Get the number of the column. let mut column_number = column.get_sort_column_id(); // Ignore columns with < 1, as those are index or invalid columns. if column_number >= 1 { // Get the selected rows. let selected_rows = decoded_view.tree_view.get_selection().get_selected_rows().0; // If there is something selected... if !selected_rows.is_empty() { // Get the list of `TreeIter`s we want to copy. let tree_iter_list = selected_rows.iter().map(|row| decoded_view.list_store.get_iter(row).unwrap()).collect::<Vec<TreeIter>>(); // Create the `String` that will copy the row that will bring that shit of TLJ down. let mut copy_string = String::new(); // For each row... for (index, row) in tree_iter_list.iter().enumerate() { // If it's the third column, we transform the boolean to string. if column_number == 3 { copy_string.push_str( match decoded_view.list_store.get_value(row, column_number).get::<bool>().unwrap() { true => "true", false => "false", } ); } // Otherwise, just get the text in the column. else { copy_string.push_str(decoded_view.list_store.get_value(row, column_number).get::<&str>().unwrap()); } // If it's not the last row... if index < tree_iter_list.len() - 1 { // Put an endline between fields, so excel understand them. copy_string.push('\n'); } } // Pass all the copied rows to the clipboard. app_ui.clipboard.set_text(&copy_string); } } } } } )); // When we hit the "Paste column" button. paste_columns.connect_activate(clone!( app_ui, pack_file, packed_file_decoded, packed_file_decoded_index, decoded_view => move |_,_| { // Hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // Get the selected cell. let cursor = decoded_view.tree_view.get_cursor(); // If there is a `TreePath` selected... if let Some(tree_path) = cursor.0 { // And a column selected... if let Some(column) = cursor.1 { // Before anything else, we check if the data in the `Clipboard` includes ONLY a valid column. if check_clipboard_column(&app_ui, &column) { // When it gets the data from the `Clipboard`.... if let Some(data) = app_ui.clipboard.wait_for_text() { // Get the number of the column. let mut column_number = column.get_sort_column_id(); // Ignore columns with < 1, as those are index or invalid columns. if column_number >= 1 { // Get the data to paste, separated by lines. let fields_data = data.lines().collect::<Vec<&str>>(); // Get the selected rows, if there is any. let selected_rows = decoded_view.tree_view.get_selection().get_selected_rows().0; // Get the selected row. let tree_iter = if !selected_rows.is_empty() { decoded_view.list_store.get_iter(&selected_rows[0]).unwrap() } else { decoded_view.list_store.get_iter(&tree_path).unwrap() }; // For each row in our fields list... for field in &fields_data { // If it's the third column, we change it to bool. if column_number == 3 { decoded_view.list_store.set_value(&tree_iter, column_number as u32, &(if *field == "true" { true } else {false}).to_value()); } // Otherwise, just paste it as string. else { decoded_view.list_store.set_value(&tree_iter, column_number as u32, &field.to_value()); } // If there are no more rows, stop. if !decoded_view.list_store.iter_next(&tree_iter) { break; } } // Replace the old encoded data with the new one. packed_file_decoded.borrow_mut().data = PackedFileLocTreeView::return_data_from_tree_view(&decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); } }; } } } } } )); // When we hit the "Import to TSV" button. import_tsv.connect_activate(clone!( app_ui, pack_file, packed_file_decoded, packed_file_decoded_index, decoded_view => move |_,_|{ // We hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // Create the `FileChooser`. let file_chooser = FileChooserNative::new( "Select TSV File to Import...", &app_ui.window, FileChooserAction::Open, "Import", "Cancel" ); // Enable the TSV filter for the `FileChooser`. file_chooser_filter_packfile(&file_chooser, "*.tsv"); // If we have selected a file to import... if file_chooser.run() == gtk_response_accept { // If there is an error while importing the TSV file, we report it. if let Err(error) = packed_file_decoded.borrow_mut().data.import_tsv( &file_chooser.get_filename().unwrap(), "Loc PackedFile" ) { return show_dialog(&app_ui.window, false, error.cause()); } // Load the new data to the TreeView. PackedFileLocTreeView::load_data_to_tree_view(&packed_file_decoded.borrow().data, &decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); } } } )); // When we hit the "Export to TSV" button. export_tsv.connect_activate(clone!( app_ui, packed_file_decoded, decoded_view => move |_,_|{ // We hide the context menu. decoded_view.context_menu.popdown(); // We only do something in case the focus is in the TreeView. This should stop problems with // the accels working everywhere. if decoded_view.tree_view.has_focus() { // Create the `FileChooser`. let file_chooser = FileChooserNative::new( "Export TSV File...", &app_ui.window, FileChooserAction::Save, "Save", "Cancel" ); // We want to ask before overwriting files. Just in case. Otherwise, there can be an accident. file_chooser.set_do_overwrite_confirmation(true); // Set the name of the Loc PackedFile as the default new name. file_chooser.set_current_name(format!("{}.tsv", &tree_path.last().unwrap())); // If we hit "Save"... if file_chooser.run() == gtk_response_accept { // Try to export the TSV. match packed_file_decoded.borrow_mut().data.export_tsv( &file_chooser.get_filename().unwrap(), ("Loc PackedFile", 9001) ) { Ok(result) => show_dialog(&app_ui.window, true, result), Err(error) => show_dialog(&app_ui.window, false, error.cause()) } } } } )); } // Things that happen when we edit a cell. { // When we edit the "Key" column. decoded_view.cell_key.connect_edited(clone!( app_ui, pack_file, packed_file_decoded, packed_file_decoded_index, decoded_view => move |_, tree_path, new_text|{ // Get the cell's old text, to check for changes. let tree_iter = decoded_view.list_store.get_iter(&tree_path).unwrap(); let old_text: String = decoded_view.list_store.get_value(&tree_iter, 1).get().unwrap(); // If the text has changed we need to check that the new text is valid, as this is a key column. // Otherwise, we do nothing. if old_text != new_text && !new_text.is_empty() && !new_text.contains(' ') { // Get the first row's `TreeIter`. let current_line = decoded_view.list_store.get_iter_first().unwrap(); // Loop to search for coincidences. let mut key_already_exists = false; loop { // If we found a coincidence, break the loop. if decoded_view.list_store.get_value(&current_line, 1).get::<String>().unwrap() == new_text { key_already_exists = true; break; } // If we reached the end of the `ListStore`, we break the loop. else if !decoded_view.list_store.iter_next(&current_line) { break; } } // If there is a coincidence with another key... if key_already_exists { show_dialog(&app_ui.window, false, "This key is already in the Loc PackedFile."); } // If it has passed all the checks without error... else { // Change the value in the cell. decoded_view.list_store.set_value(&tree_iter, 1, &new_text.to_value()); // Replace the old encoded data with the new one. packed_file_decoded.borrow_mut().data = PackedFileLocTreeView::return_data_from_tree_view(&decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); } } // If the field is empty, else if new_text.is_empty() { show_dialog(&app_ui.window, false, "Only my hearth can be empty."); } // If the field contains spaces. else if new_text.contains(' ') { show_dialog(&app_ui.window, false, "Spaces are not valid characters."); } } )); // When we edit the "Text" column. decoded_view.cell_text.connect_edited(clone!( app_ui, pack_file, packed_file_decoded, packed_file_decoded_index, decoded_view => move |_, tree_path, new_text| { // Get the cell's old text, to check for changes. let tree_iter = decoded_view.list_store.get_iter(&tree_path).unwrap(); let old_text: String = decoded_view.list_store.get_value(&tree_iter, 2).get().unwrap(); // If it has changed... if old_text != new_text { // Change the value in the cell. decoded_view.list_store.set_value(&tree_iter, 2, &new_text.to_value()); // Replace the old encoded data with the new one. packed_file_decoded.borrow_mut().data = PackedFileLocTreeView::return_data_from_tree_view(&decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); } } )); // When we change the state (true/false) of the "Tooltip" cell. decoded_view.cell_tooltip.connect_toggled(clone!( app_ui, pack_file, packed_file_decoded, packed_file_decoded_index, decoded_view => move |cell, tree_path|{ // Get his `TreeIter` and his column. let tree_iter = decoded_view.list_store.get_iter(&tree_path).unwrap(); let edited_cell_column = decoded_view.tree_view.get_cursor().1.unwrap().get_sort_column_id() as u32; // Get his new state. let state = !cell.get_active(); // Change it in the `ListStore`. decoded_view.list_store.set_value(&tree_iter, edited_cell_column, &state.to_value()); // Change his state. cell.set_active(state); // Replace the old encoded data with the new one. packed_file_decoded.borrow_mut().data = PackedFileLocTreeView::return_data_from_tree_view(&decoded_view.list_store); // Update the PackFile to reflect the changes. update_packed_file_data_loc( &*packed_file_decoded.borrow_mut(), &mut *pack_file.borrow_mut(), packed_file_decoded_index ); // Set the mod as "Modified". set_modified(true, &app_ui.window, &mut *pack_file.borrow_mut()); } )); } // Return success. Ok(()) } // Otherwise, return error. Err(error) => Err(error) } } /// This function loads the data from a `LocData` into a `TreeView`. pub fn load_data_to_tree_view( packed_file_data: &LocData, packed_file_list_store: &ListStore ) { // First, we delete all the data from the `ListStore`. Just in case there is something there. packed_file_list_store.clear(); // Then we add every line to the ListStore. for (j, i) in packed_file_data.entries.iter().enumerate() { packed_file_list_store.insert_with_values(None, &[0, 1, 2, 3], &[&format!("{:0count$}", j + 1, count = (packed_file_data.entries.len().to_string().len() + 1)), &i.key, &i.text, &i.tooltip]); } } /// This function returns a `LocData` with all the stuff in the table. We need for it the `ListStore` of that table. pub fn return_data_from_tree_view( list_store: &ListStore, ) -> LocData { // Create an empty `LocData`. let mut loc_data = LocData::new(); // If we got at least one row... if let Some(current_line) = list_store.get_iter_first() { // Loop 'til the end of the storm of the sword and axe. loop { // Make a new entry with the data from the `ListStore`, and push it to our new `LocData`. loc_data.entries.push( LocEntry::new( list_store.get_value(&current_line, 1).get().unwrap(), list_store.get_value(&current_line, 2).get().unwrap(), list_store.get_value(&current_line, 3).get().unwrap(), ) ); // If there are no more rows, stop, for the wolf has come. if !list_store.iter_next(&current_line) { break; } } } // Return the new `LocData`. loc_data } } /// This function checks if the data in the clipboard is a valid row of a Loc PackedFile. Returns /// `true` if the data in the clipboard forms valid rows, and `false` if any of them is an invalid row. fn check_clipboard_row(app_ui: &AppUI) -> bool { // Try to get the data from the `Clipboard`.... if let Some(data) = app_ui.clipboard.wait_for_text() { // Store here all the decoded fields. let mut fields_data = vec![]; // For each row in the data we received... for row in data.lines() { // Get all the data from his fields. fields_data.push(row.split('\t').map(|x| x.to_owned()).collect::<Vec<String>>()); } // If we at least have one row... if !fields_data.is_empty() { // Var to control when a field is invalid. let mut data_is_invalid = false; // For each row we have... for row in &fields_data { // If we have the same amount of data for each field... if row.len() == 3 { // If the third field is not valid, the data is invalid. if row[2] != "true" && row[2] != "false" { data_is_invalid = true; break; } } // Otherwise, the rows are invalid. else { data_is_invalid = true; break; } } // If in any point the data was invalid, return false. if data_is_invalid { false } else { true } } // Otherwise, the contents of the `Clipboard` are invalid. else { false } } // Otherwise, there is no data in the `Clipboard`. else { false } } /// This function checks if the data in the clipboard is suitable for the column we have selected. /// Returns `true` if the data is pasteable, false, otherwise. fn check_clipboard_column(app_ui: &AppUI, column: &TreeViewColumn) -> bool { // Try to get the data from the `Clipboard`.... if let Some(data) = app_ui.clipboard.wait_for_text() { // Get the column we are going to paste. let column = column.get_sort_column_id(); // If the column is valid... (0 is index column, so invalid). if column >= 1 { // Get the data to paste, separated by lines. let fields_data = data.lines().collect::<Vec<&str>>(); // If we at least have one row... if !fields_data.is_empty() { // Var to control when a field is invalid. let mut data_is_invalid = false; // For each row we have... for row in &fields_data { // If we are trying to paste in the third column and it's not a boolean, stop. if column == 3 && *row != "true" && *row != "false" { data_is_invalid = true; break; } } // If in any point the data was invalid, return false. if data_is_invalid { false } else { true } } // Otherwise, the contents of the `Clipboard` are invalid. else { false } } // Otherwise, the column is not pasteable. else { false } } // Otherwise, there is no data in the `Clipboard`. else { false } }
/* chapter 4 syntax and semantics */ fn main() { let a = vec![1, 2, 3]; let b = vec![4, 5, 6]; // don't worry if you don't understand how `fold` works, // the point here is that an immutable reference is borrowed. fn sum_vec(n: &Vec<i32>) -> i32 { return n.iter().fold(0, |a, &b| a + b); } // borrow two vectors and sum them. // this kind of borrowing does not // allow mutation to the borrowed. fn foo(a: &Vec<i32>, b: &Vec<i32>) -> i32 { // do stuff with a and b let c = sum_vec(a); let d = sum_vec(b); // return the answer c + d } let answer = foo(&a, &b); println!("{}", answer); } // output should be: /* 21 */
// Copyright (c) 2016, <daggerbot@gmail.com> // This software is available under the terms of the zlib license. // See COPYING.md for more information. use std::rc::Rc; use aurum::linear::Vec2; use ::Coord; use display::{Display, DisplayBridge}; use error::Result; use id::{IdLock, IdManager}; use imp::{DeviceProvider, PixelFormatsProvider}; use pixel_format::{PixelFormat, PixelFormatBridge, PixelFormatPriv}; use util::{Get, GetProvider}; use window::{Window, WindowPriv, WindowStyle}; /// Implementation trait for `Device`. pub trait DeviceBridge : Sized { type PixelFormat : PixelFormatBridge; type PixelFormats : Sized + Iterator<Item = Result<Self::PixelFormat>>; fn default_pixel_format (&self) -> Result<Self::PixelFormat>; fn pixel_formats (&self) -> Result<Self::PixelFormats>; } /// Display device structure. #[derive(Clone)] pub struct Device { provider: Rc<DeviceProvider>, id_manager: Rc<IdManager>, } impl Device { pub fn default_pixel_format (&self) -> Result<PixelFormat> { PixelFormat::default(self) } pub fn new_window<S: Into<Vec2<Coord>>> (&self, pixel_format: &PixelFormat, size: S, style: WindowStyle) -> Result<Window> { Window::new(self, pixel_format, size.into(), style) } pub fn pixel_formats (&self) -> Result<PixelFormats> { Ok(PixelFormats { provider: try!(self.provider.pixel_formats()), }) } } #[doc(hidden)] impl DevicePriv for Device { fn alloc_id (&self) -> IdLock { self.id_manager.alloc() } fn default (display: &Display) -> Result<Device> { Ok(Device { provider: try!(display.provider().default_device()), id_manager: display.get(), }) } } #[doc(hidden)] impl GetProvider for Device { type Provider = DeviceProvider; fn provider (&self) -> &DeviceProvider { &self.provider } } impl PartialEq for Device { fn eq (&self, rhs: &Device) -> bool { let l_provider: &DeviceProvider = self.provider.as_ref(); let r_provider: &DeviceProvider = rhs.provider.as_ref(); l_provider as *const _ == r_provider as *const _ } } /// Private methods for `Device`. pub trait DevicePriv : Sized { fn alloc_id (&self) -> IdLock; fn default (display: &Display) -> Result<Self>; } /// Iterator over pixel formats supported by a `Device`. pub struct PixelFormats { provider: PixelFormatsProvider, } impl Iterator for PixelFormats { type Item = Result<PixelFormat>; fn next (&mut self) -> Option<Result<PixelFormat>> { match self.provider.next() { Some(Ok(provider)) => Some(Ok(PixelFormat::from(provider))), Some(Err(err)) => Some(Err(err)), None => None, } } }
/* MCP6050 Gyroscope and Accelerometer */ use crate::hal::i2c::I2c; // AREA FOR THE GY-521 / MCP6050 const ADDR_MCP: u32 = 0x68; const MCP_WAKEUP: [u8; 2] = [0x6B, 0x00]; // HW LW in that order BE transfer const MCP_GYRO: [u8; 2] = [0x1B, 0x00]; // HW LW in that order BE transfer const MCP_ACCEL: [u8; 2] = [0x1C, 0x00]; // HW LW in that order BE transfer const MCP_GYRO_REG: [u8; 1] = [0x43]; // HW LW in that order BE transfer const MCP_ACCEL_REG: [u8; 1] = [0x3B]; // HW LW in that order BE transfer const MCP_TEMP_REG: [u8; 1] = [0x41]; // HW LW in that order BE transfer const SEVEN_BIT: bool = false; pub fn init(i2c: &I2c) { i2c.std_write(ADDR_MCP, SEVEN_BIT, SEVEN_BIT, &MCP_WAKEUP); // WAKE UP THE MCP 6050 i2c.std_write(ADDR_MCP, SEVEN_BIT, SEVEN_BIT, &MCP_GYRO); // SET UP THE GYRO SCALE i2c.std_write(ADDR_MCP, SEVEN_BIT, SEVEN_BIT, &MCP_ACCEL); // SET UP THE ACCELERATION SCALE } pub fn read_gyro(i2c: &I2c, buffer: &mut [u8]) { i2c.std_read(ADDR_MCP, SEVEN_BIT, SEVEN_BIT, &MCP_GYRO_REG, buffer); } pub fn read_accel(i2c: &I2c, buffer: &mut [u8]) { i2c.std_read(ADDR_MCP, SEVEN_BIT, SEVEN_BIT, &MCP_ACCEL_REG, buffer); } pub fn read_temp(i2c: &I2c, buffer: &mut [u8]) { i2c.std_read(ADDR_MCP, SEVEN_BIT, SEVEN_BIT, &MCP_TEMP_REG, buffer); } pub fn check_fail(i2c: &I2c, buffer: &[u8]) -> bool { let mut i = 0; while i < buffer.len() { if buffer[i] != 0 { return false; } i += 1; } return true; }
#![feature(plugin, custom_derive, const_fn, decl_macro, custom_attribute, proc_macro_hygiene)] #![allow(proc_macro_derive_resolution_fallback, unused_attributes)] #[macro_use] extern crate diesel; extern crate dotenv; extern crate r2d2; extern crate r2d2_diesel; #[macro_use] extern crate rocket; extern crate rocket_contrib; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; use dotenv::dotenv; use std::env; use routes::*; mod db; mod models; mod routes; mod schema; mod static_files; fn rocket() -> rocket::Rocket { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("set DATABASE_URL"); let pool = db::init_pool(database_url); rocket::ignite() .manage(pool) .mount( "/api/v1/", routes![index, new, show, delete, author, update], ) .mount("/", routes![static_files::all, static_files::index]) } fn main() { rocket().launch(); }
use crate::{ framed::{FrameConsumer, FrameProducer}, Error, Result, }; use core::{ cell::UnsafeCell, cmp::min, marker::PhantomData, mem::{forget, transmute, MaybeUninit}, ops::{Deref, DerefMut}, ptr::NonNull, result::Result as CoreResult, slice::from_raw_parts_mut, sync::atomic::{ AtomicBool, AtomicUsize, Ordering::{AcqRel, Acquire, Release}, }, }; #[derive(Debug)] /// A backing structure for a BBQueue. Can be used to create either /// a BBQueue or a split Producer/Consumer pair pub struct BBBuffer<const N: usize> { buf: UnsafeCell<MaybeUninit<[u8; N]>>, /// Where the next byte will be written write: AtomicUsize, /// Where the next byte will be read from read: AtomicUsize, /// Used in the inverted case to mark the end of the /// readable streak. Otherwise will == sizeof::<self.buf>(). /// Writer is responsible for placing this at the correct /// place when entering an inverted condition, and Reader /// is responsible for moving it back to sizeof::<self.buf>() /// when exiting the inverted condition last: AtomicUsize, /// Used by the Writer to remember what bytes are currently /// allowed to be written to, but are not yet ready to be /// read from reserve: AtomicUsize, /// Is there an active read grant? read_in_progress: AtomicBool, /// Is there an active write grant? write_in_progress: AtomicBool, /// Have we already split? already_split: AtomicBool, } unsafe impl<const A: usize> Sync for BBBuffer<A> {} impl<'a, const N: usize> BBBuffer<N> { /// Attempt to split the `BBBuffer` into `Consumer` and `Producer` halves to gain access to the /// buffer. If buffer has already been split, an error will be returned. /// /// NOTE: When splitting, the underlying buffer will be explicitly initialized /// to zero. This may take a measurable amount of time, depending on the size /// of the buffer. This is necessary to prevent undefined behavior. If the buffer /// is placed at `static` scope within the `.bss` region, the explicit initialization /// will be elided (as it is already performed as part of memory initialization) /// /// NOTE: If the `thumbv6` feature is selected, this function takes a short critical section /// while splitting. /// /// ```rust /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create and split a new buffer /// let buffer: BBBuffer<6> = BBBuffer::new(); /// let (prod, cons) = buffer.try_split().unwrap(); /// /// // Not possible to split twice /// assert!(buffer.try_split().is_err()); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub fn try_split(&'a self) -> Result<(Producer<'a, N>, Consumer<'a, N>)> { if atomic::swap(&self.already_split, true, AcqRel) { return Err(Error::AlreadySplit); } unsafe { // Explicitly zero the data to avoid undefined behavior. // This is required, because we hand out references to the buffers, // which mean that creating them as references is technically UB for now let mu_ptr = self.buf.get(); (*mu_ptr).as_mut_ptr().write_bytes(0u8, 1); let nn1 = NonNull::new_unchecked(self as *const _ as *mut _); let nn2 = NonNull::new_unchecked(self as *const _ as *mut _); Ok(( Producer { bbq: nn1, pd: PhantomData, }, Consumer { bbq: nn2, pd: PhantomData, }, )) } } /// Attempt to split the `BBBuffer` into `FrameConsumer` and `FrameProducer` halves /// to gain access to the buffer. If buffer has already been split, an error /// will be returned. /// /// NOTE: When splitting, the underlying buffer will be explicitly initialized /// to zero. This may take a measurable amount of time, depending on the size /// of the buffer. This is necessary to prevent undefined behavior. If the buffer /// is placed at `static` scope within the `.bss` region, the explicit initialization /// will be elided (as it is already performed as part of memory initialization) /// /// NOTE: If the `thumbv6` feature is selected, this function takes a short critical /// section while splitting. pub fn try_split_framed(&'a self) -> Result<(FrameProducer<'a, N>, FrameConsumer<'a, N>)> { let (producer, consumer) = self.try_split()?; Ok((FrameProducer { producer }, FrameConsumer { consumer })) } /// Attempt to release the Producer and Consumer /// /// This re-initializes the buffer so it may be split in a different mode at a later /// time. There must be no read or write grants active, or an error will be returned. /// /// The `Producer` and `Consumer` must be from THIS `BBBuffer`, or an error will /// be returned. /// /// ```rust /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create and split a new buffer /// let buffer: BBBuffer<6> = BBBuffer::new(); /// let (prod, cons) = buffer.try_split().unwrap(); /// /// // Not possible to split twice /// assert!(buffer.try_split().is_err()); /// /// // Release the producer and consumer /// assert!(buffer.try_release(prod, cons).is_ok()); /// /// // Split the buffer in framed mode /// let (fprod, fcons) = buffer.try_split_framed().unwrap(); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub fn try_release( &'a self, prod: Producer<'a, N>, cons: Consumer<'a, N>, ) -> CoreResult<(), (Producer<'a, N>, Consumer<'a, N>)> { // Note: Re-entrancy is not possible because we require ownership // of the producer and consumer, which are not cloneable. We also // can assume the buffer has been split, because // Are these our producers and consumers? let our_prod = prod.bbq.as_ptr() as *const Self == self; let our_cons = cons.bbq.as_ptr() as *const Self == self; if !(our_prod && our_cons) { // Can't release, not our producer and consumer return Err((prod, cons)); } let wr_in_progress = self.write_in_progress.load(Acquire); let rd_in_progress = self.read_in_progress.load(Acquire); if wr_in_progress || rd_in_progress { // Can't release, active grant(s) in progress return Err((prod, cons)); } // Drop the producer and consumer halves drop(prod); drop(cons); // Re-initialize the buffer (not totally needed, but nice to do) self.write.store(0, Release); self.read.store(0, Release); self.reserve.store(0, Release); self.last.store(0, Release); // Mark the buffer as ready to be split self.already_split.store(false, Release); Ok(()) } /// Attempt to release the Producer and Consumer in Framed mode /// /// This re-initializes the buffer so it may be split in a different mode at a later /// time. There must be no read or write grants active, or an error will be returned. /// /// The `FrameProducer` and `FrameConsumer` must be from THIS `BBBuffer`, or an error /// will be returned. pub fn try_release_framed( &'a self, prod: FrameProducer<'a, N>, cons: FrameConsumer<'a, N>, ) -> CoreResult<(), (FrameProducer<'a, N>, FrameConsumer<'a, N>)> { self.try_release(prod.producer, cons.consumer) .map_err(|(producer, consumer)| { // Restore the wrapper types (FrameProducer { producer }, FrameConsumer { consumer }) }) } } impl<const A: usize> BBBuffer<A> { /// Create a new constant inner portion of a `BBBuffer`. /// /// NOTE: This is only necessary to use when creating a `BBBuffer` at static /// scope, and is generally never used directly. This process is necessary to /// work around current limitations in `const fn`, and will be replaced in /// the future. /// /// ```rust,no_run /// use bbqueue::BBBuffer; /// /// static BUF: BBBuffer<6> = BBBuffer::new(); /// /// fn main() { /// let (prod, cons) = BUF.try_split().unwrap(); /// } /// ``` pub const fn new() -> Self { Self { // This will not be initialized until we split the buffer buf: UnsafeCell::new(MaybeUninit::uninit()), /// Owned by the writer write: AtomicUsize::new(0), /// Owned by the reader read: AtomicUsize::new(0), /// Cooperatively owned /// /// NOTE: This should generally be initialized as size_of::<self.buf>(), however /// this would prevent the structure from being entirely zero-initialized, /// and can cause the .data section to be much larger than necessary. By /// forcing the `last` pointer to be zero initially, we place the structure /// in an "inverted" condition, which will be resolved on the first commited /// bytes that are written to the structure. /// /// When read == last == write, no bytes will be allowed to be read (good), but /// write grants can be given out (also good). last: AtomicUsize::new(0), /// Owned by the Writer, "private" reserve: AtomicUsize::new(0), /// Owned by the Reader, "private" read_in_progress: AtomicBool::new(false), /// Owned by the Writer, "private" write_in_progress: AtomicBool::new(false), /// We haven't split at the start already_split: AtomicBool::new(false), } } } /// `Producer` is the primary interface for pushing data into a `BBBuffer`. /// There are various methods for obtaining a grant to write to the buffer, with /// different potential tradeoffs. As all grants are required to be a contiguous /// range of data, different strategies are sometimes useful when making the decision /// between maximizing usage of the buffer, and ensuring a given grant is successful. /// /// As a short summary of currently possible grants: /// /// * `grant_exact(N)` /// * User will receive a grant `sz == N` (or receive an error) /// * This may cause a wraparound if a grant of size N is not available /// at the end of the ring. /// * If this grant caused a wraparound, the bytes that were "skipped" at the /// end of the ring will not be available until the reader reaches them, /// regardless of whether the grant commited any data or not. /// * Maximum possible waste due to skipping: `N - 1` bytes /// * `grant_max_remaining(N)` /// * User will receive a grant `0 < sz <= N` (or receive an error) /// * This will only cause a wrap to the beginning of the ring if exactly /// zero bytes are available at the end of the ring. /// * Maximum possible waste due to skipping: 0 bytes /// /// See [this github issue](https://github.com/jamesmunns/bbqueue/issues/38) for a /// discussion of grant methods that could be added in the future. pub struct Producer<'a, const N: usize> { bbq: NonNull<BBBuffer<N>>, pd: PhantomData<&'a ()>, } unsafe impl<'a, const N: usize> Send for Producer<'a, N> {} impl<'a, const N: usize> Producer<'a, N> { /// Request a writable, contiguous section of memory of exactly /// `sz` bytes. If the buffer size requested is not available, /// an error will be returned. /// /// This method may cause the buffer to wrap around early if the /// requested space is not available at the end of the buffer, but /// is available at the beginning /// /// ```rust /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create and split a new buffer of 6 elements /// let buffer: BBBuffer<6> = BBBuffer::new(); /// let (mut prod, cons) = buffer.try_split().unwrap(); /// /// // Successfully obtain and commit a grant of four bytes /// let mut grant = prod.grant_exact(4).unwrap(); /// assert_eq!(grant.buf().len(), 4); /// grant.commit(4); /// /// // Try to obtain a grant of three bytes /// assert!(prod.grant_exact(3).is_err()); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub fn grant_exact(&mut self, sz: usize) -> Result<GrantW<'a, N>> { let inner = unsafe { &self.bbq.as_ref() }; if atomic::swap(&inner.write_in_progress, true, AcqRel) { return Err(Error::GrantInProgress); } // Writer component. Must never write to `read`, // be careful writing to `load` let write = inner.write.load(Acquire); let read = inner.read.load(Acquire); let max = N; let already_inverted = write < read; let start = if already_inverted { if (write + sz) < read { // Inverted, room is still available write } else { // Inverted, no room is available inner.write_in_progress.store(false, Release); return Err(Error::InsufficientSize); } } else { if write + sz <= max { // Non inverted condition write } else { // Not inverted, but need to go inverted // NOTE: We check sz < read, NOT <=, because // write must never == read in an inverted condition, since // we will then not be able to tell if we are inverted or not if sz < read { // Invertible situation 0 } else { // Not invertible, no space inner.write_in_progress.store(false, Release); return Err(Error::InsufficientSize); } } }; // Safe write, only viewed by this task inner.reserve.store(start + sz, Release); // This is sound, as UnsafeCell, MaybeUninit, and GenericArray // are all `#[repr(Transparent)] let start_of_buf_ptr = inner.buf.get().cast::<u8>(); let grant_slice = unsafe { from_raw_parts_mut(start_of_buf_ptr.offset(start as isize), sz) }; Ok(GrantW { buf: grant_slice, bbq: self.bbq, to_commit: 0, }) } /// Request a writable, contiguous section of memory of up to /// `sz` bytes. If a buffer of size `sz` is not available without /// wrapping, but some space (0 < available < sz) is available without /// wrapping, then a grant will be given for the remaining size at the /// end of the buffer. If no space is available for writing, an error /// will be returned. /// /// ``` /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create and split a new buffer of 6 elements /// let buffer: BBBuffer<6> = BBBuffer::new(); /// let (mut prod, mut cons) = buffer.try_split().unwrap(); /// /// // Successfully obtain and commit a grant of four bytes /// let mut grant = prod.grant_max_remaining(4).unwrap(); /// assert_eq!(grant.buf().len(), 4); /// grant.commit(4); /// /// // Release the four initial commited bytes /// let mut grant = cons.read().unwrap(); /// assert_eq!(grant.buf().len(), 4); /// grant.release(4); /// /// // Try to obtain a grant of three bytes, get two bytes /// let mut grant = prod.grant_max_remaining(3).unwrap(); /// assert_eq!(grant.buf().len(), 2); /// grant.commit(2); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub fn grant_max_remaining(&mut self, mut sz: usize) -> Result<GrantW<'a, N>> { let inner = unsafe { &self.bbq.as_ref() }; if atomic::swap(&inner.write_in_progress, true, AcqRel) { return Err(Error::GrantInProgress); } // Writer component. Must never write to `read`, // be careful writing to `load` let write = inner.write.load(Acquire); let read = inner.read.load(Acquire); let max = N; let already_inverted = write < read; let start = if already_inverted { // In inverted case, read is always > write let remain = read - write - 1; if remain != 0 { sz = min(remain, sz); write } else { // Inverted, no room is available inner.write_in_progress.store(false, Release); return Err(Error::InsufficientSize); } } else { if write != max { // Some (or all) room remaining in un-inverted case sz = min(max - write, sz); write } else { // Not inverted, but need to go inverted // NOTE: We check read > 1, NOT read >= 1, because // write must never == read in an inverted condition, since // we will then not be able to tell if we are inverted or not if read > 1 { sz = min(read - 1, sz); 0 } else { // Not invertible, no space inner.write_in_progress.store(false, Release); return Err(Error::InsufficientSize); } } }; // Safe write, only viewed by this task inner.reserve.store(start + sz, Release); // This is sound, as UnsafeCell, MaybeUninit, and GenericArray // are all `#[repr(Transparent)] let start_of_buf_ptr = inner.buf.get().cast::<u8>(); let grant_slice = unsafe { from_raw_parts_mut(start_of_buf_ptr.offset(start as isize), sz) }; Ok(GrantW { buf: grant_slice, bbq: self.bbq, to_commit: 0, }) } } /// `Consumer` is the primary interface for reading data from a `BBBuffer`. pub struct Consumer<'a, const N: usize> { bbq: NonNull<BBBuffer<N>>, pd: PhantomData<&'a ()>, } unsafe impl<'a, const N: usize> Send for Consumer<'a, N> {} impl<'a, const N: usize> Consumer<'a, N> { /// Obtains a contiguous slice of committed bytes. This slice may not /// contain ALL available bytes, if the writer has wrapped around. The /// remaining bytes will be available after all readable bytes are /// released /// /// ```rust /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create and split a new buffer of 6 elements /// let buffer: BBBuffer<6> = BBBuffer::new(); /// let (mut prod, mut cons) = buffer.try_split().unwrap(); /// /// // Successfully obtain and commit a grant of four bytes /// let mut grant = prod.grant_max_remaining(4).unwrap(); /// assert_eq!(grant.buf().len(), 4); /// grant.commit(4); /// /// // Obtain a read grant /// let mut grant = cons.read().unwrap(); /// assert_eq!(grant.buf().len(), 4); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub fn read(&mut self) -> Result<GrantR<'a, N>> { let inner = unsafe { &self.bbq.as_ref() }; if atomic::swap(&inner.read_in_progress, true, AcqRel) { return Err(Error::GrantInProgress); } let write = inner.write.load(Acquire); let last = inner.last.load(Acquire); let mut read = inner.read.load(Acquire); // Resolve the inverted case or end of read if (read == last) && (write < read) { read = 0; // This has some room for error, the other thread reads this // Impact to Grant: // Grant checks if read < write to see if inverted. If not inverted, but // no space left, Grant will initiate an inversion, but will not trigger it // Impact to Commit: // Commit does not check read, but if Grant has started an inversion, // grant could move Last to the prior write position // MOVING READ BACKWARDS! inner.read.store(0, Release); } let sz = if write < read { // Inverted, only believe last last } else { // Not inverted, only believe write write } - read; if sz == 0 { inner.read_in_progress.store(false, Release); return Err(Error::InsufficientSize); } // This is sound, as UnsafeCell, MaybeUninit, and GenericArray // are all `#[repr(Transparent)] let start_of_buf_ptr = inner.buf.get().cast::<u8>(); let grant_slice = unsafe { from_raw_parts_mut(start_of_buf_ptr.offset(read as isize), sz) }; Ok(GrantR { buf: grant_slice, bbq: self.bbq, to_release: 0, }) } /// Obtains two disjoint slices, which are each contiguous of committed bytes. /// Combined these contain all previously commited data. pub fn split_read(&mut self) -> Result<SplitGrantR<'a, N>> { let inner = unsafe { &self.bbq.as_ref() }; if atomic::swap(&inner.read_in_progress, true, AcqRel) { return Err(Error::GrantInProgress); } let write = inner.write.load(Acquire); let last = inner.last.load(Acquire); let mut read = inner.read.load(Acquire); // Resolve the inverted case or end of read if (read == last) && (write < read) { read = 0; // This has some room for error, the other thread reads this // Impact to Grant: // Grant checks if read < write to see if inverted. If not inverted, but // no space left, Grant will initiate an inversion, but will not trigger it // Impact to Commit: // Commit does not check read, but if Grant has started an inversion, // grant could move Last to the prior write position // MOVING READ BACKWARDS! inner.read.store(0, Release); } let (sz1, sz2) = if write < read { // Inverted, only believe last (last - read, write) } else { // Not inverted, only believe write (write - read, 0) }; if sz1 == 0 { inner.read_in_progress.store(false, Release); return Err(Error::InsufficientSize); } // This is sound, as UnsafeCell, MaybeUninit, and GenericArray // are all `#[repr(Transparent)] let start_of_buf_ptr = inner.buf.get().cast::<u8>(); let grant_slice1 = unsafe { from_raw_parts_mut(start_of_buf_ptr.offset(read as isize), sz1) }; let grant_slice2 = unsafe { from_raw_parts_mut(start_of_buf_ptr, sz2) }; Ok(SplitGrantR { buf1: grant_slice1, buf2: grant_slice2, bbq: self.bbq, to_release: 0, }) } } impl<const N: usize> BBBuffer<N> { /// Returns the size of the backing storage. /// /// This is the maximum number of bytes that can be stored in this queue. /// /// ```rust /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create a new buffer of 6 elements /// let buffer: BBBuffer<6> = BBBuffer::new(); /// assert_eq!(buffer.capacity(), 6); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub const fn capacity(&self) -> usize { N } } /// A structure representing a contiguous region of memory that /// may be written to, and potentially "committed" to the queue. /// /// NOTE: If the grant is dropped without explicitly commiting /// the contents, or by setting a the number of bytes to /// automatically be committed with `to_commit()`, then no bytes /// will be comitted for writing. /// /// If the `thumbv6` feature is selected, dropping the grant /// without committing it takes a short critical section, #[derive(Debug, PartialEq)] pub struct GrantW<'a, const N: usize> { pub(crate) buf: &'a mut [u8], bbq: NonNull<BBBuffer<N>>, pub(crate) to_commit: usize, } unsafe impl<'a, const N: usize> Send for GrantW<'a, N> {} /// A structure representing a contiguous region of memory that /// may be read from, and potentially "released" (or cleared) /// from the queue /// /// NOTE: If the grant is dropped without explicitly releasing /// the contents, or by setting the number of bytes to automatically /// be released with `to_release()`, then no bytes will be released /// as read. /// /// /// If the `thumbv6` feature is selected, dropping the grant /// without releasing it takes a short critical section, #[derive(Debug, PartialEq)] pub struct GrantR<'a, const N: usize> { pub(crate) buf: &'a mut [u8], bbq: NonNull<BBBuffer<N>>, pub(crate) to_release: usize, } /// A structure representing up to two contiguous regions of memory that /// may be read from, and potentially "released" (or cleared) /// from the queue #[derive(Debug, PartialEq)] pub struct SplitGrantR<'a, const N: usize> { pub(crate) buf1: &'a mut [u8], pub(crate) buf2: &'a mut [u8], bbq: NonNull<BBBuffer<N>>, pub(crate) to_release: usize, } unsafe impl<'a, const N: usize> Send for GrantR<'a, N> {} unsafe impl<'a, const N: usize> Send for SplitGrantR<'a, N> {} impl<'a, const N: usize> GrantW<'a, N> { /// Finalizes a writable grant given by `grant()` or `grant_max()`. /// This makes the data available to be read via `read()`. This consumes /// the grant. /// /// If `used` is larger than the given grant, the maximum amount will /// be commited /// /// NOTE: If the `thumbv6` feature is selected, this function takes a short critical /// section while committing. pub fn commit(mut self, used: usize) { self.commit_inner(used); forget(self); } /// Obtain access to the inner buffer for writing /// /// ```rust /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create and split a new buffer of 6 elements /// let buffer: BBBuffer<6> = BBBuffer::new(); /// let (mut prod, mut cons) = buffer.try_split().unwrap(); /// /// // Successfully obtain and commit a grant of four bytes /// let mut grant = prod.grant_max_remaining(4).unwrap(); /// grant.buf().copy_from_slice(&[1, 2, 3, 4]); /// grant.commit(4); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub fn buf(&mut self) -> &mut [u8] { self.buf } /// Sometimes, it's not possible for the lifetimes to check out. For example, /// if you need to hand this buffer to a function that expects to receive a /// `&'static mut [u8]`, it is not possible for the inner reference to outlive the /// grant itself. /// /// You MUST guarantee that in no cases, the reference that is returned here outlives /// the grant itself. Once the grant has been released, referencing the data contained /// WILL cause undefined behavior. /// /// Additionally, you must ensure that a separate reference to this data is not created /// to this data, e.g. using `DerefMut` or the `buf()` method of this grant. pub unsafe fn as_static_mut_buf(&mut self) -> &'static mut [u8] { transmute::<&mut [u8], &'static mut [u8]>(self.buf) } #[inline(always)] pub(crate) fn commit_inner(&mut self, used: usize) { let inner = unsafe { &self.bbq.as_ref() }; // If there is no grant in progress, return early. This // generally means we are dropping the grant within a // wrapper structure if !inner.write_in_progress.load(Acquire) { return; } // Writer component. Must never write to READ, // be careful writing to LAST // Saturate the grant commit let len = self.buf.len(); let used = min(len, used); let write = inner.write.load(Acquire); atomic::fetch_sub(&inner.reserve, len - used, AcqRel); let max = N; let last = inner.last.load(Acquire); let new_write = inner.reserve.load(Acquire); if (new_write < write) && (write != max) { // We have already wrapped, but we are skipping some bytes at the end of the ring. // Mark `last` where the write pointer used to be to hold the line here inner.last.store(write, Release); } else if new_write > last { // We're about to pass the last pointer, which was previously the artificial // end of the ring. Now that we've passed it, we can "unlock" the section // that was previously skipped. // // Since new_write is strictly larger than last, it is safe to move this as // the other thread will still be halted by the (about to be updated) write // value inner.last.store(max, Release); } // else: If new_write == last, either: // * last == max, so no need to write, OR // * If we write in the end chunk again, we'll update last to max next time // * If we write to the start chunk in a wrap, we'll update last when we // move write backwards // Write must be updated AFTER last, otherwise read could think it was // time to invert early! inner.write.store(new_write, Release); // Allow subsequent grants inner.write_in_progress.store(false, Release); } /// Configures the amount of bytes to be commited on drop. pub fn to_commit(&mut self, amt: usize) { self.to_commit = self.buf.len().min(amt); } } impl<'a, const N: usize> GrantR<'a, N> { /// Release a sequence of bytes from the buffer, allowing the space /// to be used by later writes. This consumes the grant. /// /// If `used` is larger than the given grant, the full grant will /// be released. /// /// NOTE: If the `thumbv6` feature is selected, this function takes a short critical /// section while releasing. pub fn release(mut self, used: usize) { // Saturate the grant release let used = min(self.buf.len(), used); self.release_inner(used); forget(self); } pub(crate) fn shrink(&mut self, len: usize) { let mut new_buf: &mut [u8] = &mut []; core::mem::swap(&mut self.buf, &mut new_buf); let (new, _) = new_buf.split_at_mut(len); self.buf = new; } /// Obtain access to the inner buffer for reading /// /// ``` /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create and split a new buffer of 6 elements /// let buffer: BBBuffer<6> = BBBuffer::new(); /// let (mut prod, mut cons) = buffer.try_split().unwrap(); /// /// // Successfully obtain and commit a grant of four bytes /// let mut grant = prod.grant_max_remaining(4).unwrap(); /// grant.buf().copy_from_slice(&[1, 2, 3, 4]); /// grant.commit(4); /// /// // Obtain a read grant, and copy to a buffer /// let mut grant = cons.read().unwrap(); /// let mut buf = [0u8; 4]; /// buf.copy_from_slice(grant.buf()); /// assert_eq!(&buf, &[1, 2, 3, 4]); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub fn buf(&self) -> &[u8] { self.buf } /// Obtain mutable access to the read grant /// /// This is useful if you are performing in-place operations /// on an incoming packet, such as decryption pub fn buf_mut(&mut self) -> &mut [u8] { self.buf } /// Sometimes, it's not possible for the lifetimes to check out. For example, /// if you need to hand this buffer to a function that expects to receive a /// `&'static [u8]`, it is not possible for the inner reference to outlive the /// grant itself. /// /// You MUST guarantee that in no cases, the reference that is returned here outlives /// the grant itself. Once the grant has been released, referencing the data contained /// WILL cause undefined behavior. /// /// Additionally, you must ensure that a separate reference to this data is not created /// to this data, e.g. using `Deref` or the `buf()` method of this grant. pub unsafe fn as_static_buf(&self) -> &'static [u8] { transmute::<&[u8], &'static [u8]>(self.buf) } #[inline(always)] pub(crate) fn release_inner(&mut self, used: usize) { let inner = unsafe { &self.bbq.as_ref() }; // If there is no grant in progress, return early. This // generally means we are dropping the grant within a // wrapper structure if !inner.read_in_progress.load(Acquire) { return; } // This should always be checked by the public interfaces debug_assert!(used <= self.buf.len()); // This should be fine, purely incrementing let _ = atomic::fetch_add(&inner.read, used, Release); inner.read_in_progress.store(false, Release); } /// Configures the amount of bytes to be released on drop. pub fn to_release(&mut self, amt: usize) { self.to_release = self.buf.len().min(amt); } } impl<'a, const N: usize> SplitGrantR<'a, N> { /// Release a sequence of bytes from the buffer, allowing the space /// to be used by later writes. This consumes the grant. /// /// If `used` is larger than the given grant, the full grant will /// be released. /// /// NOTE: If the `thumbv6` feature is selected, this function takes a short critical /// section while releasing. pub fn release(mut self, used: usize) { // Saturate the grant release let used = min(self.combined_len(), used); self.release_inner(used); forget(self); } /// Obtain access to both inner buffers for reading /// /// ``` /// # // bbqueue test shim! /// # fn bbqtest() { /// use bbqueue::BBBuffer; /// /// // Create and split a new buffer of 6 elements /// let buffer: BBBuffer<6> = BBBuffer::new(); /// let (mut prod, mut cons) = buffer.try_split().unwrap(); /// /// // Successfully obtain and commit a grant of four bytes /// let mut grant = prod.grant_max_remaining(4).unwrap(); /// grant.buf().copy_from_slice(&[1, 2, 3, 4]); /// grant.commit(4); /// /// // Obtain a read grant, and copy to a buffer /// let mut grant = cons.read().unwrap(); /// let mut buf = [0u8; 4]; /// buf.copy_from_slice(grant.buf()); /// assert_eq!(&buf, &[1, 2, 3, 4]); /// # // bbqueue test shim! /// # } /// # /// # fn main() { /// # #[cfg(not(feature = "thumbv6"))] /// # bbqtest(); /// # } /// ``` pub fn bufs(&self) -> (&[u8], &[u8]) { (self.buf1, self.buf2) } /// Obtain mutable access to both parts of the read grant /// /// This is useful if you are performing in-place operations /// on an incoming packet, such as decryption pub fn bufs_mut(&mut self) -> (&mut [u8], &mut [u8]) { (self.buf1, self.buf2) } #[inline(always)] pub(crate) fn release_inner(&mut self, used: usize) { let inner = unsafe { &self.bbq.as_ref() }; // If there is no grant in progress, return early. This // generally means we are dropping the grant within a // wrapper structure if !inner.read_in_progress.load(Acquire) { return; } // This should always be checked by the public interfaces debug_assert!(used <= self.combined_len()); if used <= self.buf1.len() { // This should be fine, purely incrementing let _ = atomic::fetch_add(&inner.read, used, Release); } else { // Also release parts of the second buffer inner.read.store(used - self.buf1.len(), Release); } inner.read_in_progress.store(false, Release); } /// Configures the amount of bytes to be released on drop. pub fn to_release(&mut self, amt: usize) { self.to_release = self.combined_len().min(amt); } /// The combined length of both buffers pub fn combined_len(&self) -> usize { self.buf1.len() + self.buf2.len() } } impl<'a, const N: usize> Drop for GrantW<'a, N> { fn drop(&mut self) { self.commit_inner(self.to_commit) } } impl<'a, const N: usize> Drop for GrantR<'a, N> { fn drop(&mut self) { self.release_inner(self.to_release) } } impl<'a, const N: usize> Drop for SplitGrantR<'a, N> { fn drop(&mut self) { self.release_inner(self.to_release) } } impl<'a, const N: usize> Deref for GrantW<'a, N> { type Target = [u8]; fn deref(&self) -> &Self::Target { self.buf } } impl<'a, const N: usize> DerefMut for GrantW<'a, N> { fn deref_mut(&mut self) -> &mut [u8] { self.buf } } impl<'a, const N: usize> Deref for GrantR<'a, N> { type Target = [u8]; fn deref(&self) -> &Self::Target { self.buf } } impl<'a, const N: usize> DerefMut for GrantR<'a, N> { fn deref_mut(&mut self) -> &mut [u8] { self.buf } } #[cfg(feature = "thumbv6")] mod atomic { use core::sync::atomic::{ AtomicBool, AtomicUsize, Ordering::{self, Acquire, Release}, }; use cortex_m::interrupt::free; #[inline(always)] pub fn fetch_add(atomic: &AtomicUsize, val: usize, _order: Ordering) -> usize { free(|_| { let prev = atomic.load(Acquire); atomic.store(prev.wrapping_add(val), Release); prev }) } #[inline(always)] pub fn fetch_sub(atomic: &AtomicUsize, val: usize, _order: Ordering) -> usize { free(|_| { let prev = atomic.load(Acquire); atomic.store(prev.wrapping_sub(val), Release); prev }) } #[inline(always)] pub fn swap(atomic: &AtomicBool, val: bool, _order: Ordering) -> bool { free(|_| { let prev = atomic.load(Acquire); atomic.store(val, Release); prev }) } } #[cfg(not(feature = "thumbv6"))] mod atomic { use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; #[inline(always)] pub fn fetch_add(atomic: &AtomicUsize, val: usize, order: Ordering) -> usize { atomic.fetch_add(val, order) } #[inline(always)] pub fn fetch_sub(atomic: &AtomicUsize, val: usize, order: Ordering) -> usize { atomic.fetch_sub(val, order) } #[inline(always)] pub fn swap(atomic: &AtomicBool, val: bool, order: Ordering) -> bool { atomic.swap(val, order) } }
use crate::base::LengthPrefixedVec; use crate::generated::{ErrorCode, ResponseType}; use flatbuffers::{FlatBufferBuilder, UnionWIPOffset, WIPOffset}; pub type ResultResponse<'a> = Result<FlatBufferResponse<'a>, ErrorCode>; pub type FlatBufferResponse<'a> = ( FlatBufferBuilder<'a>, ResponseType, WIPOffset<UnionWIPOffset>, ); // A response to be sent back to the client, which by default is assumed to be in the FlatBufferBuilder // but may be overriden with a different response. In that case the FlatBufferBuilder is just carried // along, so that it can be reused. pub struct FlatBufferWithResponse<'a> { buffer: FlatBufferBuilder<'a>, response: Option<LengthPrefixedVec>, } impl<'a> FlatBufferWithResponse<'a> { pub fn new(buffer: FlatBufferBuilder<'a>) -> FlatBufferWithResponse<'a> { FlatBufferWithResponse { buffer, response: None, } } pub fn with_separate_response( buffer: FlatBufferBuilder<'a>, response: LengthPrefixedVec, ) -> FlatBufferWithResponse<'a> { FlatBufferWithResponse { buffer, response: Some(response), } } pub fn into_buffer(self) -> FlatBufferBuilder<'a> { self.buffer } } impl<'a> AsRef<[u8]> for FlatBufferWithResponse<'a> { fn as_ref(&self) -> &[u8] { if let Some(ref response) = self.response { response.length_prefixed_bytes() } else { self.buffer.finished_data() } } }
use std::fs::File; use std::io::Read; #[macro_use] extern crate nom; // A named!(type_name(&str) -> &str, ws!(nom::alphanumeric)); // type A named!(type_start(&str) -> &str, fold_many1!( tuple!( tag!("type"), tag!(" "), type_name ), "", | _, (_, _, name) | name ) ); // extends A, B, C named!(type_extends(&str) -> Vec<String>, fold_many1!( pair!( ws!(tag!("extends")), many1!( pair!( type_name, opt!(ws!(tag!(","))) ) ) ), Vec::new(), | _, (_, list): (&str, Vec<(&str, Option<&str>)>) | { list.iter().map(| (name, _) | name.to_string()).collect() } ) ); #[derive(Debug)] struct TypeDef { name: String, extends: Vec<String>, } named!(type_defs(&str) -> Vec<TypeDef>, fold_many1!( complete!(ws!(tuple!( type_start, opt!(type_extends), ws!(tag!(";")) ))), Vec::new(), | mut acc: Vec<TypeDef>, (name, extends, _): (&str, Option<Vec<String>>, &str) | { acc.push( TypeDef { name: name.to_string(), extends: match extends { Some(extends) => extends, None => vec![] } } ); acc } ) ); fn main() { let mut file = File::open("test.tcss").unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); match type_defs(&contents) { Ok((_, res)) => println!("{:?}", res), Err(err) => println!("err: {:?}", err), } }
use failure::Error; use packet::Frame; use std::cmp::max; use std::collections::hash_map::Entry; use std::collections::HashMap; const MAX_REORDERING: u64 = 100; //FIXME: it really should be max bytes, not messages const MAX_QUEUE: usize = 1000; #[derive(Debug, Fail)] enum StreamError { #[fail( display = "stream underflow: incomming packet {} is too far ahead of previous {}", this, prev )] Underflow { prev: u64, this: u64 }, #[fail(display = "stream overflow: stream consumer is too slow")] Overflow, } pub struct OrderedStream { q: HashMap<u64, Frame>, producer: u64, consumer: u64, } impl OrderedStream { pub fn new() -> Self { Self { q: HashMap::new(), producer: 1, consumer: 1, } } pub fn push(&mut self, frame: Frame) -> Result<(), Error> { let order = frame.order(); assert!(order > 0); if self.producer + MAX_REORDERING < order { return Err(StreamError::Underflow { prev: self.producer, this: order, }.into()); } self.producer = max(self.producer, order); if self.q.len() > MAX_QUEUE { return Err(StreamError::Overflow.into()); } match self.q.entry(order) { Entry::Occupied(v) => { trace!("stream DUP frame with order {} {:?}", order, frame); assert_eq!(v.get().order(), order); } Entry::Vacant(v) => { trace!("stream pushed frame with order {} {:?}", order, frame); v.insert(frame); } } Ok(()) } pub fn pop(&mut self) -> Option<Frame> { if let Some(v) = self.q.remove(&self.consumer) { self.consumer += 1; Some(v) } else { None } } } #[test] pub fn overflow() { let mut st = OrderedStream::new(); for i in 1..MAX_QUEUE + 2 { st.push(Frame::Stream { order: i as u64, payload: Vec::new(), stream: 1, }).unwrap(); } assert!( st.push(Frame::Stream { order: MAX_QUEUE as u64 + 2, payload: Vec::new(), stream: 1, }).is_err() ); } #[test] pub fn underflow() { let mut st = OrderedStream::new(); assert!( st.push(Frame::Stream { order: MAX_REORDERING + 2, payload: Vec::new(), stream: 1, }).is_err() ); } #[test] pub fn ordered() { let mut st = OrderedStream::new(); for i in 1..20 { st.push(Frame::Stream { order: i as u64, payload: vec![i as u8], stream: 1, }).unwrap(); } for i in 1..20 { assert_eq!( st.pop().unwrap(), Frame::Stream { order: i as u64, payload: vec![i as u8], stream: 1, } ); } } #[test] pub fn unordered() { use rand::{thread_rng, Rng}; let mut pkg: Vec<u64> = (1..20).collect(); thread_rng().shuffle(&mut pkg); let mut st = OrderedStream::new(); for i in pkg { st.push(Frame::Stream { order: i as u64, payload: vec![i as u8], stream: 1, }).unwrap(); } for i in 1..20 { assert_eq!( st.pop().unwrap(), Frame::Stream { order: i as u64, payload: vec![i as u8], stream: 1, } ); } }
//! # The hacspec standard library //! //! ## Data types //! The standard library provides two main data types. //! //! ### Sequences //! Sequences [`Seq`](`seq::Seq`) arrays with a fixed length set at runtime. //! They replace Rust vectors, which are not allowed in hacspec. //! //! See the [seq](`mod@seq`) module documentation for more details. //! //! ``` //! use hacspec_lib::*; //! let x = Seq::<U128>::from_public_slice(&[5, 2, 7, 8, 9]); //! let x = Seq::<u128>::from_native_slice(&[5, 2, 7, 8, 9]); //! let y = ByteSeq::from_hex("0388dace60b6a392f328c2b971b2fe78"); //! ``` //! //! ### Arrays //! Arrays have a fixed length that is known at compile time. //! They replace the Rust arrays, which are not allowed in hacspec. //! //! See the [arrays](`mod@array`) module documentation for more details. //! //! To define a new array type with name `State`, holding `16` `u32` run //! //! ``` //! use hacspec_lib::*; //! array!(State, 16, u32, type_for_indexes: StateIdx); //! ``` //! //! The `type_for_indexes` defines the index type for this array as `StateIdx`. //! Such an array can now be used similarly to regular Rust arrays. //! //! ``` //! use hacspec_lib::*; //! array!(State, 16, u32, type_for_indexes: StateIdx); //! fn modify_state(mut state: State) -> State { //! state[1] = state[1] + state[2]; //! state //! } //! ``` //! //! ## Numeric Types //! The standard library provides two main numeric types. //! //! ### Math Integers //! Integers with a fixed upper bound on the byte length. //! See the [math integer](`mod@math_integers`) module documentation for more details. //! //! The following example defines and uses the type `LargeSecretInteger` that can hold unsigned integers up to 2^233-1. //! //! ``` //! use hacspec_lib::*; //! unsigned_integer!(LargeSecretInteger, 233); //! let a = LargeSecretInteger::from_literal(1); //! let b = LargeSecretInteger::from_literal(2); //! let c = a + b; //! let result = std::panic::catch_unwind(|| { //! // This panics because comparing secret math integers is currently not support. //! assert!(c.equal(LargeSecretInteger::from_literal(3))); //! }); //! assert!(result.is_err()); //! let _max = LargeSecretInteger::from_hex("1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); //! ``` //! //! ## Secret Integers //! All numeric types can be public or secret. //! By default they are secret types. //! Public types are prefixed with `public_`. //! //! ### Secret Machine Integers //! The regular machine integers Rust provides are considered public integers. //! This standard library defines secret variants for all public machine integers defined as follows. //! //! Unsigned secret integers: `U8, U16, U32, U64, U128` //! //! Signed secret integers: `I8, I16, I32, I64, I128` //! //! See the [secret integers](`secret_integers`) for details. #![no_std] #[cfg(all(feature = "alloc", not(feature = "std")))] extern crate alloc; #[cfg(feature = "std")] extern crate std as alloc; pub mod array; mod bigint_integers; mod machine_integers; pub mod math_integers; mod math_util; pub mod prelude; pub mod seq; mod traits; mod transmute; mod util; mod vec_integers; mod vec_integers_public; mod vec_integers_secret; mod vec_util; pub mod buf; pub use crate::prelude::*;
fn drink(beverage: &str) { if beverage == "lemonade" { panic!("AAAaaa!!!"); } println!("Some refreshing {} is all I need", beverage); } fn main() { drink("water"); drink("lemonade"); }
use std::ops::Index; #[derive(Debug)] pub struct Request <'a> { pub method: &'a str, pub path: String, } impl <'a> Request <'a> { pub fn new(buf: &[u8]) -> Option<Request> { let request_str = std::str::from_utf8(buf).ok()?; let mut first_line = request_str.split("\r\n").next()?.split(" "); let method = first_line.next()?; let mut buf_path = first_line.next()?; let mut path = String::from(buf_path); path = percent_encoding::percent_decode_str(path.as_str()).decode_utf8_lossy().to_string(); if path.contains("?") { path.truncate(path.find("?")?); } Some(Request { method, path, }) } }
#[doc = "Register `MISR` reader"] pub type R = crate::R<MISR_SPEC>; #[doc = "Field `TAMP1MF` reader - TAMP1 non-secure interrupt masked flag This flag is set by hardware when the tamper 1 non-secure interrupt is raised."] pub type TAMP1MF_R = crate::BitReader; #[doc = "Field `TAMP2MF` reader - TAMP2 non-secure interrupt masked flag This flag is set by hardware when the tamper 2 non-secure interrupt is raised."] pub type TAMP2MF_R = crate::BitReader; #[doc = "Field `TAMP3MF` reader - TAMP3 non-secure interrupt masked flag This flag is set by hardware when the tamper 3 non-secure interrupt is raised."] pub type TAMP3MF_R = crate::BitReader; #[doc = "Field `TAMP4MF` reader - TAMP4 non-secure interrupt masked flag This flag is set by hardware when the tamper 4 non-secure interrupt is raised."] pub type TAMP4MF_R = crate::BitReader; #[doc = "Field `TAMP5MF` reader - TAMP5 non-secure interrupt masked flag This flag is set by hardware when the tamper 5 non-secure interrupt is raised."] pub type TAMP5MF_R = crate::BitReader; #[doc = "Field `TAMP6MF` reader - TAMP6 non-secure interrupt masked flag This flag is set by hardware when the tamper 6 non-secure interrupt is raised."] pub type TAMP6MF_R = crate::BitReader; #[doc = "Field `TAMP7MF` reader - TAMP7 non-secure interrupt masked flag This flag is set by hardware when the tamper 7 non-secure interrupt is raised."] pub type TAMP7MF_R = crate::BitReader; #[doc = "Field `TAMP8MF` reader - TAMP8 non-secure interrupt masked flag This flag is set by hardware when the tamper 8 non-secure interrupt is raised."] pub type TAMP8MF_R = crate::BitReader; #[doc = "Field `ITAMP1MF` reader - Internal tamper 1 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 1 non-secure interrupt is raised."] pub type ITAMP1MF_R = crate::BitReader; #[doc = "Field `ITAMP2MF` reader - Internal tamper 2 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 2 non-secure interrupt is raised."] pub type ITAMP2MF_R = crate::BitReader; #[doc = "Field `ITAMP3MF` reader - Internal tamper 3 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 3 non-secure interrupt is raised."] pub type ITAMP3MF_R = crate::BitReader; #[doc = "Field `ITAMP4MF` reader - Internal tamper 4 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 4 non-secure interrupt is raised."] pub type ITAMP4MF_R = crate::BitReader; #[doc = "Field `ITAMP5MF` reader - Internal tamper 5 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 5 non-secure interrupt is raised."] pub type ITAMP5MF_R = crate::BitReader; #[doc = "Field `ITAMP6MF` reader - Internal tamper 6 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 6 non-secure interrupt is raised."] pub type ITAMP6MF_R = crate::BitReader; #[doc = "Field `ITAMP7MF` reader - Internal tamper 7 tamper non-secure interrupt masked flag This flag is set by hardware when the internal tamper 7 non-secure interrupt is raised."] pub type ITAMP7MF_R = crate::BitReader; #[doc = "Field `ITAMP8MF` reader - Internal tamper 8 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 8 non-secure interrupt is raised."] pub type ITAMP8MF_R = crate::BitReader; #[doc = "Field `ITAMP9MF` reader - internal tamper 9 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 9 non-secure interrupt is raised."] pub type ITAMP9MF_R = crate::BitReader; #[doc = "Field `ITAMP11MF` reader - internal tamper 11 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 11 non-secure interrupt is raised."] pub type ITAMP11MF_R = crate::BitReader; #[doc = "Field `ITAMP12MF` reader - internal tamper 12 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 12 non-secure interrupt is raised."] pub type ITAMP12MF_R = crate::BitReader; #[doc = "Field `ITAMP13MF` reader - internal tamper 13 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 13 non-secure interrupt is raised."] pub type ITAMP13MF_R = crate::BitReader; #[doc = "Field `ITAMP15MF` reader - internal tamper 15 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 15 non-secure interrupt is raised."] pub type ITAMP15MF_R = crate::BitReader; impl R { #[doc = "Bit 0 - TAMP1 non-secure interrupt masked flag This flag is set by hardware when the tamper 1 non-secure interrupt is raised."] #[inline(always)] pub fn tamp1mf(&self) -> TAMP1MF_R { TAMP1MF_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - TAMP2 non-secure interrupt masked flag This flag is set by hardware when the tamper 2 non-secure interrupt is raised."] #[inline(always)] pub fn tamp2mf(&self) -> TAMP2MF_R { TAMP2MF_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - TAMP3 non-secure interrupt masked flag This flag is set by hardware when the tamper 3 non-secure interrupt is raised."] #[inline(always)] pub fn tamp3mf(&self) -> TAMP3MF_R { TAMP3MF_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - TAMP4 non-secure interrupt masked flag This flag is set by hardware when the tamper 4 non-secure interrupt is raised."] #[inline(always)] pub fn tamp4mf(&self) -> TAMP4MF_R { TAMP4MF_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - TAMP5 non-secure interrupt masked flag This flag is set by hardware when the tamper 5 non-secure interrupt is raised."] #[inline(always)] pub fn tamp5mf(&self) -> TAMP5MF_R { TAMP5MF_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - TAMP6 non-secure interrupt masked flag This flag is set by hardware when the tamper 6 non-secure interrupt is raised."] #[inline(always)] pub fn tamp6mf(&self) -> TAMP6MF_R { TAMP6MF_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - TAMP7 non-secure interrupt masked flag This flag is set by hardware when the tamper 7 non-secure interrupt is raised."] #[inline(always)] pub fn tamp7mf(&self) -> TAMP7MF_R { TAMP7MF_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - TAMP8 non-secure interrupt masked flag This flag is set by hardware when the tamper 8 non-secure interrupt is raised."] #[inline(always)] pub fn tamp8mf(&self) -> TAMP8MF_R { TAMP8MF_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 16 - Internal tamper 1 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 1 non-secure interrupt is raised."] #[inline(always)] pub fn itamp1mf(&self) -> ITAMP1MF_R { ITAMP1MF_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Internal tamper 2 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 2 non-secure interrupt is raised."] #[inline(always)] pub fn itamp2mf(&self) -> ITAMP2MF_R { ITAMP2MF_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - Internal tamper 3 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 3 non-secure interrupt is raised."] #[inline(always)] pub fn itamp3mf(&self) -> ITAMP3MF_R { ITAMP3MF_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - Internal tamper 4 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 4 non-secure interrupt is raised."] #[inline(always)] pub fn itamp4mf(&self) -> ITAMP4MF_R { ITAMP4MF_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - Internal tamper 5 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 5 non-secure interrupt is raised."] #[inline(always)] pub fn itamp5mf(&self) -> ITAMP5MF_R { ITAMP5MF_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - Internal tamper 6 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 6 non-secure interrupt is raised."] #[inline(always)] pub fn itamp6mf(&self) -> ITAMP6MF_R { ITAMP6MF_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - Internal tamper 7 tamper non-secure interrupt masked flag This flag is set by hardware when the internal tamper 7 non-secure interrupt is raised."] #[inline(always)] pub fn itamp7mf(&self) -> ITAMP7MF_R { ITAMP7MF_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - Internal tamper 8 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 8 non-secure interrupt is raised."] #[inline(always)] pub fn itamp8mf(&self) -> ITAMP8MF_R { ITAMP8MF_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - internal tamper 9 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 9 non-secure interrupt is raised."] #[inline(always)] pub fn itamp9mf(&self) -> ITAMP9MF_R { ITAMP9MF_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 26 - internal tamper 11 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 11 non-secure interrupt is raised."] #[inline(always)] pub fn itamp11mf(&self) -> ITAMP11MF_R { ITAMP11MF_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - internal tamper 12 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 12 non-secure interrupt is raised."] #[inline(always)] pub fn itamp12mf(&self) -> ITAMP12MF_R { ITAMP12MF_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - internal tamper 13 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 13 non-secure interrupt is raised."] #[inline(always)] pub fn itamp13mf(&self) -> ITAMP13MF_R { ITAMP13MF_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 30 - internal tamper 15 non-secure interrupt masked flag This flag is set by hardware when the internal tamper 15 non-secure interrupt is raised."] #[inline(always)] pub fn itamp15mf(&self) -> ITAMP15MF_R { ITAMP15MF_R::new(((self.bits >> 30) & 1) != 0) } } #[doc = "TAMP non-secure masked interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`misr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MISR_SPEC; impl crate::RegisterSpec for MISR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`misr::R`](R) reader structure"] impl crate::Readable for MISR_SPEC {} #[doc = "`reset()` method sets MISR to value 0"] impl crate::Resettable for MISR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use tonic::{transport::Server, Request, Response, Status}; /** * Generated gRPC Stub / Skeleton */ // Stub Import Syntax: <package_name>::<service_name_server>::{ServiceName, ServiceNameServer}; use ordermgmt::order_management_server::{OrderManagement, OrderManagementServer}; // Import Message: <message_name> use ordermgmt::{Order}; mod ordermgmt; #[derive(Debug, Default)] pub struct MyOrderManagementService {} #[tonic::async_trait] impl OrderManagement for MyOrderManagementService { async fn get_order(&self, request: Request<String>) -> Result<Response<Order>, Status> { println!("{:?}", request.into_inner()); Ok(Response::new( Order { id: "21".into(), items: vec!["Test".into()], description: "Test".into(), price: 12.00, destination: "HOme".into() } )) } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let addr = "[::1]:50051".parse()?; let ecomm_service = MyOrderManagementService::default(); println!("Starting gRPC Server...."); Server::builder() .add_service(OrderManagementServer::new(ecomm_service)) .serve(addr) .await?; Ok(()) }
/*! # fltk-rs [![Documentation](https://docs.rs/fltk/badge.svg)](https://docs.rs/fltk) [![Crates.io](https://img.shields.io/crates/v/fltk.svg)](https://crates.io/crates/fltk) [![License](https://img.shields.io/crates/l/fltk.svg)](https://github.com/fltk-rs/fltk-rs/blob/master/LICENSE) [![Build](https://github.com/fltk-rs/fltk-rs/workflows/Build/badge.svg?branch=master)](https://github.com/fltk-rs/fltk-rs/actions) Rust bindings for the FLTK Graphical User Interface library. The fltk crate is a crossplatform lightweight gui library which can be statically linked to produce small, self-contained (no dependencies) and fast gui applications. Tutorials: - [Video](https://github.com/fltk-rs/fltk-rs#tutorials) - [Written](https://github.com/fltk-rs/fltk-rs/wiki) Here is a [list](https://en.wikipedia.org/wiki/FLTK#Use) of software using FLTK. For software using fltk-rs, check [here](https://github.com/fltk-rs/fltk-rs/issues/418). - [Link](https://github.com/fltk/fltk) to the official FLTK repository. - [Link](https://www.fltk.org/doc-1.3/index.html) to the official documentation. ## Usage Just add the following to your project's Cargo.toml file: ```toml [dependencies] fltk = "^1" ``` To use the latest changes in the repo: ```toml [dependencies] fltk = { version = "^1", git = "https://github.com/fltk-rs/fltk-rs" } ``` To use the bundled libs (available for x64 windows (msvc & gnu (msys2)), x64 linux & macos): ```toml [dependencies] fltk = { version = "^1", features = ["fltk-bundled"] } ``` The library is automatically built and statically linked to your binary. For faster builds you can enable ninja builds for the C++ source using the "use-ninja" feature. An example hello world application: ```rust,no_run use fltk::{app, prelude::*, window::Window}; let app = app::App::default(); let mut wind = Window::new(100, 100, 400, 300, "Hello from rust"); wind.end(); wind.show(); app.run().unwrap(); ``` Another example showing the basic callback functionality: ```rust,no_run use fltk::{app, button::Button, frame::Frame, prelude::*, window::Window}; let app = app::App::default(); let mut wind = Window::new(100, 100, 400, 300, "Hello from rust"); let mut frame = Frame::new(0, 0, 400, 200, ""); let mut but = Button::new(160, 210, 80, 40, "Click me!"); wind.end(); wind.show(); but.set_callback(move |_| frame.set_label("Hello World!")); app.run().unwrap(); ``` Please check the examples directory for more examples. You will notice that all widgets are instantiated with a new() method, taking the x and y coordinates, the width and height of the widget, as well as a label which can be left blank if needed. Another way to initialize a widget is using the builder pattern: (The following buttons are equivalent) ```rust,no_run use fltk::{button::*, prelude::*}; let but1 = Button::new(10, 10, 80, 40, "Button 1"); let but2 = Button::default() .with_pos(10, 10) .with_size(80, 40) .with_label("Button 2"); ``` An example of a counter showing use of the builder pattern: ```rust,no_run use fltk::{app, button::*, frame::*, prelude::*, window::*}; let app = app::App::default(); let mut wind = Window::default() .with_size(160, 200) .center_screen() .with_label("Counter"); let mut frame = Frame::default() .with_size(100, 40) .center_of(&wind) .with_label("0"); let mut but_inc = Button::default() .size_of(&frame) .above_of(&frame, 0) .with_label("+"); let mut but_dec = Button::default() .size_of(&frame) .below_of(&frame, 0) .with_label("-"); wind.make_resizable(true); wind.end(); wind.show(); /* Event handling */ ``` Alternatively, you can use packs to layout your widgets: ```rust,no_run use fltk::{button::*, frame::*, group::*, prelude::*, window::*}; let mut wind = Window::default().with_size(160, 200).with_label("Counter"); // Vertical is default. You can choose horizontal using pack.set_type(PackType::Horizontal); let mut pack = Pack::default().with_size(120, 140).center_of(&wind); pack.set_spacing(10); let mut but_inc = Button::default().with_size(0, 40).with_label("+"); let mut frame = Frame::default().with_size(0, 40).with_label("0"); let mut but_dec = Button::default().with_size(0, 40).with_label("-"); pack.end(); ``` ### Events Events can be handled using the `set_callback` method (as above) or the available `fltk::app::set_callback()` free function, which will handle the default trigger of each widget(like clicks for buttons): ```rust,ignore /* previous hello world code */ but.set_callback(move |_| frame.set_label("Hello World!")); app.run().unwrap(); ``` Another way is to use message passing: ```rust,ignore /* previous counter code */ let (s, r) = app::channel::<Message>(); but_inc.emit(s, Message::Increment); but_dec.emit(s, Message::Decrement); while app.wait() { let label: i32 = frame.label().parse().unwrap(); if let Some(msg) = r.recv() { match msg { Message::Increment => frame.set_label(&(label + 1).to_string()), Message::Decrement => frame.set_label(&(label - 1).to_string()), } } } ``` For the remainder of the code, check the full example [here](https://github.com/fltk-rs/fltk-rs/blob/master/fltk/examples/counter2.rs). For custom event handling, the handle() method can be used: ```rust,ignore some_widget.handle(move |widget, ev: Event| { match ev { /* handle ev */ } }); ``` Handled or ignored events using the handle method should return true, unhandled events should return false. More examples are available in the examples directory. ### Theming FLTK offers 4 application themes (called schemes): - Base - Gtk - Gleam - Plastic These can be set using the `App::with_scheme()` function. ```rust,ignore let app = app::App::default().with_scheme(app::Scheme::Gleam); ``` Themes of individual widgets can be optionally modified using the provided methods in the `WidgetExt` trait, such as `set_color()`, `set_label_font()`, `set_frame()` etc: ```rust,ignore some_button.set_color(Color::Light1); //! You can use one of the provided colors in the fltk enums some_button.set_color(Color::from_rgb(255, 0, 0)); //! Or you can specify a color by rgb or hex/u32 value some_button.set_color(Color::from_u32(0xffebee)); some_button.set_frame(FrameType::RoundUpBox); some_button.set_font(Font::TimesItalic); ``` ## Features The following are the features offered by the crate: - use-ninja: If you have ninja build installed, it builds faster than make or VS - system-libpng: Uses the system libpng - system-libjpeg: Uses the system libjpeg - system-zlib: Uses the system zlib - fltk-bundled: Support for bundled versions of cfltk and fltk on selected platforms (requires curl and tar) - no-pango: Build without pango support on Linux/BSD. - enable-glwindow: Support for drawing using OpenGL functions. ## Dependencies Rust (version > 1.38), CMake (version > 3.0), Git and a C++11 compiler need to be installed and in your PATH for a crossplatform build from source. This crate also offers a bundled form of fltk on selected platforms, this can be enabled using the fltk-bundled feature flag (which requires curl and tar to download and unpack the bundled libraries). - Windows: No dependencies. - MacOS: No dependencies. - Linux/BSD: X11 and OpenGL development headers need to be installed for development. The libraries themselves are available on linux distros with a graphical user interface. For Debian-based GUI distributions, that means running: ```ignore $ sudo apt-get install libx11-dev libxext-dev libxft-dev libxinerama-dev libxcursor-dev libxrender-dev libxfixes-dev libpango1.0-dev libpng-dev libgl1-mesa-dev libglu1-mesa-dev ``` For RHEL-based GUI distributions, that means running: ```ignore $ sudo yum groupinstall "X Software Development" && yum install pango-devel libXinerama-devel libpng-devel ``` For Arch-based GUI distributions, that means running: ```ignore $ sudo pacman -S libx11 libxext libxft libxinerama libxcursor libxrender libxfixes libpng pango cairo libgl mesa --needed ``` For Alpine linux: ```ignore $ apk add pango-dev fontconfig-dev libxinerama-dev libxfixes-dev libxcursor-dev libpng-dev mesa-gl ``` For NixOS (Linux distribution) this `nix-shell` environment can be used: ```ignore $ nix-shell --packages rustc cmake git gcc xorg.libXext xorg.libXft xorg.libXinerama xorg.libXcursor xorg.libXrender xorg.libXfixes libpng libcerf pango cairo libGL mesa pkg-config ``` - Android(experimental): Android Studio, Android Sdk, Android Ndk. ## FAQ please check the [FAQ](https://github.com/fltk-rs/fltk-rs/blob/master/FAQ.md) page for frequently asked questions, encountered issues, guides on deployment, and contribution. */ #![allow(non_upper_case_globals)] #![warn(missing_docs)] #![warn(broken_intra_doc_links)] /// Application related methods and functions pub mod app; /// Browser widgets pub mod browser; /// Button widgets pub mod button; /// Dialog widgets pub mod dialog; /// Drawing primitives pub mod draw; /// Fltk defined enums: Color, Font, `CallbackTrigger` etc pub mod enums; /// Basic fltk box/frame widget pub mod frame; /// Group widgets pub mod group; /// Image types supported by fltk pub mod image; /// Input widgets pub mod input; /// Menu widgets pub mod menu; /// Miscellaneous widgets not fitting a certain group pub mod misc; /// Output widgets pub mod output; /// All fltk widget traits and flt error types pub mod prelude; /// Widget surface to image functions pub mod surface; /// Table widgets pub mod table; /// Text display widgets pub mod text; /// Tree widgets pub mod tree; /// General utility functions pub mod utils; /// Valuator widgets pub mod valuator; /// Basic empty widget pub mod widget; /// Window widgets pub mod window; /// Printing related functions #[cfg(not(target_os = "android"))] pub mod printer; #[macro_use] extern crate fltk_derive; #[macro_use] extern crate lazy_static; #[macro_use] extern crate bitflags; #[cfg(target_os = "macos")] #[macro_use] extern crate objc;
mod meta; use std::{ io::{Error, ErrorKind, Result}, usize, }; pub const HEADER_LEN: usize = 24; use byteorder::{BigEndian, ByteOrder}; use crate::{MetaType, Protocol, Request, RingSlice}; #[inline] pub fn body_len(header: &[u8]) -> u32 { debug_assert!(header.len() >= 12); BigEndian::read_u32(&header[8..]) } // https://github.com/memcached/memcached/wiki/BinaryProtocolRevamped#command-opcodes // MC包含Get, Gets, Store, Meta四类命令,索引分别是0-3 const COMMAND_IDX: [u8; 128] = [ 0, 2, 2, 2, 2, 2, 2, 3, 3, 1, 1, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; // OP_CODE对应的noreply code。 const NOREPLY_MAPPING: [u8; 128] = [ 0x09, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x09, 0x0a, 0x0b, 0x0d, 0x0d, 0x19, 0x1a, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x32, 0x32, 0x34, 0x34, 0x36, 0x36, 0x38, 0x38, 0x3a, 0x3a, 0x3c, 0x3c, 0x3d, 0x3e, 0x3f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; const REQUEST_MAGIC: u8 = 0x80; const OP_CODE_NOOP: u8 = 0x0a; // 0x09: getq // 0x0d: getkq const MULT_GETS: [u8; 128] = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; #[derive(Clone)] pub struct MemcacheBinary; impl MemcacheBinary { pub fn new() -> Self { MemcacheBinary } #[inline(always)] fn is_multi_get(&self, op_code: u8) -> bool { MULT_GETS[op_code as usize] == 1 } #[inline] fn _probe_request(&self, req: &[u8]) -> (bool, usize) { let mut read = 0usize; while read + HEADER_LEN <= req.len() { // 当前请求的body let total = body_len(&req[read as usize..]) as usize + HEADER_LEN; if read as usize + total > req.len() { return (false, req.len()); } let op_code = req[read + 1]; read += total; // 0xd是getq请求,说明当前请求是multiget请求,最后通常一个noop请求结束 if !self.is_multi_get(op_code) { let pos = read; return (true, pos); } } (false, req.len()) } #[inline(always)] fn _noreply(&self, req: &[u8]) -> bool { req[1] == NOREPLY_MAPPING[req[1] as usize] } } impl Protocol for MemcacheBinary { #[inline] // 如果当前请求已经是noreply了,则直接clone。 // 否则把数据复制出来,再更改op_code fn copy_noreply(&self, req: &Request) -> Request { let data = req.data(); debug_assert!(data.len() >= HEADER_LEN); if req.noreply() { req.clone() } else { let noreply = self._noreply(data); if noreply { let mut new = req.clone(); new.set_noreply(); new } else { let mut v = vec![0u8; data.len()]; use std::ptr::copy_nonoverlapping as copy; unsafe { copy(data.as_ptr(), v.as_mut_ptr(), data.len()); } v[1] = NOREPLY_MAPPING[data[1] as usize]; let mut new = Request::from_vec(v, req.id()); new.set_noreply(); new } } } #[inline(always)] fn parse_request(&self, req: &[u8]) -> Result<(bool, usize)> { //debug_assert!(req.len() >= self.min_size()); if req[0] != REQUEST_MAGIC { Err(Error::new( ErrorKind::InvalidData, "not a valid protocol, the magic number must be 0x80 on mc binary protocol", )) } else { if req.len() < HEADER_LEN { return Ok((false, req.len())); } let (done, n) = self._probe_request(req); Ok((done, n)) } } // 调用方确保req是一个完整的mc的请求包。 // 第二个字节是op_code。 #[inline] fn op_route(&self, req: &[u8]) -> usize { COMMAND_IDX[req[1] as usize] as usize } fn meta_type(&self, _req: &[u8]) -> MetaType { MetaType::Version } // TODO 只有multiget 都会调用 #[inline] fn trim_eof<T: AsRef<RingSlice>>(&self, _resp: T) -> usize { HEADER_LEN } #[inline] fn key<'a>(&self, req: &'a [u8]) -> &'a [u8] { debug_assert!(req.len() >= HEADER_LEN); let extra_len = req[4] as usize; let offset = extra_len + HEADER_LEN; let key_len = BigEndian::read_u16(&req[2..]) as usize; debug_assert!(key_len + offset <= req.len()); &req[offset..offset + key_len] } #[inline] fn keys<'a>(&self, _req: &'a [u8]) -> Vec<&'a [u8]> { todo!() } fn build_gets_cmd(&self, _keys: Vec<&[u8]>) -> Vec<u8> { todo!() } fn response_found<T: AsRef<RingSlice>>(&self, response: T) -> bool { let slice = response.as_ref(); debug_assert!(slice.len() >= HEADER_LEN); slice.at(6) == 0 && slice.at(7) == 0 } fn parse_response(&self, response: &RingSlice) -> (bool, usize) { let mut read = 0; let avail = response.available(); loop { if avail < read + HEADER_LEN { return (false, avail); } debug_assert_eq!(response.at(0), 0x81); let len = response.read_u32(read + 8) as usize + HEADER_LEN; if self.is_multi_get(response.at(read + 1)) { read += len; continue; } let n = read + len; return (avail >= n, n); } } // 轮询response,找出本次查询到的keys,loop所在的位置 fn keys_response<'a, T>(&self, resp: T) -> Vec<String> where T: Iterator<Item = &'a RingSlice>, { let mut keys: Vec<String> = Vec::new(); for slice in resp { self.scan_response_keys(slice, &mut keys); } return keys; } // 轮询response,找出本次查询到的keys,loop所在的位置 fn scan_response_keys(&self, response: &RingSlice, keys: &mut Vec<String>) { let mut read = 0; let avail = response.available(); loop { if avail < read + HEADER_LEN { // 这种情况不应该出现 debug_assert!(false); return; } debug_assert_eq!(response.at(read), 0x81); // op_getkq 是最后一个response if response.at(read + 1) == OP_CODE_NOOP { return; } let len = response.read_u32(read + 8) as usize + HEADER_LEN; debug_assert!(read + len <= avail); // key 获取 let key_len = response.read_u16(read + 2); let extra_len = response.at(read + 4); let key = response.read_bytes(read + HEADER_LEN + extra_len as usize, key_len as usize); keys.push(key); read += len; if read == avail { return; } } } fn rebuild_get_multi_request( &self, current_cmds: &Request, found_keys: &Vec<String>, new_cmds: &mut Vec<u8>, ) { let mut read = 0; let origin = current_cmds.data(); let avail = origin.len(); loop { // noop 是24 bytes debug_assert!(read + HEADER_LEN <= avail); debug_assert_eq!(origin[read], 0x80); // get-multi的结尾是noop if origin[read + 1] == OP_CODE_NOOP { if new_cmds.len() == 0 { //全部命中,不用构建新的cmd了 return; } new_cmds.extend(&origin[read..read + HEADER_LEN]); debug_assert_eq!(read + HEADER_LEN, avail); return; } // 非noop cmd一定不是最后一个cmd let len = BigEndian::read_u32(&origin[read + 8..]) as usize + HEADER_LEN; debug_assert!(read + len < avail); // 找到key,如果是命中的key,则对应cmd被略过 let key_len = BigEndian::read_u16(&origin[read + 2..]) as usize; let extra_len = origin[read + 4] as usize; let extra_pos = read + HEADER_LEN + extra_len; let mut key_data = Vec::new(); key_data.extend_from_slice(&origin[extra_pos..extra_pos + key_len]); let key = String::from_utf8(key_data).unwrap_or_default(); if found_keys.contains(&key) { // key 已经命中,略过 read += len; continue; } // 该key miss,将其cmd写入new_cmds new_cmds.extend(&origin[read..read + len]); read += len; } } }
use crate::commands::autoview; use crate::commands::classified::{ ClassifiedCommand, ClassifiedInputStream, ClassifiedPipeline, ExternalCommand, InternalCommand, StreamNext, }; use crate::commands::plugin::JsonRpc; use crate::commands::plugin::{PluginCommand, PluginSink}; use crate::commands::whole_stream_command; use crate::context::Context; use crate::data::config; use crate::data::Value; pub(crate) use crate::errors::ShellError; use crate::fuzzysearch::{interactive_fuzzy_search, SelectionResult}; use crate::git::current_branch; use crate::parser::registry::Signature; use crate::parser::{hir, CallNode, Pipeline, PipelineElement, TokenNode}; use crate::prelude::*; use log::{debug, trace}; use rustyline::error::ReadlineError; use rustyline::{self, config::Configurer, config::EditMode, ColorMode, Config, Editor}; use std::env; use std::error::Error; use std::io::{BufRead, BufReader, Write}; use std::iter::Iterator; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; #[derive(Debug)] pub enum MaybeOwned<'a, T> { Owned(T), Borrowed(&'a T), } impl<T> MaybeOwned<'_, T> { pub fn borrow(&self) -> &T { match self { MaybeOwned::Owned(v) => v, MaybeOwned::Borrowed(v) => v, } } } fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), ShellError> { let mut child = std::process::Command::new(path) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .spawn() .expect("Failed to spawn child process"); let stdin = child.stdin.as_mut().expect("Failed to open stdin"); let stdout = child.stdout.as_mut().expect("Failed to open stdout"); let mut reader = BufReader::new(stdout); let request = JsonRpc::new("config", Vec::<Value>::new()); let request_raw = serde_json::to_string(&request)?; stdin.write(format!("{}\n", request_raw).as_bytes())?; let path = dunce::canonicalize(path)?; let mut input = String::new(); let result = match reader.read_line(&mut input) { Ok(count) => { trace!("processing response ({} bytes)", count); trace!("response: {}", input); let response = serde_json::from_str::<JsonRpc<Result<Signature, ShellError>>>(&input); match response { Ok(jrpc) => match jrpc.params { Ok(params) => { let fname = path.to_string_lossy(); trace!("processing {:?}", params); let name = params.name.clone(); let fname = fname.to_string(); if context.has_command(&name) { trace!("plugin {:?} already loaded.", &name); } else { if params.is_filter { context.add_commands(vec![whole_stream_command( PluginCommand::new(name, fname, params), )]); } else { context.add_commands(vec![whole_stream_command(PluginSink::new( name, fname, params, ))]); }; } Ok(()) } Err(e) => Err(e), }, Err(e) => { trace!("incompatible plugin {:?}", input); Err(ShellError::string(format!("Error: {:?}", e))) } } } Err(e) => Err(ShellError::string(format!("Error: {:?}", e))), }; let _ = child.wait(); result } fn search_paths() -> Vec<std::path::PathBuf> { let mut search_paths = Vec::new(); match env::var_os("PATH") { Some(paths) => { search_paths = env::split_paths(&paths).collect::<Vec<_>>(); } None => println!("PATH is not defined in the environment."), } #[cfg(debug_assertions)] { // Use our debug plugins in debug mode let mut path = std::path::PathBuf::from("."); path.push("target"); path.push("debug"); if path.exists() { search_paths.push(path); } } #[cfg(not(debug_assertions))] { // Use our release plugins in release mode let mut path = std::path::PathBuf::from("."); path.push("target"); path.push("release"); if path.exists() { search_paths.push(path); } } // permit Nu finding and picking up development plugins // if there are any first. search_paths.reverse(); search_paths } fn load_plugins(context: &mut Context) -> Result<(), ShellError> { let opts = glob::MatchOptions { case_sensitive: false, require_literal_separator: false, require_literal_leading_dot: false, }; for path in search_paths() { let mut pattern = path.to_path_buf(); pattern.push(std::path::Path::new("nu_plugin_[a-z]*")); match glob::glob_with(&pattern.to_string_lossy(), opts) { Err(_) => {} Ok(binaries) => { for bin in binaries.filter_map(Result::ok) { if !bin.is_file() { continue; } let bin_name = { if let Some(name) = bin.file_name() { match name.to_str() { Some(raw) => raw, None => continue, } } else { continue; } }; let is_valid_name = { #[cfg(windows)] { bin_name .chars() .all(|c| c.is_ascii_alphabetic() || c == '_' || c == '.') } #[cfg(not(windows))] { bin_name .chars() .all(|c| c.is_ascii_alphabetic() || c == '_') } }; let is_executable = { #[cfg(windows)] { bin_name.ends_with(".exe") || bin_name.ends_with(".bat") } #[cfg(not(windows))] { true } }; if is_valid_name && is_executable { trace!("Trying {:?}", bin.display()); // we are ok if this plugin load fails let _ = load_plugin(&bin, context); } } } } } Ok(()) } pub struct History; impl History { pub fn path() -> PathBuf { const FNAME: &str = "history.txt"; config::user_data() .map(|mut p| { p.push(FNAME); p }) .unwrap_or(PathBuf::from(FNAME)) } } pub async fn cli() -> Result<(), Box<dyn Error>> { let mut context = Context::basic()?; { use crate::commands::*; context.add_commands(vec![ whole_stream_command(PWD), whole_stream_command(LS), whole_stream_command(CD), whole_stream_command(Size), whole_stream_command(Nth), whole_stream_command(Next), whole_stream_command(Previous), whole_stream_command(Debug), whole_stream_command(Lines), whole_stream_command(Shells), whole_stream_command(SplitColumn), whole_stream_command(SplitRow), whole_stream_command(Lines), whole_stream_command(Reject), whole_stream_command(Reverse), whole_stream_command(Trim), whole_stream_command(ToBSON), whole_stream_command(ToCSV), whole_stream_command(ToJSON), whole_stream_command(ToSQLite), whole_stream_command(ToDB), whole_stream_command(ToTOML), whole_stream_command(ToTSV), whole_stream_command(ToURL), whole_stream_command(ToYAML), whole_stream_command(SortBy), whole_stream_command(Tags), whole_stream_command(First), whole_stream_command(Last), whole_stream_command(Env), whole_stream_command(FromCSV), whole_stream_command(FromTSV), whole_stream_command(FromINI), whole_stream_command(FromBSON), whole_stream_command(FromJSON), whole_stream_command(FromDB), whole_stream_command(FromSQLite), whole_stream_command(FromTOML), whole_stream_command(FromURL), whole_stream_command(FromXML), whole_stream_command(FromYAML), whole_stream_command(FromYML), whole_stream_command(Pick), whole_stream_command(Get), per_item_command(Remove), per_item_command(Fetch), per_item_command(Open), per_item_command(Post), per_item_command(Where), per_item_command(Echo), whole_stream_command(Config), whole_stream_command(SkipWhile), per_item_command(Enter), per_item_command(Help), whole_stream_command(Exit), whole_stream_command(Autoview), whole_stream_command(Pivot), per_item_command(Cpy), whole_stream_command(Date), per_item_command(Mkdir), per_item_command(Move), whole_stream_command(Save), whole_stream_command(Table), whole_stream_command(Version), whole_stream_command(Which), ]); #[cfg(feature = "clipboard")] { context.add_commands(vec![whole_stream_command( crate::commands::clip::clipboard::Clip, )]); } } let _ = load_plugins(&mut context); let config = Config::builder().color_mode(ColorMode::Forced).build(); let mut rl: Editor<_> = Editor::with_config(config); #[cfg(windows)] { let _ = ansi_term::enable_ansi_support(); } // we are ok if history does not exist let _ = rl.load_history(&History::path()); let ctrl_c = Arc::new(AtomicBool::new(false)); let cc = ctrl_c.clone(); ctrlc::set_handler(move || { cc.store(true, Ordering::SeqCst); }) .expect("Error setting Ctrl-C handler"); let mut ctrlcbreak = false; loop { if ctrl_c.load(Ordering::SeqCst) { ctrl_c.store(false, Ordering::SeqCst); continue; } let cwd = context.shell_manager.path(); rl.set_helper(Some(crate::shell::Helper::new( context.shell_manager.clone(), ))); let edit_mode = config::config(Tag::unknown())? .get("edit_mode") .map(|s| match s.as_string().unwrap().as_ref() { "vi" => EditMode::Vi, "emacs" => EditMode::Emacs, _ => EditMode::Emacs, }) .unwrap_or(EditMode::Emacs); rl.set_edit_mode(edit_mode); // Register Ctrl-r for history fuzzy search // rustyline doesn't support custom commands, so we override Ctrl-D (EOF) // https://github.com/nushell/nushell/issues/689 #[cfg(all(not(windows), feature = "crossterm"))] rl.bind_sequence(rustyline::KeyPress::Ctrl('R'), rustyline::Cmd::EndOfFile); // Redefine Ctrl-D to same command as Ctrl-C rl.bind_sequence(rustyline::KeyPress::Ctrl('D'), rustyline::Cmd::Interrupt); let prompt = &format!( "{}{}> ", cwd, match current_branch() { Some(s) => format!("({})", s), None => "".to_string(), } ); let mut initial_command = Some(String::new()); let mut readline = Err(ReadlineError::Eof); while let Some(ref cmd) = initial_command { readline = rl.readline_with_initial(prompt, (&cmd, "")); if let Err(ReadlineError::Eof) = &readline { // Fuzzy search in history let lines = rl.history().iter().rev().map(|s| s.as_str()).collect(); let selection = interactive_fuzzy_search(&lines, 5); // Clears last line with prompt match selection { SelectionResult::Selected(line) => { println!("{}{}", &prompt, &line); // TODO: colorize prompt readline = Ok(line.clone()); initial_command = None; } SelectionResult::Edit(line) => { initial_command = Some(line); } SelectionResult::NoSelection => { readline = Ok("".to_string()); initial_command = None; } } } else { initial_command = None; } } match process_line(readline, &mut context).await { LineResult::Success(line) => { rl.add_history_entry(line.clone()); } LineResult::CtrlC => { let config_ctrlc_exit = config::config(Tag::unknown())? .get("ctrlc_exit") .map(|s| match s.as_string().unwrap().as_ref() { "true" => true, _ => false, }) .unwrap_or(false); // default behavior is to allow CTRL-C spamming similar to other shells if !config_ctrlc_exit { continue; } if ctrlcbreak { let _ = rl.save_history(&History::path()); std::process::exit(0); } else { context.with_host(|host| host.stdout("CTRL-C pressed (again to quit)")); ctrlcbreak = true; continue; } } LineResult::Error(mut line, err) => { rl.add_history_entry(line.clone()); let diag = err.to_diagnostic(); context.with_host(|host| { let writer = host.err_termcolor(); line.push_str(" "); let files = crate::parser::Files::new(line); let _ = std::panic::catch_unwind(move || { let _ = language_reporting::emit( &mut writer.lock(), &files, &diag, &language_reporting::DefaultConfig, ); }); }) } LineResult::Break => { break; } } ctrlcbreak = false; } // we are ok if we can not save history let _ = rl.save_history(&History::path()); Ok(()) } enum LineResult { Success(String), Error(String, ShellError), CtrlC, Break, } async fn process_line(readline: Result<String, ReadlineError>, ctx: &mut Context) -> LineResult { match &readline { Ok(line) if line.trim() == "" => LineResult::Success(line.clone()), Ok(line) => { let result = match crate::parser::parse(&line, uuid::Uuid::nil()) { Err(err) => { return LineResult::Error(line.clone(), err); } Ok(val) => val, }; debug!("=== Parsed ==="); debug!("{:#?}", result); let mut pipeline = match classify_pipeline(&result, ctx, &Text::from(line)) { Ok(pipeline) => pipeline, Err(err) => return LineResult::Error(line.clone(), err), }; match pipeline.commands.last() { Some(ClassifiedCommand::External(_)) => {} _ => pipeline .commands .push(ClassifiedCommand::Internal(InternalCommand { command: whole_stream_command(autoview::Autoview), name_tag: Tag::unknown(), args: hir::Call::new( Box::new(hir::Expression::synthetic_string("autoview")), None, None, ), })), } let mut input = ClassifiedInputStream::new(); let mut iter = pipeline.commands.into_iter().peekable(); let mut is_first_command = true; loop { let item: Option<ClassifiedCommand> = iter.next(); let next: Option<&ClassifiedCommand> = iter.peek(); input = match (item, next) { (None, _) => break, (Some(ClassifiedCommand::Expr(_)), _) => { return LineResult::Error( line.clone(), ShellError::unimplemented("Expression-only commands"), ) } (_, Some(ClassifiedCommand::Expr(_))) => { return LineResult::Error( line.clone(), ShellError::unimplemented("Expression-only commands"), ) } ( Some(ClassifiedCommand::Internal(left)), Some(ClassifiedCommand::External(_)), ) => match left .run(ctx, input, Text::from(line), is_first_command) .await { Ok(val) => ClassifiedInputStream::from_input_stream(val), Err(err) => return LineResult::Error(line.clone(), err), }, (Some(ClassifiedCommand::Internal(left)), Some(_)) => { match left .run(ctx, input, Text::from(line), is_first_command) .await { Ok(val) => ClassifiedInputStream::from_input_stream(val), Err(err) => return LineResult::Error(line.clone(), err), } } (Some(ClassifiedCommand::Internal(left)), None) => { match left .run(ctx, input, Text::from(line), is_first_command) .await { Ok(val) => ClassifiedInputStream::from_input_stream(val), Err(err) => return LineResult::Error(line.clone(), err), } } ( Some(ClassifiedCommand::External(left)), Some(ClassifiedCommand::External(_)), ) => match left.run(ctx, input, StreamNext::External).await { Ok(val) => val, Err(err) => return LineResult::Error(line.clone(), err), }, (Some(ClassifiedCommand::External(left)), Some(_)) => { match left.run(ctx, input, StreamNext::Internal).await { Ok(val) => val, Err(err) => return LineResult::Error(line.clone(), err), } } (Some(ClassifiedCommand::External(left)), None) => { match left.run(ctx, input, StreamNext::Last).await { Ok(val) => val, Err(err) => return LineResult::Error(line.clone(), err), } } }; is_first_command = false; } LineResult::Success(line.clone()) } Err(ReadlineError::Interrupted) => LineResult::CtrlC, Err(ReadlineError::Eof) => LineResult::Break, Err(err) => { println!("Error: {:?}", err); LineResult::Break } } } fn classify_pipeline( pipeline: &TokenNode, context: &Context, source: &Text, ) -> Result<ClassifiedPipeline, ShellError> { let pipeline = pipeline.as_pipeline()?; let Pipeline { parts, .. } = pipeline; let commands: Result<Vec<_>, ShellError> = parts .iter() .map(|item| classify_command(&item, context, &source)) .collect(); Ok(ClassifiedPipeline { commands: commands?, }) } fn classify_command( command: &PipelineElement, context: &Context, source: &Text, ) -> Result<ClassifiedCommand, ShellError> { let call = command.call(); match call { // If the command starts with `^`, treat it as an external command no matter what call if call.head().is_external() => { let name_tag = call.head().expect_external(); let name = name_tag.slice(source); Ok(external_command(call, source, name.tagged(name_tag))) } // Otherwise, if the command is a bare word, we'll need to triage it call if call.head().is_bare() => { let head = call.head(); let name = head.source(source); match context.has_command(name) { // if the command is in the registry, it's an internal command true => { let command = context.get_command(name); let config = command.signature(); trace!(target: "nu::build_pipeline", "classifying {:?}", config); let args: hir::Call = config.parse_args(call, &context, source)?; trace!(target: "nu::build_pipeline", "args :: {}", args.debug(source)); Ok(ClassifiedCommand::Internal(InternalCommand { command, name_tag: head.tag(), args, })) } // otherwise, it's an external command false => Ok(external_command(call, source, name.tagged(head.tag()))), } } // If the command is something else (like a number or a variable), that is currently unsupported. // We might support `$somevar` as a curried command in the future. call => Err(ShellError::invalid_command(call.head().tag())), } } // Classify this command as an external command, which doesn't give special meaning // to nu syntactic constructs, and passes all arguments to the external command as // strings. fn external_command( call: &Tagged<CallNode>, source: &Text, name: Tagged<&str>, ) -> ClassifiedCommand { let arg_list_strings: Vec<Tagged<String>> = match call.children() { Some(args) => args .iter() .filter_map(|i| match i { TokenNode::Whitespace(_) => None, other => Some(other.as_external_arg(source).tagged(other.tag())), }) .collect(), None => vec![], }; let (name, tag) = name.into_parts(); ClassifiedCommand::External(ExternalCommand { name: name.to_string(), name_tag: tag, args: arg_list_strings, }) }
use crate::api::*; use crate::error::Error; use crate::service::*; use crate::types::*; #[cfg(feature = "sha256")] impl DeriveKey for super::Sha256 { #[inline(never)] fn derive_key(keystore: &mut impl Keystore, request: &request::DeriveKey) -> Result<reply::DeriveKey, Error> { let base_id = &request.base_key; let shared_secret = keystore .load_key(key::Secrecy::Secret, None, base_id)? .material; // hash it use sha2::digest::Digest; let mut hash = sha2::Sha256::new(); hash.update(&shared_secret); let symmetric_key: [u8; 32] = hash.finalize().into(); let key_id = keystore.store_key( request.attributes.persistence, key::Secrecy::Secret, key::Kind::Symmetric(32), &symmetric_key)?; Ok(reply::DeriveKey { key: key_id }) } } #[cfg(feature = "sha256")] impl Hash for super::Sha256 { #[inline(never)] fn hash(_keystore: &mut impl Keystore, request: &request::Hash) -> Result<reply::Hash, Error> { use sha2::digest::Digest; let mut hash = sha2::Sha256::new(); hash.update(&request.message); let mut hashed = ShortData::new(); hashed.extend_from_slice(&hash.finalize()).unwrap(); Ok(reply::Hash { hash: hashed } ) } } #[cfg(not(feature = "sha256"))] impl DeriveKey for super::Sha256 {} #[cfg(not(feature = "sha256"))] impl Hash for super::Sha256 {}
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use codec::{Decode, Encode}; pub use aleph_bft::default_config as default_aleph_config; use aleph_bft::{DefaultMultiKeychain, NodeCount, NodeIndex, TaskHandle}; use futures::{channel::oneshot, Future, TryFutureExt}; use sc_client_api::{backend::Backend, BlockchainEvents, Finalizer, LockImportRun, TransactionFor}; use sc_consensus::BlockImport; use sc_service::SpawnTaskHandle; use sp_api::{NumberFor, ProvideRuntimeApi}; use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_consensus::SelectChain; use sp_runtime::{ traits::{BlakeTwo256, Block}, RuntimeAppPublic, SaturatedConversion, }; use std::{collections::HashMap, convert::TryInto, fmt::Debug, sync::Arc}; mod aggregator; pub mod config; mod data_io; mod finalization; mod hash; mod import; mod justification; pub mod metrics; mod network; mod party; #[cfg(test)] pub mod testing; pub use import::AlephBlockImport; pub use justification::JustificationNotification; #[derive(Clone, Debug, Encode, Decode)] enum Error { SendData, } pub fn peers_set_config() -> sc_network::config::NonDefaultSetConfig { let mut config = sc_network::config::NonDefaultSetConfig::new( network::ALEPH_PROTOCOL_NAME.into(), // max_notification_size should be larger than the maximum possible honest message size (in bytes). // Max size of alert is UNIT_SIZE * MAX_UNITS_IN_ALERT ~ 100 * 5000 = 50000 bytes // Max size of parents response UNIT_SIZE * N_MEMBERS ~ 100 * N_MEMBERS // When adding other (large) message types we need to make sure this limit is fine. 1024 * 1024, ); config.set_config = sc_network::config::SetConfig::default(); config } #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd, Encode, Decode)] pub struct SessionId(pub u32); use sp_core::crypto::KeyTypeId; pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"alp0"); pub use crate::metrics::Metrics; use crate::party::{run_consensus_party, AlephParams}; pub use aleph_primitives::{AuthorityId, AuthorityPair, AuthoritySignature}; use aleph_primitives::{MillisecsPerBlock, SessionPeriod, UnitCreationDelay}; use futures::channel::mpsc; /// Ties an authority identification and a cryptography keystore together for use in /// signing that requires an authority. #[derive(Clone)] pub struct AuthorityKeystore { key_type_id: KeyTypeId, authority_id: AuthorityId, keystore: SyncCryptoStorePtr, } impl AuthorityKeystore { /// Constructs a new authority cryptography keystore. pub fn new(authority_id: AuthorityId, keystore: SyncCryptoStorePtr) -> Self { AuthorityKeystore { key_type_id: KEY_TYPE, authority_id, keystore, } } /// Returns a references to the authority id. pub fn authority_id(&self) -> &AuthorityId { &self.authority_id } /// Returns a reference to the cryptography keystore. pub fn keystore(&self) -> &SyncCryptoStorePtr { &self.keystore } pub fn sign(&self, msg: &[u8]) -> AuthoritySignature { SyncCryptoStore::sign_with( &*self.keystore, self.key_type_id, &self.authority_id.clone().into(), msg, ) .unwrap() .unwrap() .try_into() .unwrap() } } pub trait ClientForAleph<B, BE>: LockImportRun<B, BE> + Finalizer<B, BE> + ProvideRuntimeApi<B> + BlockImport<B, Transaction = TransactionFor<BE, B>, Error = sp_consensus::Error> + HeaderBackend<B> + HeaderMetadata<B, Error = sp_blockchain::Error> + BlockchainEvents<B> where BE: Backend<B>, B: Block, { } impl<B, BE, T> ClientForAleph<B, BE> for T where BE: Backend<B>, B: Block, T: LockImportRun<B, BE> + Finalizer<B, BE> + ProvideRuntimeApi<B> + HeaderBackend<B> + HeaderMetadata<B, Error = sp_blockchain::Error> + BlockchainEvents<B> + BlockImport<B, Transaction = TransactionFor<BE, B>, Error = sp_consensus::Error>, { } type Hasher = hash::Wrapper<BlakeTwo256>; #[derive(PartialEq, Eq, Clone, Debug, Decode, Encode)] struct Signature { id: NodeIndex, sgn: AuthoritySignature, } #[derive(Clone)] struct KeyBox { id: NodeIndex, auth_keystore: AuthorityKeystore, authorities: Vec<AuthorityId>, } impl KeyBox { fn new(id: NodeIndex, authorities: Vec<AuthorityId>, key_store: SyncCryptoStorePtr) -> Self { let auth_keystore = AuthorityKeystore::new(authorities[id.0].clone(), key_store); KeyBox { id, auth_keystore, authorities, } } } impl aleph_bft::Index for KeyBox { fn index(&self) -> NodeIndex { self.id } } #[async_trait::async_trait] impl aleph_bft::KeyBox for KeyBox { type Signature = Signature; fn node_count(&self) -> NodeCount { self.authorities.len().into() } async fn sign(&self, msg: &[u8]) -> Signature { Signature { id: self.id, sgn: self.auth_keystore.sign(msg), } } fn verify(&self, msg: &[u8], sgn: &Signature, index: NodeIndex) -> bool { self.authorities[index.0].verify(&msg.to_vec(), &sgn.sgn) } } type MultiKeychain = DefaultMultiKeychain<KeyBox>; #[derive(Clone)] struct SpawnHandle(SpawnTaskHandle); impl From<SpawnTaskHandle> for SpawnHandle { fn from(sth: SpawnTaskHandle) -> Self { SpawnHandle(sth) } } impl aleph_bft::SpawnHandle for SpawnHandle { fn spawn(&self, name: &'static str, task: impl Future<Output = ()> + Send + 'static) { self.0.spawn(name, task) } fn spawn_essential( &self, name: &'static str, task: impl Future<Output = ()> + Send + 'static, ) -> TaskHandle { let (tx, rx) = oneshot::channel(); self.spawn(name, async move { task.await; let _ = tx.send(()); }); Box::pin(rx.map_err(|_| ())) } } pub type SessionMap = HashMap<SessionId, Vec<AuthorityId>>; pub fn last_block_of_session<B: Block>( session_id: SessionId, period: SessionPeriod, ) -> NumberFor<B> { ((session_id.0 + 1) * period.0 - 1).into() } pub fn session_id_from_block_num<B: Block>(num: NumberFor<B>, period: SessionPeriod) -> SessionId { SessionId(num.saturated_into::<u32>() / period.0) } pub struct AlephConfig<B: Block, N, C, SC> { pub network: N, pub client: Arc<C>, pub select_chain: SC, pub spawn_handle: SpawnTaskHandle, pub keystore: SyncCryptoStorePtr, pub justification_rx: mpsc::UnboundedReceiver<JustificationNotification<B>>, pub metrics: Option<Metrics<B::Header>>, pub session_period: SessionPeriod, pub millisecs_per_block: MillisecsPerBlock, pub unit_creation_delay: UnitCreationDelay, } pub fn run_aleph_consensus<B: Block, BE, C, N, SC>( config: AlephConfig<B, N, C, SC>, ) -> impl Future<Output = ()> where BE: Backend<B> + 'static, N: network::Network<B> + 'static, C: ClientForAleph<B, BE> + Send + Sync + 'static, C::Api: aleph_primitives::AlephSessionApi<B>, SC: SelectChain<B> + 'static, { run_consensus_party(AlephParams { config }) }
use crate::io_ports; use crate::PIC8259; macro_rules! pushall { () => {{ llvm_asm!(" push rax push rbx push rcx push rdx push rsi push rdi push rbp push rsp push r8 push r9 push r10 push r11 push r12 push r13 push r14 push r15 " :::: "intel", "volatile"); }}; } macro_rules! popall { () => {{ llvm_asm!(" pop r15 pop r14 pop r13 pop r12 pop r11 pop r10 pop r9 pop r8 pop rsp pop rbp pop rdi pop rsi pop rdx pop rcx pop rbx pop rax " :::: "intel", "volatile"); }}; } #[naked] pub extern "C" fn isr0() -> () { pushall!(); print!("."); PIC8259::sendEOI(0); popall!(); llvm_asm!("iretq"); } } #[naked] pub extern "C" fn isr1() -> () { unsafe{ pushall!(); let scancode: u8 = io_ports::inb(0x60); print!("{}", scancode); PIC8259::sendEOI(1); popall!(); llvm_asm!("iretq"); } } #[naked] pub extern "C" fn isr2() -> () { unsafe{ pushall!(); println!("isr2 :("); PIC8259::sendEOI(2); PIC8259::sendEOI(10); popall!(); llvm_asm!("iretq"); } } #[naked] pub extern "C" fn div_zero() -> () { serial_println!("DIVIDE BY ZERO"); } #[naked] pub extern "C" fn debug() -> () { serial_println!("DEBUG"); } #[naked] pub extern "C" fn non_maskable_interrupt() -> () { serial_println!("NON_MASKABLE_INTERRUPT"); } #[naked] pub extern "C" fn breakpoint() -> () { serial_println!("breakpoint"); } #[naked] pub extern "C" fn overflow() -> () { serial_println!("overflow"); } #[naked] pub extern "C" fn bound_range_exceeded() -> () { serial_println!("bound_range_exceeded"); } #[naked] pub extern "C" fn invalid_opcode() -> () { serial_println!("invalid_opcode"); } #[naked] pub extern "C" fn device_not_avaiable() -> () { serial_println!("device_not_avaiable"); } #[naked] pub extern "C" fn double_fault() -> () { serial_println!("DOUBLE FAULT"); } #[naked] pub extern "C" fn invalid_tss() -> () { serial_println!("INVALID TSS"); } #[naked] pub extern "C" fn segment_not_present() -> () { serial_println!("SEGMENT NOT PRESENT"); } #[naked] pub extern "C" fn stack_segment_fault() -> () { serial_println!("STACK SEGMENT FAULT"); } #[naked] pub extern "C" fn general_protect_fault() -> () { serial_println!("GENERAL PROTECTION FAULT"); } #[naked] pub extern "C" fn page_fault() -> () { serial_println!("PAGE FAULT"); } #[naked] pub extern "C" fn x87_floating_point() -> () { serial_println!("x87_floating_point"); } #[naked] pub extern "C" fn alignment_check() -> () { serial_println!("alignment_check"); } #[naked] pub extern "C" fn machine_check() -> () { serial_println!("machine check"); } #[naked] pub extern "C" fn simd() -> () { serial_println!("simd"); } #[naked] pub extern "C" fn virtualization() -> () { serial_println!("virtualization"); } #[naked] pub extern "C" fn security_exception() -> () { serial_println!("security_exception"); }
extern crate leak; use leak::Leak; #[test] fn leak_str() { use std::borrow::ToOwned; let v = "hi"; let leaked : &str = { let o = v.to_owned(); o.leak() }; assert_eq!(leaked, v); let leaked : &'static str = { let o = v.to_owned(); o.leak() }; assert_eq!(leaked, v); } #[test] fn leak_empty_str() { use std::borrow::ToOwned; let v = ""; let leaked : &'static str = { let o = v.to_owned(); o.leak() }; assert_eq!(leaked, v); } #[test] fn leak_vec() { let v = vec![3, 5]; let leaked : &'static [u8] = { let o = v.clone(); o.leak() }; assert_eq!(leaked, &*v); } #[test] fn leak_empty_vec() { let v = vec![]; let leaked : &'static [u8] = { let o = v.clone(); o.leak() }; assert_eq!(leaked, &*v); } #[test] fn leak_box() { let v : Box<[&str]> = vec!["hi", "there"].into_boxed_slice(); let leaked : &'static [&str] = { let o = v.clone(); o.leak() }; assert_eq!(leaked, &*v); } #[test] fn leak_nested() { let v : Box<Vec<&str>> = Box::new(vec!["hi", "there"]); let leaked : &'static [&str] = { let o = v.clone(); o.leak() }; assert_eq!(leaked, &**v); } #[test] fn leak_mut() { let v = vec![1, 3, 4]; let leaked: &'static mut [u8] = v.leak(); leaked[1] = 5; assert_eq!(leaked, &[1,5,4]) }
use std::io::net::tcp::TcpStream; fn main() { let mut socket = TcpStream::connect("127.0.0.1", 8080).unwrap(); //unwrap is for whaaah? Removes wrapping Option? println!("Writing to socket"); socket.write(bytes!("GET / HTTP/1.0\n\n")); let response = socket.read_to_end(); println!("response: {}", response); }
pub fn factors(n: u64) -> Vec<u64> { let mut n_clone = n; let mut vec = Vec::new(); let mut n_clone_orig = n_clone; for num_2 in 2..=2 { while n_clone % num_2 == 0 && n_clone != 1 { n_clone = n_clone / num_2; vec.push(num_2); } if n_clone_orig > n_clone { n_clone_orig = n_clone; } } for num in (3..=n).step_by(2) { while n_clone % num == 0 && n_clone != 1 { n_clone = n_clone / num; vec.push(num); } if n_clone_orig > n_clone { n_clone_orig = n_clone; } if n_clone == 1 { break; } } vec }
use io::Error; use std::fs::File; use std::io; use std::io::Read; fn main() { // panic!("Error"); // index out of bounds // let v = vec![1, 2, 3]; // v[99]; // Result // let file_path = "hello.txt"; // let f = match File::open(file_path) { // Ok(file) => file, // Err(error) => match error.kind() { // ErrorKind::NotFound => match File::create(file_path) { // Ok(fc) => fc, // Err(e) => panic!("Problem creating the file: {:?}", e), // } // other_error => { // panic!("Problem opening the file: {:?}", other_error) // } // } // }; let file_path = "hello.txt"; let username = read_username_from_file(file_path).unwrap(); println!("username: {}", username); } fn read_username_from_file(filename: &str) -> Result<String, Error> { // let mut f = match File::open(filename) { // Ok(file) => file, // Err(e) => return Err(e), // }; // let mut f = File::open(filename)?; // let mut buf = String::new(); // f.read_to_string(&mut buf)?; // Ok(buf) let mut buf = String::new(); File::open(filename)?.read_to_string(&mut buf)?; Ok(buf) }
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct GetWisdomQuoteRequest { pub temp: String, }
use chrono::{Local, DateTime}; pub struct BankAccountRM { pub bank_account_id: String, pub name: String, pub is_closed: bool, pub balance: i32, pub created_at: DateTime<Local>, pub updated_at: DateTime<Local>, pub version: u64, } pub trait BankAccountRMDao: Send + Sync { fn find(&self, bank_account_id: String) -> Option<BankAccountRM>; fn insert(&self, model: BankAccountRM); fn update(&self, model: BankAccountRM); }
extern crate primes; use std::cmp; use primes::PrimeSet; fn main() { let num = 600851475143; let mut pset = PrimeSet::new(); let mut n = pset.prime_factors(num); let mut max = n[0]; let mut n_iter = n.iter(); while let Some(i) = n_iter.next() { max = cmp::max(*i, max); } println!("{}", max); }
use std::collections::HashMap; use std::iter::FromIterator; use crate::kraken::{Fragments, Taxon}; pub type AbundanceData = HashMap<Taxon, Fragments>; pub type SampleName = String; #[derive(Debug, Default, PartialEq)] pub struct SampleAbundance { pub name: SampleName, pub dataset: AbundanceData, } impl SampleAbundance { #[must_use] pub fn taxons(&self) -> Vec<Taxon> { self.dataset.keys().cloned().collect() } } impl From<(SampleName, AbundanceData)> for SampleAbundance { fn from(values: (SampleName, AbundanceData)) -> Self { Self { name: values.0, dataset: values.1, } } } pub type SamplesAbundanceData = Vec<SampleAbundance>; // FIXME remove #[derive(Debug, Default, PartialEq)] pub struct Samples { pub data: Vec<SampleAbundance>, pub unique_taxons: Vec<Taxon>, } impl Samples { #[must_use] pub fn new() -> Self { Self { data: Vec::new(), unique_taxons: Vec::new(), } } fn add(&mut self, elem: SampleAbundance) { let new_taxons = elem.taxons(); for taxon in new_taxons { if !self.unique_taxons.contains(&taxon) { self.unique_taxons.push(taxon); } } self.data.push(elem); } pub fn add_missing_taxons(&mut self) -> &mut Self { for datum in &mut self.data { for taxon in &self.unique_taxons { datum .dataset .entry(taxon.clone()) .or_insert_with(Fragments::default); } } self } } impl FromIterator<(SampleName, AbundanceData)> for Samples { fn from_iter<T: IntoIterator<Item = (SampleName, AbundanceData)>>(iter: T) -> Self { let mut samples = Self::new(); for i in iter { let sample = SampleAbundance::from(i); samples.add(sample); } samples } }
pub use self::consts::*; pub use self::inst::*; pub mod consts; pub mod inst; use {ValueRef, TypeRef}; cpp! { #include "llvm/IR/Value.h" pub fn LLVMRustValueDump(value: ValueRef as "llvm::Value*") { value->dump(); } pub fn LLVMRustValueGetType(value: ValueRef as "llvm::Value*") -> TypeRef as "llvm::Type*" { return value->getType(); } } #[cfg(test)] mod test { use test_support::Context; #[test] fn can_get_type_from_constant() { let ctx = Context::new(); unsafe { let val = ::LLVMRustConstantIntGetTrue(ctx.inner); ::LLVMRustValueGetType(val); } } }
use paillier::{BigInt, *}; fn main() { // generate a fresh keypair let (ek, dk) = Paillier::keypair(&mut rand::thread_rng()).keys(); // encrypt two values let c1 = Paillier::encrypt(&ek, RawPlaintext::from(BigInt::from(20))); let c2 = Paillier::encrypt(&ek, RawPlaintext::from(BigInt::from(30))); // add all of them together let c = Paillier::add(&ek, c1, c2); // multiply the sum by 2 let d = Paillier::mul(&ek, c, RawPlaintext::from(BigInt::from(2))); // decrypt final result let m: BigInt = Paillier::decrypt(&dk, d).into(); println!("decrypted total sum is {}", m); }
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Shl, Sub, Shr}; use std::convert::TryInto; pub fn make_mask<OutT>(size: usize) -> OutT where OutT: num::traits::One + Shl<usize, Output=OutT> + Sub<OutT, Output=OutT> { assert!(std::mem::size_of::<OutT>()*8 > size); (OutT::one() << size) - OutT::one() } pub fn extract_bits<T>(x: T, range: std::ops::Range<usize>) -> T where T: BitAnd<Output=T> + num::traits::One + Shr<usize, Output=T> + Shl<usize, Output=T> + Sub<T, Output=T> { assert!(std::mem::size_of::<T>()*8 > range.end); (x >> range.start) & make_mask::<T>(range.end - range.start) } pub trait ShiftOps : std::ops::Shl + std::ops::ShlAssign + std::ops::Shr + std::ops::ShrAssign + Sized { } pub trait BitOps : std::ops::Not + BitAnd + BitAndAssign + BitOr + BitOrAssign + BitXor + BitXorAssign + Sized { } pub trait Bits<'a>: Clone + BitOps + ShiftOps + Default { fn byte_len(&self) -> usize; fn bit_len(&self) -> usize { self.byte_len()*8 } unsafe fn as_mut_bytes_ptr(&mut self) -> *mut u8; unsafe fn as_bytes_ptr(&self) -> *const u8; fn as_bytes_slice(&self) -> &'a [u8] { unsafe { std::slice::from_raw_parts(self.as_bytes_ptr(), self.byte_len()) } } fn as_mut_bytes_slice(&mut self) -> &mut [u8] { unsafe { std::slice::from_raw_parts_mut(self.as_mut_bytes_ptr(), self.byte_len()) } } fn set_bit(&mut self, bit: usize); fn clear_bit(&mut self, bit: usize); fn get_bit(&self, bit: usize) -> bool; } pub enum Endianness { Little, Big } macro_rules! bit_impl { ($($t:ty),*) => ($( impl BitOps for $t { } impl ShiftOps for $t { } impl<'a> Bits<'a> for $t { fn byte_len(&self) -> usize { std::mem::size_of::<$t>() } unsafe fn as_mut_bytes_ptr(&mut self) -> *mut u8 { std::mem::transmute::<*mut $t, *mut u8>(self) } unsafe fn as_bytes_ptr(&self) -> *const u8 { std::mem::transmute::<*const $t, *const u8>(self) } fn set_bit(&mut self, bit: usize) { *self |= 1 << bit } fn clear_bit(&mut self, bit: usize) { *self &= !(1 << bit) } fn get_bit(&self, bit: usize) -> bool { ((self >> bit) & 1) == 1 } } )*) } bit_impl!(u8, u16, u32, u64, u128); pub struct BitVector { data: Vec<u8>, bit_length: usize, } impl BitVector { } pub struct BitScanner<'a> { flip_bits: bool, bytes: &'a [u8], bit_position: usize, } impl<'a> Iterator for BitScanner<'a> { type Item = bool; fn next(&mut self) -> Option<Self::Item> { let b = self.peek_bit()?; self.bit_position+=1; Some(b) } } fn reverse_bits(b: u8) -> u8 { let b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; let b = (b & 0xCC) >> 2 | (b & 0x33) << 2; let b = (b & 0xAA) >> 1 | (b & 0x55) << 1; b } impl<'a> BitScanner<'a> { pub fn new(bytes: &[u8]) -> BitScanner { BitScanner {flip_bits: true, bytes, bit_position: 0} } pub fn is_done(&self) -> bool { self.len() == self.pos() } pub fn peek_bit(&self) -> Option<bool> { if self.pos() >= self.len() { None } else { Some(((self.current_byte()? << self.current_pos_in_byte()) & 1) == 1) } } pub fn byte_pos(&self) -> usize { self.bit_position / 8 } pub fn pos(&self) -> usize { self.bit_position } pub fn len(&self) -> usize { self.bytes_len() * 8 } pub fn bytes_len(&self) -> usize { self.bytes.len() } pub fn bits_left(&self) -> usize { self.len() - self.pos() } pub fn atleast_n_bits_left(&self, n: usize) -> bool { self.bits_left() >= n } fn current_pos_in_byte(&self) -> u8 { (self.pos() % 8).try_into().unwrap() } fn current_byte(&self) -> Option<u8> { if !self.atleast_n_bits_left(8) { None } else { let mut b = self.bytes[self.byte_pos()]; Some(b) } } fn is_aligned(&self) -> bool { self.current_pos_in_byte() == 0 } fn next_byte_aligned(&mut self) -> Option<u8> { if !self.is_aligned() && !self.atleast_n_bits_left(8) { None } else { let b = self.current_byte()?; self.bit_position += 8; Some(b) } } pub fn next_byte(&mut self) -> Option<u8> { if !self.atleast_n_bits_left(8) { None } else if self.is_aligned() { self.next_byte_aligned() } else { let bit_pos = self.current_pos_in_byte(); let mut out: u8 = self.current_byte()? >> bit_pos; self.bit_position += (8-bit_pos) as usize; out |= self.current_byte()? << bit_pos; self.bit_position += bit_pos as usize; Some(out) } } pub fn is_byte_aligned(&self, byte_alignment: u8) -> bool { (self.bit_position % (8 << byte_alignment) as usize) == 0 } fn next_sub_byte_aligned(&mut self, amount: u8) -> Option<u8> { if amount >= 8 || !self.is_aligned() || !self.atleast_n_bits_left(amount.into()) { None } else { let out: u8 = self.current_byte()? & make_mask::<u8>(amount.into()); self.bit_position += amount as usize; Some(out) } } fn consume_bits_left_in_current_byte(&mut self) -> u8 { let bit_pos = self.current_pos_in_byte(); let out = self.current_byte().unwrap_or(0) >> bit_pos; self.bit_position += bit_pos as usize; out } fn next_sub_byte(&mut self, amount: u8) -> Option<u8> { if amount == 0 ||amount >= 8 || !self.atleast_n_bits_left(amount.into()) { None } else if self.is_aligned() { self.next_sub_byte_aligned(amount) } else { //FIXME let rest_count = 8-self.current_pos_in_byte(); let mut out: u8 = make_mask::<u8>(amount as usize) & (self.current_byte().unwrap() >> self.current_pos_in_byte()); out |= self.next_sub_byte_aligned(amount.checked_sub(rest_count).unwrap_or(0)).unwrap_or(0) << rest_count; Some(out) } } pub fn collect_bits<OutT>(&mut self, amount: usize) -> Option<OutT> where OutT: for<'b> Bits<'b> + From<u8> + Shl<usize, Output=OutT> { assert!(std::mem::size_of::<OutT>() <= amount, "trying to collect more bits than the type can contain"); if !self.atleast_n_bits_left(amount) { None } else if (8-self.current_pos_in_byte()) as usize >= amount { Some(self.next_sub_byte(amount.try_into().expect("amount should be 8> by now")).expect("should be subbyte").into()) } else { let start_pos = self.pos(); let mut out: OutT = self.consume_bits_left_in_current_byte().into(); let mut out_pos = self.pos()-start_pos; let mut out_left = amount-out_pos; while out_left>=8 { let next_byte = self.next_byte().unwrap(); out |= OutT::from(next_byte) << out_pos; out_pos += 8; out_left -= 8; } if out_left > 0 { //sub byte left out |= OutT::from(self.next_sub_byte(out_left.try_into().expect("amount should be 8> by now")).unwrap()) << out_pos; } Some(out) } } pub fn collect_type<T>(&mut self) -> Option<T> where T: for<'b> Bits<'b> + From<u8> + Shl<usize, Output=T> { self.collect_bits(std::mem::size_of::<T>()*8) } } impl<'a, T> From<&'a T> for BitScanner<'a> where T: Bits<'a> { fn from(bits: &T) -> Self { BitScanner::new(bits.as_bytes_slice()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test1() { let x = 0x7F7Fu16; let mut scanner: BitScanner = (&x).into(); assert_eq!(scanner.len(), 16); assert_eq!(scanner.bits_left(), 16); assert!(scanner.atleast_n_bits_left(16)); assert_eq!(scanner.collect_type::<u16>().expect("expected u16"), x); assert!(scanner.is_done()); } #[test] fn test2() { let x = 0xACACu16; //0b1010110010101100 let mut scanner: BitScanner = (&x).into(); assert_eq!(scanner.len(), 16); assert_eq!(scanner.bits_left(), 16); assert!(scanner.atleast_n_bits_left(16)); assert_eq!(scanner.collect_bits::<u8>(4).unwrap(), 0xCu8); assert_eq!(scanner.collect_bits::<u8>(3).unwrap(), 0x6u8); assert_eq!(scanner.collect_bits::<u8>(4).unwrap(), 0x9u8); assert!(!scanner.is_done()); } #[test] fn test3() { assert_eq!(make_mask::<u8>(0), 0); assert_eq!(make_mask::<u16>(4), 0b1111); assert_eq!(make_mask::<u32>(7), 0b1111_111); assert_eq!(make_mask::<u64>(11),0b1111_1111_111); } }
use radmin::uuid::Uuid; use serde::{Deserialize, Serialize}; use crate::schema::phone_numbers; #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Queryable, Identifiable, AsChangeset)] #[table_name = "phone_numbers"] pub struct Phone { pub id: Uuid, pub phone: String, pub extension: String, }
pub mod connect; pub mod logical; pub mod opaque_transport; #[cfg(test)] mod tests; pub use self::connect::Connect; use crate::target; pub use linkerd_app_core::proxy::tcp::Forward; use linkerd_app_core::{svc::Param, transport::OrigDstAddr, transport_header::SessionProtocol}; pub type Accept = target::Accept<()>; pub type Logical = target::Logical<()>; pub type Concrete = target::Concrete<()>; pub type Endpoint = target::Endpoint<()>; impl From<OrigDstAddr> for Accept { fn from(orig_dst: OrigDstAddr) -> Self { Self { orig_dst, protocol: (), } } } impl<P> From<(P, Accept)> for target::Accept<P> { fn from((protocol, Accept { orig_dst, .. }): (P, Accept)) -> Self { Self { orig_dst, protocol } } } impl Param<Option<SessionProtocol>> for Endpoint { fn param(&self) -> Option<SessionProtocol> { None } }
use multiversion::{ multiversion, target::{match_target, selected_target, target_cfg, target_cfg_attr, target_cfg_f}, }; #[test] fn cfg() { #[multiversion(targets = "simd")] fn foo() { #[target_cfg(all(target_arch = "x86_64", target_feature = "avx"))] fn test_avx(has_avx: bool) { assert!(has_avx); } #[target_cfg(not(all(target_arch = "x86_64", target_feature = "avx")))] fn test_avx(has_avx: bool) { assert!(!has_avx); } let has_avx = std::env::consts::ARCH == "x86_64" && selected_target!().supports_feature_str("avx"); test_avx(has_avx); } foo(); } #[test] fn cfg_attr() { #[multiversion(targets = "simd")] fn foo() { #[target_cfg_attr(all(target_arch = "x86_64", target_feature = "avx"), cfg(all()))] #[target_cfg_attr(not(all(target_arch = "x86_64", target_feature = "avx")), cfg(any()))] fn test_avx(has_avx: bool) { assert!(has_avx); } #[target_cfg_attr(all(target_arch = "x86_64", target_feature = "avx"), cfg(any()))] #[target_cfg_attr(not(all(target_arch = "x86_64", target_feature = "avx")), cfg(all()))] fn test_avx(has_avx: bool) { assert!(!has_avx); } let has_avx = std::env::consts::ARCH == "x86_64" && selected_target!().supports_feature_str("avx"); test_avx(has_avx); } foo(); } #[test] fn cfg_f() { #[multiversion(targets = "simd")] fn foo() { let cfg_avx = target_cfg_f!(all(target_arch = "x86_64", target_feature = "avx")); let has_avx = std::env::consts::ARCH == "x86_64" && selected_target!().supports_feature_str("avx"); assert_eq!(cfg_avx, has_avx); } foo(); } #[test] fn match_target() { #[multiversion(targets = "simd")] fn foo() { let match_avx = match_target! { "x86_64+avx" => true, "aarch64+neon" | "x86_64+sse" => false, _ => false, }; let has_avx = std::env::consts::ARCH == "x86_64" && selected_target!().supports_feature_str("avx"); assert_eq!(match_avx, has_avx); } foo(); }
use crate::edge::Edge; use crate::node::Node; use attributes::{Attributes, AttributesContainer}; use attributes_derive::AttributesContainer; pub mod graph_items { pub mod node { pub use crate::node::Node; } pub mod edge { pub use crate::edge::Edge; } } #[derive(Clone, Debug, PartialEq, AttributesContainer)] pub struct Graph { pub nodes: Vec<Node>, pub edges: Vec<Edge>, #[attributes] pub attrs: Attributes, } impl Graph { pub fn new() -> Self { Self { nodes: Vec::new(), edges: Vec::new(), attrs: Attributes::new(), } } pub fn with_nodes<T>(mut self, nodes: T) -> Self where T: AsRef<[Node]>, { self.nodes.extend(nodes.as_ref().iter().cloned()); self } pub fn with_edges<T>(mut self, edges: T) -> Self where T: AsRef<[Edge]>, { self.edges.extend(edges.as_ref().iter().cloned()); self } pub fn get_node<T>(&self, name: T) -> Option<&Node> where T: Into<String>, { let name = name.into(); self.nodes.iter().find(|&node| node.name == name) } }
use crate::vector::{ Vector3 }; use crate::ray::{ Ray, Intersectable }; use crate::material::{ Material }; use crate::hit::{ Hit }; #[derive(Clone, Copy)] pub struct Sphere { pub position: Vector3, pub radius: f64, pub material: Material, } impl Sphere { pub fn new(position: Vector3, radius: f64, material: Material) -> Self { Self { position, radius, material, } } } impl Intersectable for Sphere { fn intersect(&self, ray: &Ray) -> Option<Hit> { let l = self.position - ray.origin; let tca = Vector3::dot(&l, &ray.direction); if tca < 0.0 { return Option::None; } let d2 = Vector3::dot(&l, &l) - tca * tca; if d2 > self.radius * self.radius { return Option::None; } let thc = (self.radius * self.radius - d2).sqrt(); let mut t0 = tca - thc; let mut t1 = tca + thc; if t0 > t1 { let tmp = t0; t0 = t1; t1 = tmp; } if t0 < 0.0 { t0 = t1; if t0 < 0.0 { return Option::None; } } let t = t0; let hit_point = ray.origin + (ray.direction * t); let mut normal = (hit_point - self.position).normalized(); if Vector3::dot(&normal, &ray.direction) > 0.0 { normal = normal * -1.0; } return Option::from(Hit::new(hit_point, normal, self.material, t)); } }
extern crate serde; extern crate serde_json; extern crate nix; extern crate daemonize; #[macro_use] extern crate clap; #[macro_use] extern crate serde_derive; use std::io::{self, Read}; use nix::unistd::execvp; use std::ffi::CString; use std::path::Path; use daemonize::Daemonize; #[derive(Serialize, Deserialize)] struct ContainerState { id: String, pid: i32 } fn main() { let matches = clap_app!(ocistracehook => (version: "0.1.0") (about: "OCI strace hook") (@arg LOGDIR: -l --logdir +takes_value "Specify directory for storing logs") ).get_matches(); let log_dir = matches.value_of("logdir").unwrap_or("/tmp"); let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer).unwrap(); let cs: ContainerState = serde_json::from_str(&buffer).unwrap(); println!("ID: {}, Pid: {}", cs.id, cs.pid); let log_file_path = Path::new(log_dir).join(cs.id).as_os_str().to_str().unwrap().to_string(); println!("LogPath: {}", log_file_path); let prog = CString::new("strace").unwrap(); let args = &[CString::new("strace").unwrap(), CString::new("-f").unwrap(), CString::new("-o").unwrap(), CString::new(log_file_path).unwrap(), CString::new("-p").unwrap(), CString::new(cs.pid.to_string()).unwrap()]; let daemonize = Daemonize::new().working_directory("/tmp").umask(0o777); daemonize.start().unwrap(); execvp(&prog, args).unwrap(); }
use crate as pallet_transporter; use crate::{Config, TryConvertBack}; use codec::{Decode, Encode}; use domain_runtime_primitives::MultiAccountId; use frame_support::parameter_types; use frame_support::traits::{ConstU16, ConstU32, ConstU64}; use pallet_balances::AccountData; use sp_core::H256; use sp_messenger::endpoint::{EndpointId, EndpointRequest, Sender}; use sp_messenger::messages::ChainId; use sp_runtime::testing::Header; use sp_runtime::traits::{BlakeTwo256, Convert, IdentityLookup}; use sp_runtime::DispatchError; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<MockRuntime>; type Block = frame_system::mocking::MockBlock<MockRuntime>; pub(crate) type Balance = u64; pub(crate) type AccountId = u64; frame_support::construct_runtime!( pub struct MockRuntime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Balances: pallet_balances::{Pallet, Call, Config<T>, Storage, Event<T>}, Transporter: pallet_transporter::{Pallet, Call, Storage, Event<T>}, } ); impl frame_system::Config for MockRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); type PalletInfo = PalletInfo; type AccountData = AccountData<Balance>; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = ConstU16<42>; type OnSetCode = (); type MaxConsumers = ConstU32<16>; } parameter_types! { pub const ExistentialDeposit: u64 = 1; } impl pallet_balances::Config for MockRuntime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); type WeightInfo = (); type FreezeIdentifier = (); type MaxFreezes = (); type RuntimeHoldReason = (); type MaxHolds = (); } parameter_types! { pub SelfChainId: ChainId = 1.into(); pub const SelfEndpointId: EndpointId = 100; } #[derive(Debug)] pub struct MockMessenger {} impl Sender<AccountId> for MockMessenger { type MessageId = u64; fn send_message( _sender: &AccountId, _dst_chain_id: ChainId, _req: EndpointRequest, ) -> Result<Self::MessageId, DispatchError> { Ok(0) } #[cfg(feature = "runtime-benchmarks")] fn unchecked_open_channel(_dst_chain_id: ChainId) -> Result<(), DispatchError> { Ok(()) } } #[derive(Debug)] pub struct MockAccountIdConverter; impl Convert<AccountId, MultiAccountId> for MockAccountIdConverter { fn convert(account_id: AccountId) -> MultiAccountId { MultiAccountId::Raw(account_id.encode()) } } impl TryConvertBack<AccountId, MultiAccountId> for MockAccountIdConverter { fn try_convert_back(multi_account_id: MultiAccountId) -> Option<AccountId> { match multi_account_id { MultiAccountId::Raw(data) => AccountId::decode(&mut data.as_slice()).ok(), _ => None, } } } impl Config for MockRuntime { type RuntimeEvent = RuntimeEvent; type SelfChainId = SelfChainId; type SelfEndpointId = SelfEndpointId; type Currency = Balances; type Sender = MockMessenger; type AccountIdConverter = MockAccountIdConverter; type WeightInfo = (); } pub const USER_ACCOUNT: AccountId = 1; pub const USER_INITIAL_BALANCE: Balance = 1000; pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<MockRuntime>() .unwrap(); pallet_balances::GenesisConfig::<MockRuntime> { balances: vec![(USER_ACCOUNT, USER_INITIAL_BALANCE)], } .assimilate_storage(&mut t) .unwrap(); let mut t: sp_io::TestExternalities = t.into(); t.execute_with(|| System::set_block_number(1)); t }
mod utils; use surf; use utils::{Error, ProbyProcess}; /// If querying a connectable service, Proby returns 200 by default. #[actix_rt::test] async fn connectable_service() -> Result<(), Error> { let mut dh = ProbyProcess::new(Vec::<String>::new())?; let mut resp_body = surf::get(&dh.selfcheck()).await?; assert_eq!(resp_body.status(), 200); assert_eq!( resp_body.body_string().await?, format!("{}:{} is connectable", dh.host, dh.port) ); dh.child.kill()?; Ok(()) } /// If querying an unconnectable service, Proby returns 503 by default. #[actix_rt::test] async fn unconnectable_service() -> Result<(), Error> { let mut dh = ProbyProcess::new(Vec::<String>::new())?; // Generate a URL that's not connectable. let url = format!("{}/{}:{}", dh.url, dh.host, 1); let mut resp_body = surf::get(&url).await?; assert_eq!(resp_body.status(), 503); assert_eq!( resp_body.body_string().await?, format!("{}:{} is NOT connectable", dh.host, 1) ); dh.child.kill()?; Ok(()) } /// We can set a different good status code. #[actix_rt::test] async fn can_configure_good_status_code() -> Result<(), Error> { let mut dh = ProbyProcess::new(Vec::<String>::new())?; let url = format!("{}?good=201", dh.selfcheck()); let mut resp_body = surf::get(url).await?; assert_eq!(resp_body.status(), 201); assert_eq!( resp_body.body_string().await?, format!("{}:{} is connectable", dh.host, dh.port) ); dh.child.kill()?; Ok(()) } /// We can set a different bad status code. #[actix_rt::test] async fn can_configure_bad_status_code() -> Result<(), Error> { let mut dh = ProbyProcess::new(Vec::<String>::new())?; let url = format!("{}?good=500", dh.selfcheck()); let mut resp_body = surf::get(url).await?; assert_eq!(resp_body.status(), 500); assert_eq!( resp_body.body_string().await?, format!("{}:{} is connectable", dh.host, dh.port) ); dh.child.kill()?; Ok(()) }
use criterion::{criterion_group, criterion_main, Criterion}; use rand::thread_rng; use rust_bench::*; fn function_benchmark(c: &mut Criterion) { // around 8MB dataset const VEC_LENGTH: usize = 20_000; const NUM_VECS: usize = 100; let mut rng = thread_rng(); let test_set = TestSet::create(VEC_LENGTH, NUM_VECS, &mut rng); c.bench_function("rng select baseline", |b| { b.iter(|| test_set.sample_pair(&mut rng)) }); c.bench_function("calculate_direct_index", |b| { b.iter(|| { let vecs = test_set.sample_pair(&mut rng); let res = calculate_direct_index(vecs.0, vecs.1); res }) }); c.bench_function("calculate_direct", |b| { b.iter(|| { let vecs = test_set.sample_pair(&mut rng); let res = calculate_direct(vecs.0, vecs.1); res }) }); c.bench_function("calculate_iter", |b| { b.iter(|| { let vecs = test_set.sample_pair(&mut rng); let res = calculate_iter(vecs.0, vecs.1); res }) }); c.bench_function("calculate_fold", |b| { b.iter(|| { let vecs = test_set.sample_pair(&mut rng); let res = calculate_fold(vecs.0, vecs.1); res }) }); c.bench_function("calculate_avx", |b| { b.iter(|| { let vecs = test_set.sample_pair(&mut rng); let res = calculate_avx(vecs.0, vecs.1); res }) }); } criterion_group!(benches, function_benchmark); criterion_main!(benches);
//! Parsing utilities for RON config files. (Requires the `ron-parsing` feature.) //! //! Not all of the RON syntax is currently supported: //! //! 1. Maps are not supported, for example: `{ "a": 1 }`, because `ron` cannot parse them as //! structs. //! 2. Named structs are not supported, for example: `Person(age: 20)`, because the struct name //! is not available at build time, and so cannot match the name in the config file. //! 3. Tuples are not supported, for example: `(1, 2, 3)`. It was attempted and did not work for //! some reason. use ron::{self, value::Value}; use crate::{ error::GenerationError, options::StructOptions, parsing, value::{GenericStruct, GenericValue}, }; pub fn parse_ron(ron: &str, options: &StructOptions) -> Result<GenericStruct, GenerationError> { use parsing::ParsedFields; let ron_struct = { let ron_object: Value = ron::de::from_str(ron) .map_err(|err| GenerationError::DeserializationFailed(err.to_string()))?; if let Value::Map(mapping) = ron_object { mapping .into_iter() .map(|(key, value)| { let key = { if let Value::String(key) = key { key } else { let m = "Top-level keys in RON map must be strings.".to_owned(); return Err(GenerationError::DeserializationFailed(m)); } }; Ok((key, value)) }) .collect::<Result<ParsedFields<Value>, GenerationError>>()? } else { let m = "Root RON object must be a struct or map.".to_owned(); return Err(GenerationError::DeserializationFailed(m)); } }; let generic_struct = parsing::parsed_to_generic_struct(ron_struct, options, ron_to_raw_value); Ok(generic_struct) } #[allow(clippy::float_cmp)] fn ron_to_raw_value( super_struct: &str, super_key: &str, value: Value, options: &StructOptions, ) -> GenericValue { match value { Value::Unit => GenericValue::Unit, Value::Bool(value) => GenericValue::Bool(value), Value::Char(value) => GenericValue::Char(value), Value::Number(value) => { let float = value.get(); if float.trunc() == float { parsing::preferred_int(float as i64, options.default_int_size) } else { parsing::preferred_float(float, options.default_float_size) } } Value::String(value) => GenericValue::String(value), Value::Option(option) => GenericValue::Option( option .map(|value| Box::new(ron_to_raw_value(super_struct, super_key, *value, options))), ), Value::Seq(values) => GenericValue::Array( values .into_iter() .map(|value| ron_to_raw_value(super_struct, super_key, value, options)) .collect(), ), Value::Map(values) => { let sub_struct_name = format!("{}__{}", super_struct, super_key); let values = values .into_iter() .map(|(key, value)| { let key = { if let Value::String(key) = key { key } else { unimplemented!("We should handle an error here"); } }; let value = ron_to_raw_value(&sub_struct_name, &key, value, options); (key, value) }) .collect(); GenericValue::Struct(GenericStruct { struct_name: sub_struct_name, fields: values, }) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_non_string_keys() { let ron_code = r#"(100: "One hundred")"#; assert!(parse_ron(ron_code, &StructOptions::default()).is_err()); } #[test] fn test_non_struct_root_object() { let ron_code = r#"["key", "value"]"#; assert!(parse_ron(ron_code, &StructOptions::default()).is_err()); } }
pub type OperList = Vec<Oper>; #[derive(Clone, Debug, PartialEq)] pub enum Oper { Plus, Minus, Times, Divide, Mod, Eq, Neq, Lt, Le, Gt, Ge, And, Or, Subscript, TypeEq, Deref, Address, UMinus, Not, None, } pub fn string_to_oper(name: &str) -> Oper { match name { "AddOp" => Oper::Plus, "SubOp" => Oper::Minus, "EqOp" => Oper::Eq, "NeOp" => Oper::Neq, "LtOp" => Oper::Lt, "LeOp" => Oper::Le, "GtOp" => Oper::Gt, "GeOp" => Oper::Ge, "AndOp" => Oper::And, "OrOp" => Oper::Or, "MulOp" => Oper::Times, "DivOp" => Oper::Divide, "DerefOp" => Oper::Deref, "AddressOp" => Oper::Address, "NotOp" => Oper::Not, _ => Oper::None, } }
#![allow(dead_code)] pub enum ClipboardContentType { #[cfg(any(target_os="linux", target_os="openbsd"))] X11ContentType(X11ContentType), #[cfg(target_os="windows")] WinContentType(WinContentType), #[cfg(target_os="macos")] MacContent, } /// See: https://tronche.com/gui/x/icccm/sec-2.html#s-2 #[cfg(any(target_os="linux", target_os="openbsd"))] pub enum X11ContentType { AdobePortableDocumentFormat, ApplePict, /// A list of pixel values Background, /// A list of bitmap IDs Bitmap, /// The start and end of the selection in bytes CharacterPosition, Class, /// Any top-level window owned by the selection owner ClientWindow, /// A list of colormap IDs Colormap, /// The start and end column numbers ColumnNumber, /// Compound Text CompoundText, Delete, /// A list of drawable IDs Drawable, Eps, EpsInterchange, /// The full path name of a file FileName, /// A list of pixel values Foreground, HostName, InsertProperty, InsertSelection, /// The number of bytes in the selection Length, /// The start and end line numbers LineNumber, /// The number of disjoint parts of the selection ListLength, /// The name of the selected procedure Module, Multiple, Name, /// ISO Office Document Interchange Format Odif, /// The operating system of the owner client OwnerOs, /// A list of pixmap IDs Pixmap, Postscript, /// The name of the selected procedure Procedure, /// The process ID of the owner Process, /// ISO Latin-1 (+TAB+NEWLINE) text String, /// A list of valid target atoms Targets, /// The task ID of the owner Task, /// The text in the owner's choice of encoding Text, /// The timestamp used to acquire the selection Timestamp, /// The name of the user running the owner User, } /// See https://msdn.microsoft.com/en-us/library/windows/desktop/ff729168%28v=vs.85%29.aspx #[cfg(target_os="windows")] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum WinContentType { /// A handle to a bitmap (HBITMAP) Bitmap, /// A memory object containing a BITMAPINFO structure followed by the bitmap bits. Dib, /// A memory object containing a BITMAPV5HEADER structure followed by /// the bitmap color space information and the bitmap bits. Dib5, /// Software Arts' Data Interchange Format. Dif, /// Bitmap display format associated with a private format. The hMem parameter must be a /// handle to data that can be displayed in bitmap format in lieu of the privately /// formatted data. DspBitmap, /// CF_DSPENHMETAFILE: Enhanced metafile display format associated with a private /// format. The hMem parameter must be a handle to data that can be displayed in /// enhanced metafile format in lieu of the privately formatted data. DspEnhancedMetaFile, /// CF_DSPMETAFILEPICT: Metafile-picture display format associated with a private /// format. The hMem parameter must be a handle to data that can be displayed in /// metafile-picture format in lieu of the privately formatted data. DspMetaFilePict, /// Text display format associated with a private format. The hMem parameter must /// be a handle to data that can be displayed in text format in lieu of the /// privately formatted data. DspText, /// A handle to an enhanced metafile (HENHMETAFILE). EnhancedMetaFile, /// Start of a range of integer values for application-defined /// GDI object clipboard formats. GdiObjectFirst, /// End of a range of integer values for application-defined GDI /// object clipboard formats. GdiObjectLast, /// A handle to type HDROP that identifies a list of files. HDrop, /// The data is a handle to the locale identifier associated /// with text in the clipboard. Locale, /// Handle to a metafile picture format as defined by the METAFILEPICT structure. MetaFilePict, /// Text format containing characters in the OEM character set. OemText, /// Owner-display format OwnerDisplay, /// Handle to a color palette Palette, /// Data for the pen extensions to the Microsoft Windows for Pen Computing PenData, /// Start of a range of integer values for private clipboard formats PrivateFirst, /// End of a range of integer values for private clipboard formats PrivateLast, /// Represents audio data more complex than can be represented in a CF_WAVE standard wave format Riff, /// Microsoft Symbolic Link (SYLK) format Sylk, /// ANSI text format Text, /// Tagged-image file format Tiff, /// UTF16 text format UnicodeText, /// Represents audio data in one of the standard wave formats Wave, /// Custom content type, used as backup if none of the formats are known Custom(u32), } #[cfg(target_os="windows")] impl WinContentType { /// Toggles through the clipboard types pub(crate) fn next(&self) -> Option<Self> { use self::WinContentType::*; match self { Bitmap => Some(Dib), Dib => Some(Dib5), Dib5 => Some(Dif), Dif => Some(DspBitmap), DspBitmap => Some(DspEnhancedMetaFile), DspEnhancedMetaFile => Some(DspMetaFilePict), DspMetaFilePict => Some(DspText), DspText => Some(EnhancedMetaFile), EnhancedMetaFile => Some(GdiObjectFirst), GdiObjectFirst => Some(GdiObjectLast), GdiObjectLast => Some(HDrop), HDrop => Some(Locale), Locale => Some(MetaFilePict), MetaFilePict => Some(OemText), OemText => Some(OwnerDisplay), OwnerDisplay => Some(Palette), Palette => Some(PenData), PenData => Some(PrivateFirst), PrivateFirst => Some(PrivateLast), PrivateLast => Some(Riff), Riff => Some(Sylk), Sylk => Some(Text), Text => Some(Tiff), Tiff => Some(UnicodeText), UnicodeText => Some(Wave), Wave => Some(Custom((*self).into())), Custom(_) => None, } } } #[cfg(target_os="windows")] impl Into<u32> for WinContentType { fn into(self) -> u32 { use self::WinContentType::*; use clipboard_win::formats::*; match self { Bitmap => CF_BITMAP, Custom(a) => a, Dib => CF_DIB, Dib5 => CF_DIBV5, Dif => CF_DIF, DspBitmap => CF_DSPBITMAP, DspEnhancedMetaFile => CF_DSPENHMETAFILE, DspMetaFilePict => CF_DSPMETAFILEPICT, DspText => CF_DSPTEXT, EnhancedMetaFile => CF_ENHMETAFILE, GdiObjectFirst => CF_GDIOBJFIRST, GdiObjectLast =>CF_GDIOBJLAST, HDrop => CF_HDROP, Locale => CF_LOCALE, MetaFilePict => CF_METAFILEPICT, OemText => CF_OEMTEXT, OwnerDisplay => CF_OWNERDISPLAY, Palette => CF_PALETTE, PenData => CF_PENDATA, PrivateFirst => CF_PRIVATEFIRST, PrivateLast => CF_PRIVATELAST, Riff => CF_RIFF, Sylk => CF_SYLK, Text => CF_TEXT, Tiff => CF_TIFF, UnicodeText => CF_UNICODETEXT, Wave => CF_WAVE, } } }
#![feature(min_type_alias_impl_trait)] mod chromosome; mod crossover; mod individual; mod mutation; mod selection; use chromosome::Chromosome; use individual::Individual; pub use crossover::{CrossoverMethod, UniformCrossover}; pub use mutation::{GaussianMutation, MutationMethod}; pub use selection::{RouletteWheelSelection, SelectionMethod}; use rand::RngCore; pub struct GeneticAlgorithm<C, M, S> { crossover_method: C, mutation_method: M, selection_method: S, } impl<C, M, S> GeneticAlgorithm<C, M, S> where C: CrossoverMethod, M: MutationMethod, S: SelectionMethod, { pub fn new(crossover_method: C, mutation_method: M, selection_method: S) -> Self { Self { crossover_method, mutation_method, selection_method, } } pub fn evolve<I>(&self, rng: &mut dyn RngCore, population: &[I]) -> Vec<I> where I: Individual, { assert!(!population.is_empty()); (0..population.len()) .map(|_| { let parent_a = self.selection_method.select(rng, population).chromosome(); let parent_b = self.selection_method.select(rng, population).chromosome(); let mut child = self.crossover_method.crossover(rng, &parent_a, &parent_b); self.mutation_method.mutate(rng, &mut child); I::create(child) }) .collect() } } #[cfg(test)] #[derive(Debug, PartialEq)] enum TestIndividual { WithChromosome { chromosome: Chromosome }, WithFitness { fitness: f32 }, } #[cfg(test)] impl TestIndividual { fn new_with_fitness(fitness: f32) -> Self { Self::WithFitness { fitness } } } #[cfg(test)] impl Individual for TestIndividual { fn fitness(&self) -> f32 { match self { Self::WithFitness { fitness } => *fitness, Self::WithChromosome { chromosome } => chromosome.iter().sum(), } } fn create(chromosome: Chromosome) -> Self { Self::WithChromosome { chromosome } } fn chromosome(&self) -> &Chromosome { match self { Self::WithChromosome { chromosome } => &chromosome, _ => panic!("not supported on this variant"), } } } #[cfg(test)] mod test { use super::*; use rand::SeedableRng; use rand_chacha::ChaCha8Rng as Cc8; fn individual(genes: &[f32]) -> TestIndividual { let chromosome = genes.iter().cloned().collect(); TestIndividual::create(chromosome) } #[test] fn evolution() { let mut rng = Cc8::from_seed(Default::default()); let ga = GeneticAlgorithm::new( UniformCrossover::new(), GaussianMutation::new(0.5, 0.5), RouletteWheelSelection::new(), ); let mut population = vec![ individual(&[0.0, 0.0, 0.0]), // fitness = 0.0 individual(&[1.0, 1.0, 1.0]), // fitness = 3.0 individual(&[1.0, 2.0, 1.0]), // fitness = 4.0 individual(&[1.0, 2.0, 4.0]), // fitness = 7.0 ]; for _ in 0..10 { population = ga.evolve(&mut rng, &population); } let expected_population = vec![ individual(&[0.44769490, 2.0648358, 4.3058133]), individual(&[1.21268670, 1.5538777, 2.8869110]), individual(&[1.06176780, 2.2657390, 4.4287640]), individual(&[0.95909685, 2.4618788, 4.0247330]), ]; assert_eq!(population, expected_population); } }
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin: cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::<String>(); token.parse::<T>().ok() } fn input<T: FromStr>(&mut self) -> T { self.read().unwrap() } fn vec<T: FromStr>(&mut self, len: usize) -> Vec<T> { (0..len).map(|_| self.input()).collect() } fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> { (0..row).map(|_| self.vec(col)).collect() } } fn main() { let cin = stdin(); let cin = cin.lock(); let mut sc = Scanner::new(cin); let (n, s, d): (usize, usize, usize) = (sc.input(), sc.input(), sc.input()); let mut xy = vec![(0, 0); n]; for i in 0..n { let (x, y): (usize, usize)= (sc.input(), sc.input()); xy[i] = (x, y); } let mut ok = false; for (x, y) in xy { if x < s && y > d { ok = true; break; } } println!("{}", if ok { "Yes" } else { "No" }); }
use serde::Deserialize; pub type Res<T> = Result<T, Box<dyn std::error::Error>>; #[derive(Deserialize)] pub struct WallpaperPost { pub subreddit: String, pub ups: u32, pub url: String, //created: f64, TODO: implement use for this later pub author: String, } #[derive(Deserialize)] pub struct Post { pub data: WallpaperPost } #[derive(Deserialize)] pub struct Data { pub children: Vec<Post>, pub after: String, // TODO: support for pagination later } #[derive(Deserialize)] pub struct RedditResponse { pub data: Data, }
fn step_by_2(s: &str) -> String{ s.chars().step_by(2).collect() } fn main(){ let s1 = String::from("パタトクカシーー"); println!("{}",step_by_2(&s1)); }
// Copyright (c) 2017 oic developers // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. //! This structure is used for transferring error information from ODPI-C. use odpi::structs::ODPIErrorInfo; use std::ffi::CStr; use std::{fmt, slice}; /// This structure is used for transferring error information from ODPI-C. All of the strings /// referenced here may become invalid as soon as the next ODPI-C call is made. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Info { /// The OCI error code if an OCI error has taken place. If no OCI error has taken place the /// value is 0. code: i32, /// The parse error offset (in bytes) when executing a statement or the row offset when /// fetching batch error information. If neither of these cases are true, the value is 0. offset: u16, /// The error message as a string. message: String, /// The public ODPI-C function name which was called in which the error took place. fn_name: String, /// The internal action that was being performed when the error took place. action: String, /// The SQLSTATE code associated with the error. sql_state: String, /// A boolean value indicating if the error is recoverable. This member always has a false value /// unless both client and server are at release 12.1 or higher. recoverable: bool, } impl Info { /// Create a new `Info` struct. pub fn new(code: i32, offset: u16, message: String, fn_name: String, action: String, sql_state: String, recoverable: bool) -> Info { Info { code: code, offset: offset, message: message, fn_name: fn_name, action: action, sql_state: sql_state, recoverable: recoverable, } } /// Get the `code` value. pub fn code(&self) -> i32 { self.code } /// Get the `offset` value. pub fn offset(&self) -> u16 { self.offset } /// Get the `message` value. pub fn message(&self) -> &str { &self.message } /// Get the `fn_name` value. pub fn fn_name(&self) -> &str { &self.fn_name } /// Get the `action` value. pub fn action(&self) -> &str { &self.action } /// Get the `sql_state` value. pub fn sql_state(&self) -> &str { &self.sql_state } /// Get the `recoverable` value. pub fn recoverable(&self) -> bool { self.recoverable } } impl fmt::Display for Info { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{}: {}\nfn: {}\naction: {}\nsql_state: {}\nrecoverable: {}", self.code, self.message, self.fn_name, self.action, self.sql_state, self.recoverable) } } impl From<ODPIErrorInfo> for Info { fn from(err: ODPIErrorInfo) -> Info { let slice = unsafe { slice::from_raw_parts(err.message as *mut u8, err.message_length as usize) }; let fn_name = unsafe { CStr::from_ptr(err.fn_name) } .to_string_lossy() .into_owned(); let action = unsafe { CStr::from_ptr(err.action) } .to_string_lossy() .into_owned(); let sql_state = unsafe { CStr::from_ptr(err.sql_state) } .to_string_lossy() .into_owned(); Info::new(err.code, err.offset, String::from_utf8_lossy(slice).into_owned(), fn_name, action, sql_state, err.is_recoverable.is_positive()) } }
#[doc = "Register `C1IER` reader"] pub type R = crate::R<C1IER_SPEC>; #[doc = "Register `C1IER` writer"] pub type W = crate::W<C1IER_SPEC>; #[doc = "Field `ISE0` reader - Interrupt semaphore n enable bit"] pub type ISE0_R = crate::BitReader<ISE0_A>; #[doc = "Interrupt semaphore n enable bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ISE0_A { #[doc = "0: Interrupt generation disabled"] Disabled = 0, #[doc = "1: Interrupt generation enabled"] Enabled = 1, } impl From<ISE0_A> for bool { #[inline(always)] fn from(variant: ISE0_A) -> Self { variant as u8 != 0 } } impl ISE0_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ISE0_A { match self.bits { false => ISE0_A::Disabled, true => ISE0_A::Enabled, } } #[doc = "Interrupt generation disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == ISE0_A::Disabled } #[doc = "Interrupt generation enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == ISE0_A::Enabled } } #[doc = "Field `ISE0` writer - Interrupt semaphore n enable bit"] pub type ISE0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ISE0_A>; impl<'a, REG, const O: u8> ISE0_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Interrupt generation disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(ISE0_A::Disabled) } #[doc = "Interrupt generation enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(ISE0_A::Enabled) } } #[doc = "Field `ISE1` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE1_R; #[doc = "Field `ISE2` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE2_R; #[doc = "Field `ISE3` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE3_R; #[doc = "Field `ISE4` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE4_R; #[doc = "Field `ISE5` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE5_R; #[doc = "Field `ISE6` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE6_R; #[doc = "Field `ISE7` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE7_R; #[doc = "Field `ISE8` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE8_R; #[doc = "Field `ISE9` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE9_R; #[doc = "Field `ISE10` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE10_R; #[doc = "Field `ISE11` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE11_R; #[doc = "Field `ISE12` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE12_R; #[doc = "Field `ISE13` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE13_R; #[doc = "Field `ISE14` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE14_R; #[doc = "Field `ISE15` reader - Interrupt semaphore n enable bit"] pub use ISE0_R as ISE15_R; #[doc = "Field `ISE1` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE1_W; #[doc = "Field `ISE2` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE2_W; #[doc = "Field `ISE3` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE3_W; #[doc = "Field `ISE4` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE4_W; #[doc = "Field `ISE5` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE5_W; #[doc = "Field `ISE6` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE6_W; #[doc = "Field `ISE7` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE7_W; #[doc = "Field `ISE8` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE8_W; #[doc = "Field `ISE9` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE9_W; #[doc = "Field `ISE10` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE10_W; #[doc = "Field `ISE11` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE11_W; #[doc = "Field `ISE12` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE12_W; #[doc = "Field `ISE13` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE13_W; #[doc = "Field `ISE14` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE14_W; #[doc = "Field `ISE15` writer - Interrupt semaphore n enable bit"] pub use ISE0_W as ISE15_W; impl R { #[doc = "Bit 0 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise0(&self) -> ISE0_R { ISE0_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise1(&self) -> ISE1_R { ISE1_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise2(&self) -> ISE2_R { ISE2_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise3(&self) -> ISE3_R { ISE3_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise4(&self) -> ISE4_R { ISE4_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise5(&self) -> ISE5_R { ISE5_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise6(&self) -> ISE6_R { ISE6_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise7(&self) -> ISE7_R { ISE7_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise8(&self) -> ISE8_R { ISE8_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise9(&self) -> ISE9_R { ISE9_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise10(&self) -> ISE10_R { ISE10_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise11(&self) -> ISE11_R { ISE11_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise12(&self) -> ISE12_R { ISE12_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise13(&self) -> ISE13_R { ISE13_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise14(&self) -> ISE14_R { ISE14_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - Interrupt semaphore n enable bit"] #[inline(always)] pub fn ise15(&self) -> ISE15_R { ISE15_R::new(((self.bits >> 15) & 1) != 0) } } impl W { #[doc = "Bit 0 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise0(&mut self) -> ISE0_W<C1IER_SPEC, 0> { ISE0_W::new(self) } #[doc = "Bit 1 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise1(&mut self) -> ISE1_W<C1IER_SPEC, 1> { ISE1_W::new(self) } #[doc = "Bit 2 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise2(&mut self) -> ISE2_W<C1IER_SPEC, 2> { ISE2_W::new(self) } #[doc = "Bit 3 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise3(&mut self) -> ISE3_W<C1IER_SPEC, 3> { ISE3_W::new(self) } #[doc = "Bit 4 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise4(&mut self) -> ISE4_W<C1IER_SPEC, 4> { ISE4_W::new(self) } #[doc = "Bit 5 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise5(&mut self) -> ISE5_W<C1IER_SPEC, 5> { ISE5_W::new(self) } #[doc = "Bit 6 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise6(&mut self) -> ISE6_W<C1IER_SPEC, 6> { ISE6_W::new(self) } #[doc = "Bit 7 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise7(&mut self) -> ISE7_W<C1IER_SPEC, 7> { ISE7_W::new(self) } #[doc = "Bit 8 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise8(&mut self) -> ISE8_W<C1IER_SPEC, 8> { ISE8_W::new(self) } #[doc = "Bit 9 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise9(&mut self) -> ISE9_W<C1IER_SPEC, 9> { ISE9_W::new(self) } #[doc = "Bit 10 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise10(&mut self) -> ISE10_W<C1IER_SPEC, 10> { ISE10_W::new(self) } #[doc = "Bit 11 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise11(&mut self) -> ISE11_W<C1IER_SPEC, 11> { ISE11_W::new(self) } #[doc = "Bit 12 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise12(&mut self) -> ISE12_W<C1IER_SPEC, 12> { ISE12_W::new(self) } #[doc = "Bit 13 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise13(&mut self) -> ISE13_W<C1IER_SPEC, 13> { ISE13_W::new(self) } #[doc = "Bit 14 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise14(&mut self) -> ISE14_W<C1IER_SPEC, 14> { ISE14_W::new(self) } #[doc = "Bit 15 - Interrupt semaphore n enable bit"] #[inline(always)] #[must_use] pub fn ise15(&mut self) -> ISE15_W<C1IER_SPEC, 15> { ISE15_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "HSEM Interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`c1ier::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`c1ier::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct C1IER_SPEC; impl crate::RegisterSpec for C1IER_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`c1ier::R`](R) reader structure"] impl crate::Readable for C1IER_SPEC {} #[doc = "`write(|w| ..)` method takes [`c1ier::W`](W) writer structure"] impl crate::Writable for C1IER_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets C1IER to value 0"] impl crate::Resettable for C1IER_SPEC { const RESET_VALUE: Self::Ux = 0; }
use rustyline::{completion::Completer, validate::Validator}; use rustyline::highlight::Highlighter; use rustyline::hint::Hinter; use rustyline::{CompletionType, Config, Context, Editor, Helper}; use crate::input::UserInput; pub struct CliEditor { // TODO } impl Completer for CliEditor { type Candidate = String; fn complete( &self, line: &str, pos: usize, _: &Context<'_>, ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> { let start = line .chars() .enumerate() .find(|(_, i)| !i.is_whitespace()) .map(|(i, _)| i) .unwrap_or(0); let subs = if pos > start { &line[start..pos] } else { &line[start..] }; let base = UserInput::values() .iter() .filter(|s| s.starts_with(subs)) .map(|&s| s.to_owned()) .collect(); Ok((start, base)) } } impl Hinter for CliEditor { // TODO } impl Highlighter for CliEditor {} impl Validator for CliEditor {} impl Helper for CliEditor {} impl CliEditor { pub fn into_editor(self) -> Editor<CliEditor> { let mut r = Editor::with_config( Config::builder() .history_ignore_space(true) .completion_type(CompletionType::List) .build(), ); r.set_helper(Some(self)); r } }
#[macro_use] extern crate static_assertions; pub mod blas; pub mod driver; pub mod extras; pub mod ffi; pub mod rand; pub mod runtime;
// least significant --> most significant pub fn u32_to_u16(value: u32) -> (u16, u16) { (value as u16, (value >> 16) as u16) } // least significant --> most significant pub fn u32_to_u8(value: u32) -> (u8, u8, u8, u8) { (value as u8, (value >> 8) as u8, (value >> 16) as u8, (value >> 24) as u8) } // least significant --> most significant pub fn u16_to_u8(value: u16) -> (u8, u8) { (value as u8, (value >> 8) as u8) }
#![allow(dead_code)] mod render; pub mod vector; extern crate termion; fn main() { render::test(); }
use super::*; /// The function macro (bound to `fn`) takes a function form that has the following elements: /// 1. The `fn` symbol, /// 2. An optional symbol providing the function's name for recursive calls, /// 3. A list of arguments, /// 4. Zero or more _silent_ expressions, that are evaluated for their side-effects, and /// 5. A last expression that is evaluated to produce the return value. /// /// ``` /// use risp::*; /// use risp::builtins::*; /// let mut ctx = BasicStaticContext::new(); /// install_builtins(&mut ctx); /// let form = read("(fn (x) x)").unwrap()[0].clone(); /// let compiled = compile(form, &ctx).unwrap(); /// assert_eq!(compiled.call(&vec![RispValue::Int(2)].into_iter().collect()), /// Ok(RispValue::Int(2))); /// ``` pub fn fn_macro(form: RispValue) -> Result<RispValue, CompilationError> { let mut i = form.iter(); i.next(); // Consume fn symbol let formal_args = i.next().ok_or(CompilationError::ArityMismatch(1, 0))?.clone(); let body = i.next().ok_or(CompilationError::ArityMismatch(2, 1))?.clone(); Ok(RispValue::Fn(RispFunc::new(Arc::new(move |act_args| { let bindings = act_args.match_pattern(&formal_args).ok_or(CompilationError::ArityMismatch(0,0))?; body.eval(&DerivedDynamicContext::new(&BasicDynamicContext::new(), bindings)) })))) } /// Installs all builtins to the given static context pub fn install_builtins(ctx: &mut BasicStaticContext) { ctx.define_macro(String::from("fn"), Box::new(fn_macro)); }
use crate::multiset::MultiSet; use ark_bls12_381::Fr; use num_traits::identities::One; /// Computes the multisets h_1 and h_2 pub fn compute_h1_h2(f: &MultiSet, t: &MultiSet) -> (MultiSet, MultiSet) { // // 1. Compute s // XXX: we no longer use sorted by t definition let sorted_s = f.concatenate_and_sort(&t); //2 . Compute h_1 and h_2 let (h_1, h_2) = sorted_s.halve(); // assert that the last element of h_1 is equal to the first element of h_2 assert_eq!(h_1.0.last().unwrap(), &h_2.0[0]); (h_1, h_2) } // Computes the i+1'th term of F(beta, gamma) fn compute_f_i(i: usize, f: &MultiSet, t: &MultiSet, beta: Fr, gamma: Fr) -> Fr { let gamma_beta_one = gamma * (beta + Fr::one()); // (gamma + f_i) * [gamma *(1 + beta) + t_i + beta * t_{i+1}] (gamma + f.0[i]) * (gamma_beta_one + t.0[i] + (beta * t.0[i + 1])) } // Computes the i+1'th term of F(beta, gamma) fn compute_g_i(i: usize, h_1: &MultiSet, h_2: &MultiSet, beta: Fr, gamma: Fr) -> Fr { let gamma_one_b = gamma * (Fr::one() + beta); // gamma * (1 + beta) + s_j + beta * s_{j+1} let d = gamma_one_b + h_1.0[i] + (beta * h_1.0[i + 1]); // gamma * (1 + beta) + s_{n+j} + beta * s_{n+j+1} let e = gamma_one_b + h_2.0[i] + (beta * h_2.0[i + 1]); d * e } /// Computes the values for Z(X) pub fn compute_accumulator_values( f: &MultiSet, t: &MultiSet, h_1: &MultiSet, h_2: &MultiSet, beta: Fr, gamma: Fr, ) -> Vec<Fr> { let n = f.len(); // F(beta, gamma) let mut numerator: Vec<Fr> = Vec::with_capacity(n + 1); // G(beta, gamma) let mut denominator: Vec<Fr> = Vec::with_capacity(n + 1); // Z evaluated at the first root of unity is 1 numerator.push(Fr::one()); denominator.push(Fr::one()); let beta_one = Fr::one() + beta; // Compute values for Z(X) for i in 0..n { let f_i = beta_one * compute_f_i(i, f, t, beta, gamma); let g_i = compute_g_i(i, h_1, h_2, beta, gamma); let last_numerator = *numerator.last().unwrap(); let last_denominator = *denominator.last().unwrap(); numerator.push(f_i * last_numerator); denominator.push(g_i * last_denominator); } // Check that Z(g^{n+1}) = 1 let last_numerator = *numerator.last().unwrap(); let last_denominator = *denominator.last().unwrap(); assert_eq!(last_numerator / last_denominator, Fr::one()); // Combine numerator and denominator assert_eq!(numerator.len(), denominator.len()); assert_eq!(numerator.len(), n + 1); let mut evaluations = Vec::with_capacity(numerator.len()); for (n, d) in numerator.into_iter().zip(denominator) { evaluations.push(n / d) } evaluations } #[cfg(test)] mod test { use super::*; use ark_poly::{ polynomial::univariate::DensePolynomial as Polynomial, EvaluationDomain, Polynomial as Poly, Radix2EvaluationDomain, UVPolynomial, }; #[test] fn test_manually_compute_z() { // This test manually computes the values of the accumulator Z(x) // Notice that the test will fail if: // - You add a value to 'f' that is not in 't' // - 't' is unordered // Now notice that the test will pass if: // - (1) len(t) != len(f) + 1 // - (2) len(t) is not a power of two // The reason why the tests pass for these values is : // (1) We made this restriction, so that it would be easier to check that h_1 and h_2 are continuous. This should not affect the outcome of Z(X) if h_1 and h_2 when merged // indeed form 's' // (2) This is a restriction that is placed upon the protocol due to using roots of unity. It would not affect the computation of Z(X) let mut f = MultiSet::new(); f.push(Fr::from(1u8)); f.push(Fr::from(1u8)); f.push(Fr::from(2u8)); f.push(Fr::from(2u8)); f.push(Fr::from(3u8)); f.push(Fr::from(3u8)); f.push(Fr::from(3u8)); // Table of values let mut t = MultiSet::new(); t.push(Fr::from(1u8)); t.push(Fr::from(1u8)); t.push(Fr::from(2u8)); t.push(Fr::from(2u8)); t.push(Fr::from(3u8)); t.push(Fr::from(3u8)); t.push(Fr::from(4u8)); t.push(Fr::from(5u8)); let beta = Fr::from(8u8); let gamma = Fr::from(10u8); let (h_1, h_2) = compute_h1_h2(&f, &t); let beta_one = Fr::one() + beta; // Manually compute the accumulator values // // First value of z_0 is 1 / 1 let z_0_numerator = Fr::one(); let z_0_denominator = Fr::one(); let z_0 = z_0_numerator / z_0_denominator; // // Next value z_1 is (1+beta) * (z_0_numerator * f_0) / (z_0_denominator * g_0) let f_0 = compute_f_i(0, &f, &t, beta, gamma); let g_0 = compute_g_i(0, &h_1, &h_2, beta, gamma); let z_1_numerator = beta_one * z_0_numerator * f_0; let z_1_denominator = z_0_denominator * g_0; let z_1 = z_1_numerator / z_1_denominator; // // Next value z_2 is (1+beta)^2 * (z_1_numerator * f_1) / (z_1_denominator * g_1) let f_1 = compute_f_i(1, &f, &t, beta, gamma); let g_1 = compute_g_i(1, &h_1, &h_2, beta, gamma); let z_2_numerator = beta_one * z_1_numerator * f_1; let z_2_denominator = z_1_denominator * g_1; let z_2 = z_2_numerator / z_2_denominator; // // Next value z_3 is (1+beta)^3 * (z_2_numerator * f_2) / (z_2_denominator * g_2) let f_2 = compute_f_i(2, &f, &t, beta, gamma); let g_2 = compute_g_i(2, &h_1, &h_2, beta, gamma); let z_3_numerator = beta_one * z_2_numerator * f_2; let z_3_denominator = z_2_denominator * g_2; let z_3 = z_3_numerator / z_3_denominator; // // Next value z_4 is (1+beta)^4 * (z_3_numerator * f_3) / (z_3_denominator * g_3) let f_3 = compute_f_i(3, &f, &t, beta, gamma); let g_3 = compute_g_i(3, &h_1, &h_2, beta, gamma); let z_4_numerator = beta_one * z_3_numerator * f_3; let z_4_denominator = z_3_denominator * g_3; let z_4 = z_4_numerator / z_4_denominator; // // Next value z_5 is (1+beta)^5 * (z_4_numerator * f_4) / (z_4_denominator * g_4) let f_4 = compute_f_i(4, &f, &t, beta, gamma); let g_4 = compute_g_i(4, &h_1, &h_2, beta, gamma); let z_5_numerator = beta_one * z_4_numerator * f_4; let z_5_denominator = z_4_denominator * g_4; let z_5 = z_5_numerator / z_5_denominator; // // Next value z_6 is (1+beta)^6 * (z_5_numerator * f_5) / (z_5_denominator * g_5) let f_5 = compute_f_i(5, &f, &t, beta, gamma); let g_5 = compute_g_i(5, &h_1, &h_2, beta, gamma); let z_6_numerator = beta_one * z_5_numerator * f_5; let z_6_denominator = z_5_denominator * g_5; let z_6 = z_6_numerator / z_6_denominator; // // Last value z_7 is (1+beta)^7 * (z_6_numerator * f_6) / (z_6_denominator * g_6) // For an honest prover, this should be 1 let f_6 = compute_f_i(6, &f, &t, beta, gamma); let g_6 = compute_g_i(6, &h_1, &h_2, beta, gamma); let z_7_numerator = beta_one * z_6_numerator * f_6; let z_7_denominator = z_6_denominator * g_6; let z_7 = z_7_numerator / z_7_denominator; // Check that the next value in z can be computed using the previously accumulated values multiplied by the next term // ie z_{n+1} = (1+beta) * z_n * (f_n / g_n) // Except for the last element which should be equal to 1 assert_eq!(z_1, beta_one * z_0 * (f_0 / g_0)); assert_eq!(z_2, beta_one * z_1 * (f_1 / g_1)); assert_eq!(z_3, beta_one * z_2 * (f_2 / g_2)); assert_eq!(z_4, beta_one * z_3 * (f_3 / g_3)); assert_eq!(z_5, beta_one * z_4 * (f_4 / g_4)); assert_eq!(z_6, beta_one * z_5 * (f_5 / g_5)); assert_eq!(z_7, Fr::one()); // Now check if we get the same values when computed by our function let expected_z_evaluations = vec![z_0, z_1, z_2, z_3, z_4, z_5, z_6, z_7]; let z_evaluations = compute_accumulator_values(&f, &t, &h_1, &h_2, beta, gamma); assert_eq!(expected_z_evaluations.len(), z_evaluations.len()); for (should_be, got) in expected_z_evaluations.iter().zip(z_evaluations.iter()) { assert_eq!(should_be, got) } } #[test] fn test_h1_h2() { // Checks whether h_1 and h_2 are well formed(continuous) in s // This is done by checking that the last element of h_1 is the first element of h_2 let (f, t, _) = setup_correct_test(); // Compute h_1(x) and h_2(x) from f and t let (h_1, h_2) = compute_h1_h2(&f, &t); let domain: Radix2EvaluationDomain<Fr> = EvaluationDomain::new(h_1.len()).unwrap(); let h_1_poly = h_1.to_polynomial(&domain); let h_2_poly = h_2.to_polynomial(&domain); // compute the last and first element in the domain let last_element = domain.elements().last().unwrap(); let first_element = Fr::one(); let h_1_last = h_1_poly.evaluate(&last_element); let h_2_first = h_2_poly.evaluate(&first_element); assert_eq!(h_1_last, h_2_first); } #[test] fn test_term_check() { // Checks whether z_{n+1} = z_n * (f_n / g_n) holds for every value in the domain except for the last element // Then checks that Z(X) evaluated at the last element in the domain is 1 let (f, t, domain) = setup_correct_test(); let f_poly = f.to_polynomial(&domain); let t_poly = t.to_polynomial(&domain); let beta = Fr::from(5u8); let gamma = Fr::from(6u8); let (h_1, h_2) = compute_h1_h2(&f, &t); let h_1_poly = h_1.to_polynomial(&domain); let h_2_poly = h_2.to_polynomial(&domain); let z_evaluations = compute_accumulator_values(&f, &t, &h_1, &h_2, beta, gamma); let z_poly = Polynomial::from_coefficients_vec(domain.ifft(&z_evaluations)); let beta_one = Fr::one() + beta; let last_element = domain.elements().last().unwrap(); for (_, element) in domain.elements().enumerate() { // Evaluate polynomials // evaluate z(X) let z_x = z_poly.evaluate(&element); // evaluate z(Xg) let z_x_next = z_poly.evaluate(&(element * domain.group_gen)); // evaluate f(X) let f_x = f_poly.evaluate(&element); // evaluate t(X) let t_x = t_poly.evaluate(&element); // evaluate t(Xg) let t_x_next = t_poly.evaluate(&(element * domain.group_gen)); // evaluate h_1(X) let h_1_x = h_1_poly.evaluate(&element); // evaluate h_1(Xg) let h_1_x_next = h_1_poly.evaluate(&(element * domain.group_gen)); // evaluate h_2(X) let h_2_x = h_2_poly.evaluate(&element); // evaluate h_2(Xg) let h_2_x_next = h_2_poly.evaluate(&(element * domain.group_gen)); // LHS = (x - g^n)[z(x) * (1+b) * (gamma + f(x))] ( gamma(1 + beta) + t(x) + beta * t(Xg)) // x - g^n let a = element - last_element; // z(x) * (1+b) * (gamma + f(x)) let b = z_x * beta_one * (gamma + f_x); // gamma(1 + beta) + t(x) + beta * t(Xg) let c = (gamma * beta_one) + t_x + (beta * t_x_next); let lhs = a * b * c; // RHS = z(Xg)(x - g^n) [gamma *(1 + beta) + h_1(X) + beta*h_1(Xg)] [gamma * (1 + beta)] + h_2(X) + (beta * h_2(Xg)) // z(Xg)(x - g^n) let a = z_x_next * (element - last_element); // [gamma *(1 + beta) + h_1(X) + beta*h_1(Xg)] let b = (gamma * beta_one) + h_1_x + (beta * h_1_x_next); // [gamma * (1 + beta)] + h_2(X) + (beta * h_2(Xg)) let c = (gamma * beta_one) + h_2_x + (beta * h_2_x_next); let rhs = a * b * c; assert_eq!(lhs, rhs,); } // Now check that the last element is equal to 1 assert_eq!(z_poly.evaluate(&last_element), Fr::one()) } // This is just a helper function to setup tests with values that work fn setup_correct_test() -> (MultiSet, MultiSet, Radix2EvaluationDomain<Fr>) { // n is the amount of witness values // d is the amount of table values // We need d = n+1 let mut f = MultiSet::new(); f.push(Fr::from(1u8)); f.push(Fr::from(2u8)); f.push(Fr::from(3u8)); f.push(Fr::from(4u8)); f.push(Fr::from(5u8)); f.push(Fr::from(6u8)); f.push(Fr::from(7u8)); // Table of values let mut t = MultiSet::new(); t.push(Fr::from(1u8)); t.push(Fr::from(2u8)); t.push(Fr::from(3u8)); t.push(Fr::from(4u8)); t.push(Fr::from(5u8)); t.push(Fr::from(6u8)); t.push(Fr::from(7u8)); t.push(Fr::from(7u8)); assert_eq!(t.len(), f.len() + 1); assert_eq!(t.len().next_power_of_two(), t.len()); // The domain will be n+1 let domain: Radix2EvaluationDomain<Fr> = EvaluationDomain::new(f.len() + 1).unwrap(); (f, t, domain) } }
// q0008_string_to_integer_atoi struct Solution; impl Solution { pub fn my_atoi(str: String) -> i32 { let mut ret: i32 = 0; let mut neg = false; let s = str.as_bytes(); let mut index = 0; for &c in s { if c >= b'0' && c <= b'9' { break; } else if c == b'-' { neg = true; index += 1; break; } else if c == b'+' { neg = false; index += 1; break; } else if c == b' ' { index += 1; } else { return 0; } } for &c in &s[index..] { if c < b'0' || c > b'9' { break; } if neg { match ret.checked_mul(10) { Some(n) => ret = n, None => return i32::min_value(), } match ret.checked_sub((c - b'0') as i32) { Some(n) => ret = n, None => return i32::min_value(), } } else { match ret.checked_mul(10) { Some(n) => ret = n, None => return i32::max_value(), } match ret.checked_add((c - b'0') as i32) { Some(n) => ret = n, None => return i32::max_value(), } } } ret } } #[cfg(test)] mod tests { use super::Solution; #[test] fn it_works() { assert_eq!(Solution::my_atoi(String::from("42")), 42); } }
use super::candidate_base::*; use super::*; use crate::rand::generate_cand_id; use std::sync::atomic::{AtomicU16, AtomicU8}; use std::sync::Arc; /// The config required to create a new `CandidateHost`. #[derive(Default)] pub struct CandidateHostConfig { pub base_config: CandidateBaseConfig, pub tcp_type: TcpType, } impl CandidateHostConfig { /// Creates a new host candidate. pub async fn new_candidate_host( self, agent_internal: Option<Arc<Mutex<AgentInternal>>>, ) -> Result<CandidateBase, Error> { let mut candidate_id = self.base_config.candidate_id; if candidate_id.is_empty() { candidate_id = generate_cand_id(); } let c = CandidateBase { id: candidate_id, address: self.base_config.address.clone(), candidate_type: CandidateType::Host, component: AtomicU16::new(self.base_config.component), port: self.base_config.port, tcp_type: self.tcp_type, foundation_override: self.base_config.foundation, priority_override: self.base_config.priority, network: self.base_config.network, network_type: AtomicU8::new(NetworkType::Udp4 as u8), conn: self.base_config.conn, agent_internal, ..CandidateBase::default() }; if !self.base_config.address.ends_with(".local") { let ip = self.base_config.address.parse()?; c.set_ip(&ip).await?; }; Ok(c) } }
use std; import std::task::join; import std::task::spawn_joinable; fn main() { let x = spawn_joinable(bind m::child(10)); join(x); } mod m { fn child(i: int) { log i; } }
use lazy_static::lazy_static; use sensor_api::comms; use sensor_api::config::LinkConfig; use sensor_api::sensors::{RequestType, Sensor, SensorMessage, SensorType}; use sensor_api::SensorList; use std::collections::{HashMap, HashSet}; use std::net::SocketAddrV4; use std::net::TcpListener; use std::net::TcpStream; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::{Arc, Mutex}; use std::thread; lazy_static! { static ref CONF: LinkConfig = LinkConfig::from_toml("Nodelink.toml"); } struct SensorMemory { pub sensor_value: String, } impl SensorMemory { fn new(sensor_value: String) -> SensorMemory { SensorMemory { sensor_value } } } fn main() { CONF.show(); let sensor_list = initialize_mock_sensors(); discovery(CONF.listener().addr(), &sensor_list); let (tx, rx) = channel(); let handles = vec![ thread::spawn(move || mock_fixed_node_receiver(CONF.node().bind_addr(), tx, &sensor_list)), thread::spawn(move || mock_fixed_node_sender(CONF.listener().addr(), rx)), ]; for handle in handles { handle.join().unwrap(); } } fn discovery(addr: SocketAddrV4, sensor_list: &SensorList) { for s in &*sensor_list.lock().unwrap() { let stream = TcpStream::connect(addr).expect("PLEASE START SERVER BEFORE MOCK_NODE"); let discovery_message = s.discovery(); let discovery_message = serde_json::to_string(&discovery_message).unwrap(); comms::send_string(discovery_message, stream); } } fn mock_fixed_node_receiver(addr: SocketAddrV4, tx: Sender<String>, sensor_list: &SensorList) { let mut memory_map = HashMap::new(); for s in &*sensor_list.lock().unwrap() { let sensor = s.clone(); let mem = match sensor.sensor_type { SensorType::Thermometer | SensorType::Thermostat => SensorMemory::new("23".to_owned()), _ => SensorMemory::new("Off".to_owned()), }; memory_map.insert(sensor, mem); } let listener = TcpListener::bind(addr).unwrap(); for stream in listener.incoming() { let data = comms::read_string(stream.unwrap()); println!("RECEIVED: {:?}", &data); let sensor_reponse = mock_mobile_node(data, &mut memory_map); tx.send(sensor_reponse).unwrap(); } } fn mock_fixed_node_sender(addr: SocketAddrV4, rx: Receiver<String>) { for data in rx { println!("SENDING: {:?}", &data); let stream = TcpStream::connect(addr).unwrap(); comms::send_string(data, stream); } } fn mock_mobile_node(data: String, mbed_memory: &mut HashMap<Sensor, SensorMemory>) -> String { let mut message: SensorMessage = serde_json::from_str(&data).unwrap(); match message.request_type { RequestType::Get => { let sensor_memory = mbed_memory .get(&message.sensor()) .expect("Sensor does not exist!"); message.replace_payload(sensor_memory.sensor_value.clone()); } RequestType::Set => { let sensor_memory = mbed_memory .get_mut(&message.sensor()) .expect("Sensor does not exist!"); sensor_memory.sensor_value = message.extract_payload(); println!("New value: {} has been set!", sensor_memory.sensor_value) } _ => unreachable!(), } message.change_request_type(RequestType::GetResponse); serde_json::to_string(&message).unwrap() } fn initialize_mock_sensors() -> SensorList { let sensors = vec![ Sensor::new(1, SensorType::Light), Sensor::new(2, SensorType::Lock), Sensor::new(3, SensorType::Thermometer), Sensor::new(4, SensorType::Thermometer), Sensor::new(5, SensorType::SmartSwitch), Sensor::new(6, SensorType::Thermostat), Sensor::new(7, SensorType::MusicPlayer), Sensor::new(8, SensorType::Store), Sensor::new(9, SensorType::Thermometer), ]; let sensor_list = Arc::new(Mutex::new(HashSet::new())); { let mut sensor_list = sensor_list.lock().unwrap(); for sensor in sensors { sensor_list.insert(sensor); } //println!("{}", serde_json::to_string(&*sensor_list).unwrap()); } sensor_list }
use std::mem; use std::io; use libc; use super::*; #[cfg(target_os = "linux")] #[derive(Debug)] pub struct TapInterfaceDesc { lower: libc::c_int, ifreq: ifreq } impl TapInterfaceDesc { pub fn new(name: &str) -> io::Result<TapInterfaceDesc> { let lower = unsafe { let lower = libc::open("/dev/net/tun".as_ptr() as *const libc::c_char, libc::O_RDWR); if lower == -1 { return Err(io::Error::last_os_error()) } lower }; Ok(TapInterfaceDesc { lower: lower, ifreq: ifreq_for(name) }) } pub fn attach_interface(&mut self) -> io::Result<()> { self.ifreq.ifr_data = imp::IFF_TAP | imp::IFF_NO_PI; ifreq_ioctl(self.lower, &mut self.ifreq, imp::TUNSETIFF).map(|_| ()) } fn wait(&mut self, ms: u32) -> io::Result<bool> { unsafe { let mut readfds = mem::uninitialized::<libc::fd_set>(); libc::FD_ZERO(&mut readfds); libc::FD_SET(self.lower, &mut readfds); let mut writefds = mem::uninitialized::<libc::fd_set>(); libc::FD_ZERO(&mut writefds); let mut exceptfds = mem::uninitialized::<libc::fd_set>(); libc::FD_ZERO(&mut exceptfds); let mut timeout = libc::timeval { tv_sec: 0, tv_usec: (ms * 1_000) as i64 }; let res = libc::select(self.lower + 1, &mut readfds, &mut writefds, &mut exceptfds, &mut timeout); if res == -1 { return Err(io::Error::last_os_error()) } Ok(res == 0) } } pub fn recv(&mut self, buffer: &mut [u8]) -> io::Result<usize> { // FIXME: here we don't wait forever, in case we need to send several packets in a row // ideally this would be implemented by going full nonblocking if self.wait(100)? { return Err(io::ErrorKind::TimedOut)? } unsafe { let len = libc::read(self.lower, buffer.as_mut_ptr() as *mut libc::c_void, buffer.len()); if len == -1 { return Err(io::Error::last_os_error()) } Ok(len as usize) } } pub fn send(&mut self, buffer: &[u8]) -> io::Result<usize> { self.wait(100)?; unsafe { let len = libc::write(self.lower, buffer.as_ptr() as *const libc::c_void, buffer.len()); if len == -1 { Err(io::Error::last_os_error()).unwrap() } Ok(len as usize) } } } impl Drop for TapInterfaceDesc { fn drop(&mut self) { unsafe { libc::close(self.lower); } } }
use std::collections::HashSet; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; fn main() -> Result<(), std::io::Error> { let input_path = Path::new("input.txt"); let reader = BufReader::new(File::open(&input_path)?); let input: Vec<usize> = reader .lines() .map(|line| line.unwrap().parse()) .flatten() .collect(); let p1 = part_01(&input); println!("{}", p1); let p2 = part_02(&input, p1); println!("{:?}", p2); Ok(()) } fn part_01(input: &Vec<usize>) -> usize { *input .as_slice() .windows(26) .find_map(|window| { let set = window[..25].into_iter().collect::<HashSet<&usize>>(); for w in window[..25].into_iter() { match window.last().unwrap().checked_sub(*w) { Some(num) => { if set.contains(&(num)) && num != *w { return None; } } _ => (), } } Some(window.last().unwrap()) }) .unwrap() } fn part_02(input: &Vec<usize>, target: usize) -> usize { for i in 0..input.len() - 1 { for x in i + 1..(input.len() - 1) { let slice = &input[i..x]; let sum: usize = slice.clone().iter().sum::<usize>(); if sum == target { return slice.clone().iter().min().unwrap() + slice.clone().iter().max().cloned().unwrap(); } } } 0 }
use log::{debug, info, trace}; use std::fs; use std::io::{stdin, BufRead}; use std::process; use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Serialize}; use crate::{ conf::GoogleCalendarGlobalConf, error::Result, google::api::{confirm_code, refresh_token}, }; #[derive(Serialize, Deserialize)] struct OAuthToken { access_token: String, expires_at: DateTime<Utc>, refresh_token: String, } pub async fn access_token(conf: &GoogleCalendarGlobalConf) -> Result<String> { let token_path = conf.token_dir.clone().join(&conf.token_filename); debug!("Google OAuth token path: {}", token_path.display()); if let Ok(json) = fs::read_to_string(&token_path) { let mut auth: OAuthToken = serde_json::from_str(&json)?; if auth.expires_at > Utc::now() { Ok(auth.access_token) } else { info!("Google OAuth token expired. Refreshing."); let res = refresh_token(&auth.refresh_token, conf).await?; auth.access_token = res.access_token; auth.expires_at = Utc::now() + Duration::seconds(res.expires_in); trace!("Saving Google OAuth token."); fs::write(token_path, serde_json::to_string(&auth)?)?; Ok(auth.access_token) } } else { info!( "Please visit: https://accounts.google.com/o/oauth2/v2/auth\ ?client_id={}&redirect_uri={}&scope=https://www.googleapis.com/auth/calendar\ &response_type=code&access_type=offline", conf.client_id, conf.redirect_uri, ); info!("Follow the instructions and paste the code here (press q to quit):"); for line in stdin().lock().lines() { let line = line?; let code = line.trim(); if code.is_empty() { continue; } else if code == "q" { process::exit(1); } info!("Confirming code."); let res = confirm_code(code, conf).await?; let auth = OAuthToken { access_token: res.access_token, expires_at: Utc::now() + Duration::seconds(res.expires_in), refresh_token: res.refresh_token, }; trace!("Saving Google OAuth token."); fs::write(token_path, serde_json::to_string(&auth)?)?; return Ok(auth.access_token); } process::exit(1); } }
use super::{Order, Action, Trader}; use crate::economy::Monetary; use crate::indicators::{Indicator, Value, StretchedRSI, SMA, MACDHistogram, MACD}; pub struct MACDTrader<const FRACTION: Monetary> { previous_macdh: Monetary, } impl<const FRACTION: Monetary> Trader for MACDTrader<FRACTION> { type Indicators = (Value, MACDHistogram<720, 1560, 540>, MACDHistogram<5760, 12480, 4320>); fn initialize(base: &str, quote: &str) -> MACDTrader<FRACTION> { MACDTrader { previous_macdh: 0.0 } } fn evaluate(&mut self, (value, macd, lmacd): <Self::Indicators as Indicator>::Output) -> Option<Order> { if let (Some((macd, macdh)), Some((lmacd, lmacdh))) = (macd, lmacd) { let action = if self.previous_macdh < 0.0 && macdh >= 0.0 && macd < 0.0 && lmacdh >= 0.0 && lmacd < 0.0 { Some(Order::Limit(Action::Buy, FRACTION, value)) } else if self.previous_macdh > 0.0 && macdh <= 0.0 && macd > 0.0 && lmacdh <= 0.0 && lmacd > 0.0 { Some(Order::Limit(Action::Sell, FRACTION, value)) } else { None }; self.previous_macdh = macdh; action } else { None } } }
use actix_web::{HttpResponse, Responder}; use serde::Serialize; use common::result::Result; use crate::error::PublicError; pub fn map<T: Serialize>(res: Result<T>) -> impl Responder { res.map(|res| HttpResponse::Ok().json(res)) .map_err(PublicError::from) }
use crate::log_core::LogExtend; #[macro_use] mod log; pub use self::log::*; ///The constructor of empty structures pub trait LogUnionConst { #[inline] fn union<'a, B: LogExtend<'a>>(self, b: B) -> LogUnion<'a, Self, B> where Self: Sized + LogExtend<'a> { LogUnion::new(self, b) } } impl<'a, T: LogExtend<'a> + Sized> LogUnionConst for T { } impl<'a, A: LogExtend<'a>, B: LogExtend<'a>> From<(A, B)> for LogUnion<'a, A, B> { #[inline(always)] fn from((a, b): (A, B)) -> Self { a.union(b) } }
use serde::Deserialize; pub struct DataFrame{ pub time: Vec<String>, pub prediction: Vec<i8>, pub price: Vec<f64> } impl DataFrame{ pub fn new() -> DataFrame{ DataFrame{ time: Vec::new(), prediction: Vec::new(), price: Vec::new(), } } pub fn push(&mut self, row: &csv::StringRecord){ self.time.push(row[0].to_string()); self.prediction.push(row[1].to_string().parse::<i8>().unwrap()); self.price.push(row[2].to_string().parse::<f64>().unwrap()); } pub fn load_csv(path: &str) -> DataFrame { let file = std::fs::File::open(path).unwrap(); let mut file_reader = csv::ReaderBuilder::new() .from_reader(file); let mut dataframe = DataFrame::new(); for row in file_reader.records().into_iter() { let record= row.unwrap(); dataframe.push(&record); } return dataframe; } }
use std::collections::HashMap; use std::fs; use std::str::FromStr; use std::sync::Arc; use bevy::prelude::*; use bevy::reflect::{TypeUuidDynamic, Uuid}; use bevy::render::texture::{Extent3d, ImageType}; use dashmap::DashMap; pub struct BoxMeshHandle(pub Handle<Mesh>); #[derive(Debug, Serialize, Deserialize, Clone, Copy)] pub struct PbrConfig { pub uuid: Uuid, pub id: u64, pub unlit: bool, pub color: [u8; 3], pub emissive: [u8; 3], pub metalic: u8, pub roughness: u8, pub reflectance: u8, // pub clearcoat: u8, // pub clearcoatroughness: u8, // pub ansiotropy: u8, } impl Default for PbrConfig { fn default() -> Self { Self { id: 0, uuid: Uuid::new_v4(), unlit: false, color: [0u8; 3], emissive: [0u8; 3], metalic: 0u8, reflectance: 0u8, roughness: 0u8, } } } impl PbrConfig { pub fn color(&self) -> Color { return Color::rgb_u8(self.color[0], self.color[1], self.color[2]); } pub fn emissive(&self) -> Color { return Color::rgb_u8(self.emissive[0], self.emissive[1], self.emissive[2]); } pub fn metalic(&self) -> f32 { return (self.metalic & 31) as f32 / 32.0f32; } pub fn roughness(&self) -> f32 { return (self.roughness & 31) as f32 / 32.0f32; } pub fn reflectance(&self) -> f32 { return (self.reflectance & 31) as f32 / 32.0f32; } // pub fn clearcoat(&self) -> f32 { // return (self.clearcoat & 31) as f32 / 32.0f32; // } // pub fn clearcoatroughness(&self) -> f32 { // return (self.clearcoatroughness & 31) as f32 / 32.0f32; // } // pub fn ansiotropy(&self) -> f32 { // return (self.ansiotropy & 31) as f32 / 32.0f32; // } pub fn pbr(&self, normal: Option<Handle<Texture>>) -> StandardMaterial { StandardMaterial { base_color: self.color(), emissive: self.emissive(), double_sided: false, metallic: self.metalic(), reflectance: self.reflectance(), roughness: self.roughness(), unlit: self.unlit, normal_map: normal, ..Default::default() } } } impl TypeUuidDynamic for PbrConfig { fn type_uuid(&self) -> Uuid { Uuid::from_str("17bd4300-be62-4fbe-b32f-40e1a0294421").unwrap() } fn type_name(&self) -> &'static str { "PbrConfig" } } // impl TypeUuid for PbrConfig { // const TYPE_UUID: Uuid = Uuid::from_str("17bd4300-be62-4fbe-b32f-40e1a0294421").unwrap(); // } pub struct MaterialsMapping { pub map: Arc<DashMap<u64, Handle<StandardMaterial>>> } impl Default for MaterialsMapping { fn default() -> Self { Self { map: Arc::new(DashMap::new()) } } } pub fn load_materials( mut commands: Commands, mut textures: ResMut<Assets<Texture>>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { let box_mesh_handle = meshes.add(Mesh::from(bevy::prelude::shape::Cube { size: 1.0 })); commands.insert_resource(BoxMeshHandle(box_mesh_handle)); let cwd = std::env::current_dir().unwrap().display().to_string(); let path = format!("{0}/assets/materials/base.toml", cwd); let contents = fs::read_to_string(path) .expect("Something went wrong reading the file"); let dict: HashMap<String, PbrConfig> = toml::from_str(&contents).unwrap(); let map = DashMap::new(); // let mut pixel: Vec<u8> = Vec::new(); // for x in 0..32 { // for y in 0..32 { // pixel.push(crate::noise::noise_2d(x as u64, y as u64, 54u64) as u8); // } // } // let texture = Texture::new_fill(Extent3d::new(32, 32, 1), bevy::render::texture::TextureDimension::D2, &pixel, bevy::render::texture::TextureFormat::R8Uint); // let texture_handle = Some(textures.add(texture)); for (_k, v) in dict { map.insert(v.id, materials.add(v.pbr(None))); } commands.insert_resource(MaterialsMapping { map: Arc::new(map) }); }
#![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))] use support::*; use std::fmt; use std::net::IpAddr; use std::sync::{Arc, Mutex}; use conduit_proxy_controller_grpc as pb; use self::bytes::BufMut; use self::futures::sync::mpsc; use self::prost::Message; pub fn new() -> Controller { Controller::new() } struct Destination(Box<Fn() -> Option<pb::destination::Update> + Send>); #[derive(Debug)] pub struct Controller { destinations: Vec<(String, Destination)>, reports: Option<mpsc::UnboundedSender<pb::telemetry::ReportRequest>>, } #[derive(Debug)] pub struct Listening { pub addr: SocketAddr, shutdown: Shutdown, } impl Controller { pub fn new() -> Self { Controller { destinations: Vec::new(), reports: None, } } pub fn destination(mut self, dest: &str, addr: SocketAddr) -> Self { self.destination_fn(dest, move || Some(destination_update(addr))) } pub fn destination_fn<F>(mut self, dest: &str, f: F) -> Self where F: Fn() -> Option<pb::destination::Update> + Send + 'static, { self.destinations .push((dest.into(), Destination(Box::new(f)))); self } pub fn destination_close(mut self, dest: &str) -> Self { self.destination_fn(dest, || None) } pub fn reports(&mut self) -> mpsc::UnboundedReceiver<pb::telemetry::ReportRequest> { let (tx, rx) = mpsc::unbounded(); self.reports = Some(tx); rx } pub fn run(self) -> Listening { run(self) } } type Response = self::http::Response<GrpcBody>; type Destinations = Arc<Mutex<Vec<(String, Destination)>>>; const DESTINATION_GET: &str = "/conduit.proxy.destination.Destination/Get"; const TELEMETRY_REPORT: &str = "/conduit.proxy.telemetry.Telemetry/Report"; impl fmt::Debug for Destination { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Destination") } } #[derive(Debug)] struct Svc { destinations: Destinations, reports: Option<mpsc::UnboundedSender<pb::telemetry::ReportRequest>>, } impl Svc { fn route( &self, path: &str, body: RecvBodyStream, ) -> Box<Future<Item = Response, Error = h2::Error>> { let mut rsp = http::Response::builder(); rsp.version(http::Version::HTTP_2); match path { DESTINATION_GET => { let destinations = self.destinations.clone(); Box::new(body.concat2().and_then(move |_bytes| { let update = { let mut vec = destinations.lock().unwrap(); //TODO: decode `_bytes` and compare with `.0` if !vec.is_empty() { let Destination(f) = vec.remove(0).1; f() } else { None } }.unwrap_or_default(); let len = update.encoded_len(); let mut buf = BytesMut::with_capacity(len + 5); buf.put(0u8); buf.put_u32::<BigEndian>(len as u32); update.encode(&mut buf).unwrap(); let body = GrpcBody::new(buf.freeze()); let rsp = rsp.body(body).unwrap(); Ok(rsp) })) } TELEMETRY_REPORT => { let mut reports = self.reports.clone(); Box::new(body.concat2().and_then(move |mut bytes| { if let Some(ref mut report) = reports { let req = Message::decode(bytes.split_off(5)).unwrap(); let _ = report.unbounded_send(req); } let body = GrpcBody::new([0u8; 5][..].into()); let rsp = rsp.body(body).unwrap(); Ok(rsp) })) } unknown => { println!("unknown route: {:?}", unknown); let body = GrpcBody::unimplemented(); let rsp = rsp.body(body).unwrap(); Box::new(future::ok(rsp)) } } } } impl Service for Svc { type Request = Request<RecvBody>; type Response = Response; type Error = h2::Error; type Future = Box<Future<Item = Response, Error = h2::Error>>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Ok(Async::Ready(())) } fn call(&mut self, req: Request<RecvBody>) -> Self::Future { let (head, body) = req.into_parts(); self.route(head.uri.path(), RecvBodyStream(body)) } } struct GrpcBody { message: Bytes, status: &'static str, } impl GrpcBody { fn new(body: Bytes) -> Self { GrpcBody { message: body, status: "0", } } fn unimplemented() -> Self { GrpcBody { message: Bytes::new(), status: "12", } } } impl Body for GrpcBody { type Data = Bytes; fn poll_data(&mut self) -> Poll<Option<Bytes>, self::h2::Error> { let data = self.message.split_off(0); let data = if data.is_empty() { None } else { Some(data) }; Ok(Async::Ready(data)) } fn poll_trailers(&mut self) -> Poll<Option<HeaderMap>, self::h2::Error> { let mut map = HeaderMap::new(); map.insert("grpc-status", HeaderValue::from_static(self.status)); Ok(Async::Ready(Some(map))) } } #[derive(Debug)] struct NewSvc { destinations: Destinations, reports: Option<mpsc::UnboundedSender<pb::telemetry::ReportRequest>>, } impl NewService for NewSvc { type Request = Request<RecvBody>; type Response = Response; type Error = h2::Error; type InitError = ::std::io::Error; type Service = Svc; type Future = future::FutureResult<Svc, Self::InitError>; fn new_service(&self) -> Self::Future { future::ok(Svc { destinations: self.destinations.clone(), reports: self.reports.clone(), }) } } fn run(controller: Controller) -> Listening { let (tx, rx) = shutdown_signal(); let (addr_tx, addr_rx) = oneshot::channel(); ::std::thread::Builder::new() .name("support controller".into()) .spawn(move || { let mut core = Core::new().unwrap(); let reactor = core.handle(); let factory = NewSvc { destinations: Arc::new(Mutex::new(controller.destinations)), reports: controller.reports, }; let h2 = tower_h2::Server::new(factory, Default::default(), reactor.clone()); let addr = ([127, 0, 0, 1], 0).into(); let bind = TcpListener::bind(&addr, &reactor).expect("bind"); let _ = addr_tx.send(bind.local_addr().expect("addr")); let serve = bind.incoming() .fold((h2, reactor), |(h2, reactor), (sock, _)| { if let Err(e) = sock.set_nodelay(true) { return Err(e); } let serve = h2.serve(sock); reactor.spawn(serve.map_err(|e| println!("controller error: {:?}", e))); Ok((h2, reactor)) }); core.handle().spawn( serve .map(|_| ()) .map_err(|e| println!("controller error: {}", e)), ); core.run(rx).unwrap(); }) .unwrap(); let addr = addr_rx.wait().expect("addr"); Listening { addr, shutdown: tx, } } pub fn destination_update(addr: SocketAddr) -> pb::destination::Update { pb::destination::Update { update: Some(pb::destination::update::Update::Add( pb::destination::WeightedAddrSet { addrs: vec![ pb::destination::WeightedAddr { addr: Some(pb::common::TcpAddress { ip: Some(ip_conv(addr.ip())), port: u32::from(addr.port()), }), weight: 0, }, ], }, )), } } fn ip_conv(ip: IpAddr) -> pb::common::IpAddress { match ip { IpAddr::V4(v4) => pb::common::IpAddress { ip: Some(pb::common::ip_address::Ip::Ipv4(v4.into())), }, IpAddr::V6(v6) => { let (first, last) = octets_to_u64s(v6.octets()); pb::common::IpAddress { ip: Some(pb::common::ip_address::Ip::Ipv6(pb::common::IPv6 { first, last, })), } } } } fn octets_to_u64s(octets: [u8; 16]) -> (u64, u64) { let first = (u64::from(octets[0]) << 56) + (u64::from(octets[1]) << 48) + (u64::from(octets[2]) << 40) + (u64::from(octets[3]) << 32) + (u64::from(octets[4]) << 24) + (u64::from(octets[5]) << 16) + (u64::from(octets[6]) << 8) + u64::from(octets[7]); let last = (u64::from(octets[8]) << 56) + (u64::from(octets[9]) << 48) + (u64::from(octets[10]) << 40) + (u64::from(octets[11]) << 32) + (u64::from(octets[12]) << 24) + (u64::from(octets[13]) << 16) + (u64::from(octets[14]) << 8) + u64::from(octets[15]); (first, last) }
#![no_std] #![no_main] use core::cell::RefCell; // pick a panicking behavior use panic_halt as _; // you can put a breakpoint on `rust_begin_unwind` to catch panics // use panic_abort as _; // requires nightly // use panic_itm as _; // logs messages over ITM; requires ITM support // use panic_semihosting as _; // logs messages to the host stderr; requires a debugger use cortex_m::asm; use cortex_m::interrupt::Mutex; use cortex_m_rt::entry; // use cortex_m_semihosting::hprintln; use tm4c123x; use tm4c123x::Interrupt; use tm4c123x::interrupt; const OFF: u32 = 0x00; // all LEDs off const ON: u32 = 0x02; // red LED on static GPIO_MUTEX: Mutex<RefCell<Option<tm4c123x::GPIO_PORTF>>> = Mutex::new(RefCell::new(None)); fn setupGPIO(){ let cp = cortex_m::Peripherals::take().unwrap(); let p = tm4c123x::Peripherals::take().unwrap(); //setup(); p.SYSCTL.rcgcgpio.write(|w| unsafe{w.bits(0x01 << 5)}); let sysctl = p.SYSCTL; // let test = &sysctl.rcgc2; //sysctl.rcgcgpio.write(|w| unsafe { w.bits(0x01 << 5) }); // clock for portf //sysctl.rcgcgpio.write(|w| w.r5().set_bit()); // clock for portf without unsafe //sysctl.rcgcgpio.modify(|r, w| unsafe{w.bits(r.bits() | (0x01 << 5))}); let portf = p.GPIO_PORTF; // OWNERSHIP TRANSFER! //portf.lock.write(|w| unsafe{w.bits(0x4C4F434B)}); // unlock portf.lock.write(|w| w.lock().unlocked()); // unlock woithout unsafe portf.cr.write(|w| unsafe{w.bits(0x1F)}); portf.dir.write(|w| unsafe{w.bits(0x0E)}); portf.pur.write(|w| unsafe{w.bits(0x11)}); portf.den.write(|w| unsafe{w.bits(0x1F)}); // portf.data.write(|w| unsafe{w.bits(ON)}); // interrupt setup portf.is.write(|w| unsafe {w.bits(0x00)}); portf.ibe.write(|w| unsafe{w.bits(0x00)}); portf.iev.write(|w| unsafe{w.bits(0x00)}); portf.im.write(|w| unsafe{w.bits(0x11)}); // interrupt mask -> enable for pf0 and pf4 // unsafe{cp.NVIC.iser[0].write(1 << 30)}; // let mut nvic = cp.NVIC; // nvic.enable(Interrupt::GPIOF); //deprecated unsafe {cortex_m::peripheral::NVIC::unmask(Interrupt::GPIOF)}; // new version (is unsafe) // move the GPIO_PORTF object to the mutex (mutex takes ownership) cortex_m::interrupt::free(|cs| GPIO_MUTEX.borrow(cs).replace(Some(portf))); } #[entry] fn main() -> ! { setupGPIO(); loop { asm::nop(); } } #[interrupt] fn GPIOF() { static mut led_state: bool = false; *led_state = !*led_state; let value = if *led_state {ON} else {OFF}; asm::nop(); cortex_m::interrupt::free(|cs|{ let mutex_res_portf = GPIO_MUTEX.borrow(cs).borrow(); let portf = mutex_res_portf.as_ref().unwrap(); portf.data.write(|w| unsafe{w.bits(value)}); portf.icr.write(|w| unsafe{w.bits(0x11)}); }); }
// use lib.rs mod lib; use lib::RunCCP; use slog; use clap; use portus; /* Receive arguments: --ipc: netlink/unix, default netlink --time_slot_interval: (ms), fefault 10000ms Return: (rccp: RunCCP{log, time_slot_interval}, ipc: String) */ fn make_args(log: slog::Logger) -> Result<(RunCCP, String), String> { let time_slot_interval_default = format!("{}", lib::TIME_SLOT_INTERVAL_MSEC); let matches = clap::App::new("Run CCP Program") .version("0.2.2") .author("xyzhao <xyzhao@cs.hku.hk>") .about("Implementation of MLCC on CCP") .arg(clap::Arg::with_name("ipc") .long("ipc") .help("Sets the type of ipc to use: (netlink|unix)") .default_value("netlink") .validator(portus::algs::ipc_valid)) .arg(clap::Arg::with_name("time_slot_interval") .long("time_slot_interval") .help("Set the time slot value in (ms)") .default_value(&time_slot_interval_default)) .get_matches(); let time_slot_interval_arg = time::Duration::milliseconds( i64::from_str_radix(matches.value_of("time_slot_interval").unwrap(), 10) // 10进制 .map_err(|e| format!("{:?}", e)) .and_then(|time_slot_interval_arg| { if time_slot_interval_arg <= 0 { Err(format!( "time_slot_interval must be positive: {}", time_slot_interval_arg )) } else { Ok(time_slot_interval_arg) } })?, ); let time_slot_interval_arg = u32::from_str_radix(matches.value_of("time_slot_interval").unwrap(), 10); slog::info!(log, "Successfully receive arguments for RunCCP."); Ok(( RunCCP { logger: Some(log), time_slot_interval: time_slot_interval_arg.unwrap(), }, String::from(matches.value_of("ipc").unwrap()), )) } /* Main function: init an RunCCP instance with args and start. */ fn main(){ let log = portus::algs::make_logger(); let (rccp, ipc) = make_args(log.clone()) .map_err(|e| slog::warn!(log, "bad argument"; "err" => ?e)) .unwrap(); slog::info!(log, "Configured RunCCP"; "ipc" => ipc.clone(), "time_slot_interval(ms)" => ?rccp.time_slot_interval, ); portus::start!(ipc.as_str(), Some(log), rccp).expect("Fail to launch portus::start."); }
use super::aggregation::Aggregator; #[derive(Debug, PartialEq, Eq)] pub struct Statement { pub aggregators: Vec<Aggregator>, pub group_by: u64, pub limit: usize, pub from: i64, }
async fn say_hi() { println!("Hello world!"); } #[runtime::main] async fn main() { say_hi().await; }
use super::*; pub(super) fn struct_def(p: &mut Parser) { assert!(p.at(STRUCT_KW)); p.bump(); name(p); type_params::type_param_list(p); match p.current() { WHERE_KW => { type_params::where_clause(p); match p.current() { SEMI => { p.bump(); return; } L_CURLY => named_fields(p), _ => { //TODO: special case `(` error message p.error("expected `;` or `{`"); return; } } } SEMI => { p.bump(); return; } L_CURLY => named_fields(p), L_PAREN => { pos_fields(p); p.expect(SEMI); } _ => { p.error("expected `;`, `{`, or `(`"); return; } } } pub(super) fn enum_def(p: &mut Parser) { assert!(p.at(ENUM_KW)); p.bump(); name(p); type_params::type_param_list(p); type_params::where_clause(p); if p.expect(L_CURLY) { while !p.at(EOF) && !p.at(R_CURLY) { let var = p.start(); attributes::outer_attributes(p); if p.at(IDENT) { name(p); match p.current() { L_CURLY => named_fields(p), L_PAREN => pos_fields(p), EQ => { p.bump(); expressions::expr(p); } _ => (), } var.complete(p, ENUM_VARIANT); } else { var.abandon(p); p.err_and_bump("expected enum variant"); } if !p.at(R_CURLY) { p.expect(COMMA); } } p.expect(R_CURLY); } } fn named_fields(p: &mut Parser) { assert!(p.at(L_CURLY)); p.bump(); while !p.at(R_CURLY) && !p.at(EOF) { named_field(p); if !p.at(R_CURLY) { p.expect(COMMA); } } p.expect(R_CURLY); fn named_field(p: &mut Parser) { let m = p.start(); // test field_attrs // struct S { // #[serde(with = "url_serde")] // pub uri: Uri, // } attributes::outer_attributes(p); visibility(p); if p.at(IDENT) { name(p); p.expect(COLON); types::type_(p); m.complete(p, NAMED_FIELD); } else { m.abandon(p); p.err_and_bump("expected field declaration"); } } } fn pos_fields(p: &mut Parser) { if !p.expect(L_PAREN) { return; } while !p.at(R_PAREN) && !p.at(EOF) { let pos_field = p.start(); visibility(p); types::type_(p); pos_field.complete(p, POS_FIELD); if !p.at(R_PAREN) { p.expect(COMMA); } } p.expect(R_PAREN); }
#[doc = "Reader of register MDMA_C16CR"] pub type R = crate::R<u32, super::MDMA_C16CR>; #[doc = "Writer for register MDMA_C16CR"] pub type W = crate::W<u32, super::MDMA_C16CR>; #[doc = "Register MDMA_C16CR `reset()`'s with value 0"] impl crate::ResetValue for super::MDMA_C16CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EN_A { #[doc = "0: Channel disabled"] B_0X0 = 0, #[doc = "1: Channel enabled"] B_0X1 = 1, } impl From<EN_A> for bool { #[inline(always)] fn from(variant: EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EN`"] pub type EN_R = crate::R<bool, EN_A>; impl EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EN_A { match self.bits { false => EN_A::B_0X0, true => EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == EN_A::B_0X1 } } #[doc = "Write proxy for field `EN`"] pub struct EN_W<'a> { w: &'a mut W, } impl<'a> EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Channel disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(EN_A::B_0X0) } #[doc = "Channel enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(EN_A::B_0X1) } #[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 = "TEIE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TEIE_A { #[doc = "0: TE interrupt disabled"] B_0X0 = 0, #[doc = "1: TE interrupt enabled"] B_0X1 = 1, } impl From<TEIE_A> for bool { #[inline(always)] fn from(variant: TEIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TEIE`"] pub type TEIE_R = crate::R<bool, TEIE_A>; impl TEIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TEIE_A { match self.bits { false => TEIE_A::B_0X0, true => TEIE_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TEIE_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TEIE_A::B_0X1 } } #[doc = "Write proxy for field `TEIE`"] pub struct TEIE_W<'a> { w: &'a mut W, } impl<'a> TEIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TEIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TE interrupt disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TEIE_A::B_0X0) } #[doc = "TE interrupt enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TEIE_A::B_0X1) } #[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 = "CTCIE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CTCIE_A { #[doc = "0: TC interrupt disabled"] B_0X0 = 0, #[doc = "1: TC interrupt enabled"] B_0X1 = 1, } impl From<CTCIE_A> for bool { #[inline(always)] fn from(variant: CTCIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CTCIE`"] pub type CTCIE_R = crate::R<bool, CTCIE_A>; impl CTCIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CTCIE_A { match self.bits { false => CTCIE_A::B_0X0, true => CTCIE_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == CTCIE_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == CTCIE_A::B_0X1 } } #[doc = "Write proxy for field `CTCIE`"] pub struct CTCIE_W<'a> { w: &'a mut W, } impl<'a> CTCIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CTCIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TC interrupt disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(CTCIE_A::B_0X0) } #[doc = "TC interrupt enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(CTCIE_A::B_0X1) } #[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 = "BRTIE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BRTIE_A { #[doc = "0: BT interrupt disabled"] B_0X0 = 0, #[doc = "1: BT interrupt enabled"] B_0X1 = 1, } impl From<BRTIE_A> for bool { #[inline(always)] fn from(variant: BRTIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `BRTIE`"] pub type BRTIE_R = crate::R<bool, BRTIE_A>; impl BRTIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BRTIE_A { match self.bits { false => BRTIE_A::B_0X0, true => BRTIE_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == BRTIE_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == BRTIE_A::B_0X1 } } #[doc = "Write proxy for field `BRTIE`"] pub struct BRTIE_W<'a> { w: &'a mut W, } impl<'a> BRTIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BRTIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "BT interrupt disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(BRTIE_A::B_0X0) } #[doc = "BT interrupt enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(BRTIE_A::B_0X1) } #[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 = "BTIE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BTIE_A { #[doc = "0: BT complete interrupt\r\n disabled"] B_0X0 = 0, #[doc = "1: BT complete interrupt\r\n enabled"] B_0X1 = 1, } impl From<BTIE_A> for bool { #[inline(always)] fn from(variant: BTIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `BTIE`"] pub type BTIE_R = crate::R<bool, BTIE_A>; impl BTIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BTIE_A { match self.bits { false => BTIE_A::B_0X0, true => BTIE_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == BTIE_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == BTIE_A::B_0X1 } } #[doc = "Write proxy for field `BTIE`"] pub struct BTIE_W<'a> { w: &'a mut W, } impl<'a> BTIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BTIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "BT complete interrupt disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(BTIE_A::B_0X0) } #[doc = "BT complete interrupt enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(BTIE_A::B_0X1) } #[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 = "TCIE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TCIE_A { #[doc = "0: TC interrupt disabled"] B_0X0 = 0, #[doc = "1: TC interrupt enabled"] B_0X1 = 1, } impl From<TCIE_A> for bool { #[inline(always)] fn from(variant: TCIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TCIE`"] pub type TCIE_R = crate::R<bool, TCIE_A>; impl TCIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TCIE_A { match self.bits { false => TCIE_A::B_0X0, true => TCIE_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TCIE_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TCIE_A::B_0X1 } } #[doc = "Write proxy for field `TCIE`"] pub struct TCIE_W<'a> { w: &'a mut W, } impl<'a> TCIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TCIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TC interrupt disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TCIE_A::B_0X0) } #[doc = "TC interrupt enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TCIE_A::B_0X1) } #[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 = "PL\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PL_A { #[doc = "0: Low"] B_0X0 = 0, #[doc = "1: Medium"] B_0X1 = 1, #[doc = "2: High"] B_0X2 = 2, #[doc = "3: Very high"] B_0X3 = 3, } impl From<PL_A> for u8 { #[inline(always)] fn from(variant: PL_A) -> Self { variant as _ } } #[doc = "Reader of field `PL`"] pub type PL_R = crate::R<u8, PL_A>; impl PL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PL_A { match self.bits { 0 => PL_A::B_0X0, 1 => PL_A::B_0X1, 2 => PL_A::B_0X2, 3 => PL_A::B_0X3, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == PL_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == PL_A::B_0X1 } #[doc = "Checks if the value of the field is `B_0X2`"] #[inline(always)] pub fn is_b_0x2(&self) -> bool { *self == PL_A::B_0X2 } #[doc = "Checks if the value of the field is `B_0X3`"] #[inline(always)] pub fn is_b_0x3(&self) -> bool { *self == PL_A::B_0X3 } } #[doc = "Write proxy for field `PL`"] pub struct PL_W<'a> { w: &'a mut W, } impl<'a> PL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Low"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(PL_A::B_0X0) } #[doc = "Medium"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(PL_A::B_0X1) } #[doc = "High"] #[inline(always)] pub fn b_0x2(self) -> &'a mut W { self.variant(PL_A::B_0X2) } #[doc = "Very high"] #[inline(always)] pub fn b_0x3(self) -> &'a mut W { self.variant(PL_A::B_0X3) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } #[doc = "BEX\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BEX_A { #[doc = "0: Little endianess preserved for\r\n bytes"] B_0X0 = 0, #[doc = "1: byte order exchanged in each\r\n half-word"] B_0X1 = 1, } impl From<BEX_A> for bool { #[inline(always)] fn from(variant: BEX_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `BEX`"] pub type BEX_R = crate::R<bool, BEX_A>; impl BEX_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BEX_A { match self.bits { false => BEX_A::B_0X0, true => BEX_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == BEX_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == BEX_A::B_0X1 } } #[doc = "Write proxy for field `BEX`"] pub struct BEX_W<'a> { w: &'a mut W, } impl<'a> BEX_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BEX_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Little endianess preserved for bytes"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(BEX_A::B_0X0) } #[doc = "byte order exchanged in each half-word"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(BEX_A::B_0X1) } #[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 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "HEX\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum HEX_A { #[doc = "0: Little endianess preserved for half\r\n words"] B_0X0 = 0, #[doc = "1: half-word order exchanged in each\r\n word"] B_0X1 = 1, } impl From<HEX_A> for bool { #[inline(always)] fn from(variant: HEX_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `HEX`"] pub type HEX_R = crate::R<bool, HEX_A>; impl HEX_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HEX_A { match self.bits { false => HEX_A::B_0X0, true => HEX_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == HEX_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == HEX_A::B_0X1 } } #[doc = "Write proxy for field `HEX`"] pub struct HEX_W<'a> { w: &'a mut W, } impl<'a> HEX_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HEX_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Little endianess preserved for half words"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(HEX_A::B_0X0) } #[doc = "half-word order exchanged in each word"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(HEX_A::B_0X1) } #[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 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "WEX\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum WEX_A { #[doc = "0: Little endianess preserved for\r\n words"] B_0X0 = 0, #[doc = "1: word order exchanged in double\r\n word"] B_0X1 = 1, } impl From<WEX_A> for bool { #[inline(always)] fn from(variant: WEX_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `WEX`"] pub type WEX_R = crate::R<bool, WEX_A>; impl WEX_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> WEX_A { match self.bits { false => WEX_A::B_0X0, true => WEX_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == WEX_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == WEX_A::B_0X1 } } #[doc = "Write proxy for field `WEX`"] pub struct WEX_W<'a> { w: &'a mut W, } impl<'a> WEX_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: WEX_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Little endianess preserved for words"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(WEX_A::B_0X0) } #[doc = "word order exchanged in double word"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(WEX_A::B_0X1) } #[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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Write proxy for field `SWRQ`"] pub struct SWRQ_W<'a> { w: &'a mut W, } impl<'a> SWRQ_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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } impl R { #[doc = "Bit 0 - EN"] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TEIE"] #[inline(always)] pub fn teie(&self) -> TEIE_R { TEIE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - CTCIE"] #[inline(always)] pub fn ctcie(&self) -> CTCIE_R { CTCIE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - BRTIE"] #[inline(always)] pub fn brtie(&self) -> BRTIE_R { BRTIE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - BTIE"] #[inline(always)] pub fn btie(&self) -> BTIE_R { BTIE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - TCIE"] #[inline(always)] pub fn tcie(&self) -> TCIE_R { TCIE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bits 6:7 - PL"] #[inline(always)] pub fn pl(&self) -> PL_R { PL_R::new(((self.bits >> 6) & 0x03) as u8) } #[doc = "Bit 12 - BEX"] #[inline(always)] pub fn bex(&self) -> BEX_R { BEX_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - HEX"] #[inline(always)] pub fn hex(&self) -> HEX_R { HEX_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - WEX"] #[inline(always)] pub fn wex(&self) -> WEX_R { WEX_R::new(((self.bits >> 14) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - EN"] #[inline(always)] pub fn en(&mut self) -> EN_W { EN_W { w: self } } #[doc = "Bit 1 - TEIE"] #[inline(always)] pub fn teie(&mut self) -> TEIE_W { TEIE_W { w: self } } #[doc = "Bit 2 - CTCIE"] #[inline(always)] pub fn ctcie(&mut self) -> CTCIE_W { CTCIE_W { w: self } } #[doc = "Bit 3 - BRTIE"] #[inline(always)] pub fn brtie(&mut self) -> BRTIE_W { BRTIE_W { w: self } } #[doc = "Bit 4 - BTIE"] #[inline(always)] pub fn btie(&mut self) -> BTIE_W { BTIE_W { w: self } } #[doc = "Bit 5 - TCIE"] #[inline(always)] pub fn tcie(&mut self) -> TCIE_W { TCIE_W { w: self } } #[doc = "Bits 6:7 - PL"] #[inline(always)] pub fn pl(&mut self) -> PL_W { PL_W { w: self } } #[doc = "Bit 12 - BEX"] #[inline(always)] pub fn bex(&mut self) -> BEX_W { BEX_W { w: self } } #[doc = "Bit 13 - HEX"] #[inline(always)] pub fn hex(&mut self) -> HEX_W { HEX_W { w: self } } #[doc = "Bit 14 - WEX"] #[inline(always)] pub fn wex(&mut self) -> WEX_W { WEX_W { w: self } } #[doc = "Bit 16 - SWRQ"] #[inline(always)] pub fn swrq(&mut self) -> SWRQ_W { SWRQ_W { w: self } } }
// Copyright 2019, 2020 Wingchain // // 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. //! Subcommand `node` //! start wingchain node use std::path::PathBuf; use primitives::errors::CommonResult; use service::ServiceConfig; use crate::cli::NodeOpt; pub mod cli; pub mod errors; const AGENT_NAME: &str = "Wingchain"; pub fn run(opt: NodeOpt) -> CommonResult<()> { let home = match opt.shared_params.home { Some(home) => home, None => base::get_default_home()?, }; if !home_inited(&home) { return Err(errors::ErrorKind::NotInited(home).into()); } let agent_version = format!("{}/{}", AGENT_NAME, env!("CARGO_PKG_VERSION")); let config = ServiceConfig { home, agent_version, }; service::start(config)?; Ok(()) } fn home_inited(home: &PathBuf) -> bool { home.exists() }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// DashboardSummary : Dashboard summary response. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DashboardSummary { /// List of dashboard definitions. #[serde(rename = "dashboards", skip_serializing_if = "Option::is_none")] pub dashboards: Option<Vec<crate::models::DashboardSummaryDefinition>>, } impl DashboardSummary { /// Dashboard summary response. pub fn new() -> DashboardSummary { DashboardSummary { dashboards: None, } } }
/// Returns the un-synchronized view of self. /// /// See also `UnSyncRef` and `IntoUnSync`. pub trait IntoUnSyncView { type Target; /// Returns the un-synchronized view of self. /// /// What does 'view' mean: The implementation is not really changed, just the interface is /// changed. It's still backed by a synchronized implementation. /// /// ```rust /// use abin::{SBin, NewSBin, BinFactory, IntoUnSyncView, Bin, AnyBin, IntoSync}; /// let string = "This is some string; content of the binary."; /// let sync_bin : SBin = NewSBin::copy_from_slice(string.as_bytes()); /// function_wants_bin(sync_bin.un_sync()); /// /// fn function_wants_bin(value : Bin) { /// // note: the 'value' here is still a synchronized binary (it just wrapped inside an /// // un-synchronized view). /// assert_eq!("This is some string; content of the binary.".as_bytes(), value.as_slice()); /// // we can also un-wrap it to be a synchronized bin again... in this case, this is /// // a cheap operation (but it's not always a cheap operation). /// let _synchronized_again : SBin = value.into_sync(); /// } /// ``` fn un_sync(self) -> Self::Target; } /// Returns the un-synchronized view of self (as reference). /// /// See also `IntoUnSyncView` and `IntoUnSync`. pub trait UnSyncRef { type Target; /// Returns the un-synchronized view of self (as reference). /// /// What does 'view' mean: The implementation is not really changed, just the interface is /// changed. It's still backed by a synchronized implementation. /// /// ```rust /// use abin::{NewSBin, SBin, BinFactory, UnSyncRef, Bin, AnyBin}; /// let string = "This is some string; content of the binary."; /// let sync_bin : SBin = NewSBin::copy_from_slice(string.as_bytes()); /// function_wants_bin(sync_bin.un_sync_ref()); /// /// fn function_wants_bin(value : &Bin) { /// // note: the 'value' here is still a synchronized binary (it just wrapped inside an /// // un-synchronized view). /// assert_eq!("This is some string; content of the binary.".as_bytes(), value.as_slice()); /// } /// ``` fn un_sync_ref(&self) -> &Self::Target; } /// Converts self into the un-synchronized version. /// /// See also `IntoUnSyncView` and `UnSyncRef`. pub trait IntoUnSync { type Target; /// Converts self into the un-synchronized version. /// /// Note: Unlike the `IntoUnSyncView` this does not always just return a view, it might /// actually change the backend (depending on the implementation). This operation /// might be expensive - depending on the implementation (for example a reference counted /// binary must clone its data if there are multiple references to that binary). So if /// there's no good reason to use this, better use the `IntoUnSyncView`. /// /// ```rust /// use abin::{NewSBin, SBin, BinFactory, Bin, IntoUnSync, AnyBin, IntoSync}; /// let string = "This is some string; content of the binary."; /// let sync_bin : SBin = NewSBin::copy_from_slice(string.as_bytes()); /// function_wants_bin(sync_bin.un_sync_convert()); /// /// fn function_wants_bin(value : Bin) { /// // note: The 'value' is no longer sync. E.g. the reference counter of this binary /// // is no longer synchronized. /// assert_eq!("This is some string; content of the binary.".as_bytes(), value.as_slice()); /// // we can also un-wrap it to be a synchronized bin again... in this case, this is /// // a cheap operation (since there are no other references to `value`). /// let _synchronized_again : SBin = value.into_sync(); /// } /// ``` fn un_sync_convert(self) -> Self::Target; }
// https://github.com/elliptic-email/rust-grpc-web/blob/master/examples/seed-wasm-client/src/lib.rs use crate::{ quotes::{chat_client, User}, state::AppState, }; use log::debug; use sycamore::context::{ContextProvider, ContextProviderProps}; use sycamore::prelude::*; use sycamore::reactive::use_context; use wasm_bindgen_futures::spawn_local; #[component(Counter<G>)] fn counter(class: &'static str) -> Template<G> { let state = use_context::<Signal<AppState>>(); template! { p(class=class) { "Value: " (state.get().counter) } } } #[component(Controls<G>)] pub fn controls() -> Template<G> { let state = use_context::<Signal<AppState>>(); let grpc_client = chat_client::Chat::new("http://127.0.0.1:9999".into()); cloned!(() => { spawn_local(async move { let resp = grpc_client.say_hello(User {name: String::from("User"), id: 1}).await; debug!("{:?}", resp); }) }); let increment = cloned!((state) => move |_| state.set(state.get().incr())); let decrement = cloned!((state) => move |_| state.set(state.get().decr())); let reset = cloned!((state) => move |_| state.set(state.get().reset())); template! { button(class="increment", on:click=increment) { "Increment" } button(class="decrement", on:click=decrement) { "Decrement" } button(class="reset", on:click=reset) { "Reset" } } } #[component(App<G>)] pub fn app() -> Template<G> { let counter = Signal::new(AppState::default()); template! { ContextProvider(ContextProviderProps { value: counter, children: move || { template! { div { h2(class="header") { "Counter demo" } Counter("poop") Controls() } } } }) } }
use detect_single_xor; use std::fs; fn main() { let data = fs::read_to_string("encrypted_strings.txt").expect("Unable to read file"); let decrypted = detect_single_xor::detect_single_xor(data); println!("{:?}", &decrypted.encrypted_strings); }
#![cfg(feature = "csvdump")] use diff::*; use std::io::prelude::*; use std::fs::File; use csv; pub fn csv_dump(stats: &[Stat]) { let mut w = csv::Writer::from_memory(); for record in stats { w.encode(LocalStat::from_stat(record.clone())).unwrap(); } let mut f = File::create("data.csv").unwrap(); f.write_all(w.as_bytes()).unwrap(); } #[derive(RustcEncodable)] struct LocalStat { pub id: String, pub author: String, pub email: String, pub inserts: u32, pub dels: u32, pub time: i64, pub offset_minutes: i32, pub message: String, } impl LocalStat { fn from_stat(stat: Stat) -> Self { let message = match stat.message { Some(m) => m, None => "".to_string(), }; // let message = message.replace("\n", "\\n"); LocalStat { id: stat.id.to_string(), author: stat.author, email: stat.email, inserts: stat.inserts, dels: stat.dels, time: stat.time.seconds(), offset_minutes: stat.time.offset_minutes(), message: message, } } }
/// A WAV file // TODO: Follow naming conventions pub struct WavFile { /// The number of channels pub channels: u16, /// The sample rate pub sample_rate: u32, /// The sample bits pub sample_bits: u16, /// The data pub data: Vec<u8>, } impl WavFile { /// Create a new empty WAV file pub fn new() -> Self { WavFile { channels: 0, sample_rate: 0, sample_bits: 0, data: Vec::new(), } } /// Create a WAV file from data pub fn from_data(file_data: &[u8]) -> Self { let mut ret = WavFile::new(); let get = |i: usize| -> u8 { match file_data.get(i) { Some(byte) => *byte, None => 0, } }; let getw = |i: usize| -> u16 { (get(i) as u16) + ((get(i + 1) as u16) << 8) }; let getd = |i: usize| -> u32 { (get(i) as u32) + ((get(i + 1) as u32) << 8) + ((get(i + 2) as u32) << 16) + ((get(i + 3) as u32) << 24) }; let gets = |start: usize, len: usize| -> String { (start..start + len).map(|i| get(i) as char).collect::<String>() }; let mut i = 0; let root_type = gets(i, 4); i += 4; // let root_size = getd(i); i += 4; if root_type == "RIFF" { let media_type = gets(i, 4); i += 4; if media_type == "WAVE" { loop { let chunk_type = gets(i, 4); i += 4; let chunk_size = getd(i); i += 4; if chunk_type.len() == 0 || chunk_size == 0 { break; } if chunk_type == "fmt " { ret.channels = getw(i + 2); ret.sample_rate = getd(i + 4); ret.sample_bits = getw(i + 0xE); } if chunk_type == "data" { ret.data = file_data[i..chunk_size as usize].to_vec(); } i += chunk_size as usize; } } } ret } }
/* * YNAB API Endpoints * * Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudget.com * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://openapi-generator.tech */ #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct HybridTransaction { #[serde(rename = "id")] pub id: String, /// The transaction date in ISO format (e.g. 2016-12-01) #[serde(rename = "date")] pub date: String, /// The transaction amount in milliunits format #[serde(rename = "amount")] pub amount: i64, #[serde(rename = "memo", skip_serializing_if = "Option::is_none")] pub memo: Option<String>, /// The cleared status of the transaction #[serde(rename = "cleared")] pub cleared: Cleared, /// Whether or not the transaction is approved #[serde(rename = "approved")] pub approved: bool, /// The transaction flag #[serde(rename = "flag_color", skip_serializing_if = "Option::is_none")] pub flag_color: Option<FlagColor>, #[serde(rename = "account_id")] pub account_id: String, #[serde(rename = "payee_id", skip_serializing_if = "Option::is_none")] pub payee_id: Option<String>, #[serde(rename = "category_id", skip_serializing_if = "Option::is_none")] pub category_id: Option<String>, /// If a transfer transaction, the account to which it transfers #[serde(rename = "transfer_account_id", skip_serializing_if = "Option::is_none")] pub transfer_account_id: Option<String>, /// If a transfer transaction, the id of transaction on the other side of the transfer #[serde(rename = "transfer_transaction_id", skip_serializing_if = "Option::is_none")] pub transfer_transaction_id: Option<String>, /// If transaction is matched, the id of the matched transaction #[serde(rename = "matched_transaction_id", skip_serializing_if = "Option::is_none")] pub matched_transaction_id: Option<String>, /// If the Transaction was imported, this field is a unique (by account) import identifier. If this transaction was imported through File Based Import or Direct Import and not through the API, the import_id will have the format: 'YNAB:[milliunit_amount]:[iso_date]:[occurrence]'. For example, a transaction dated 2015-12-30 in the amount of -$294.23 USD would have an import_id of 'YNAB:-294230:2015-12-30:1'. If a second transaction on the same account was imported and had the same date and same amount, its import_id would be 'YNAB:-294230:2015-12-30:2'. #[serde(rename = "import_id", skip_serializing_if = "Option::is_none")] pub import_id: Option<String>, /// Whether or not the transaction has been deleted. Deleted transactions will only be included in delta requests. #[serde(rename = "deleted")] pub deleted: bool, /// Whether the hybrid transaction represents a regular transaction or a subtransaction #[serde(rename = "type")] pub _type: Type, /// For subtransaction types, this is the id of the parent transaction. For transaction types, this id will be always be null. #[serde(rename = "parent_transaction_id", skip_serializing_if = "Option::is_none")] pub parent_transaction_id: Option<String>, #[serde(rename = "account_name")] pub account_name: String, #[serde(rename = "payee_name", skip_serializing_if = "Option::is_none")] pub payee_name: Option<String>, #[serde(rename = "category_name", skip_serializing_if = "Option::is_none")] pub category_name: Option<String>, } impl HybridTransaction { pub fn new(id: String, date: String, amount: i64, cleared: Cleared, approved: bool, account_id: String, deleted: bool, _type: Type, account_name: String) -> HybridTransaction { HybridTransaction { id, date, amount, memo: None, cleared, approved, flag_color: None, account_id, payee_id: None, category_id: None, transfer_account_id: None, transfer_transaction_id: None, matched_transaction_id: None, import_id: None, deleted, _type, parent_transaction_id: None, account_name, payee_name: None, category_name: None, } } } /// The cleared status of the transaction #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum Cleared { #[serde(rename = "cleared")] Cleared, #[serde(rename = "uncleared")] Uncleared, #[serde(rename = "reconciled")] Reconciled, } /// The transaction flag #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum FlagColor { #[serde(rename = "red")] Red, #[serde(rename = "orange")] Orange, #[serde(rename = "yellow")] Yellow, #[serde(rename = "green")] Green, #[serde(rename = "blue")] Blue, #[serde(rename = "purple")] Purple, } /// Whether the hybrid transaction represents a regular transaction or a subtransaction #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum Type { #[serde(rename = "transaction")] Transaction, #[serde(rename = "subtransaction")] Subtransaction, }
#[doc = "Register `SCSR` reader"] pub type R = crate::R<SCSR_SPEC>; #[doc = "Register `SCSR` writer"] pub type W = crate::W<SCSR_SPEC>; #[doc = "Field `SRAM2ER` reader - SRAM2 Erase"] pub type SRAM2ER_R = crate::BitReader; #[doc = "Field `SRAM2ER` writer - SRAM2 Erase"] pub type SRAM2ER_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SRAM2BSY` reader - SRAM2 busy by erase operation"] pub type SRAM2BSY_R = crate::BitReader; impl R { #[doc = "Bit 0 - SRAM2 Erase"] #[inline(always)] pub fn sram2er(&self) -> SRAM2ER_R { SRAM2ER_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - SRAM2 busy by erase operation"] #[inline(always)] pub fn sram2bsy(&self) -> SRAM2BSY_R { SRAM2BSY_R::new(((self.bits >> 1) & 1) != 0) } } impl W { #[doc = "Bit 0 - SRAM2 Erase"] #[inline(always)] #[must_use] pub fn sram2er(&mut self) -> SRAM2ER_W<SCSR_SPEC, 0> { SRAM2ER_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "SCSR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`scsr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`scsr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SCSR_SPEC; impl crate::RegisterSpec for SCSR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`scsr::R`](R) reader structure"] impl crate::Readable for SCSR_SPEC {} #[doc = "`write(|w| ..)` method takes [`scsr::W`](W) writer structure"] impl crate::Writable for SCSR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets SCSR to value 0"] impl crate::Resettable for SCSR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::{ grid::{ color::AnsiColor, config::{self, ColoredConfig, SpannedConfig}, dimension::{Dimension, Estimate}, records::{ExactRecords, Records}, }, settings::{ object::{FirstRow, LastRow}, Color, TableOption, }, }; use super::Offset; /// [`BorderText`] writes a custom text on a border. /// /// # Example /// /// ```rust /// use tabled::{Table, settings::style::BorderText, settings::object::Rows}; /// /// let mut table = Table::new(["Hello World"]); /// table /// .with(BorderText::new("+-.table").horizontal(Rows::first())); /// /// assert_eq!( /// table.to_string(), /// "+-.table------+\n\ /// | &str |\n\ /// +-------------+\n\ /// | Hello World |\n\ /// +-------------+" /// ); /// ``` #[derive(Debug)] pub struct BorderText<L> { // todo: change to T and specify to be As<str> text: String, offset: Offset, color: Option<AnsiColor<'static>>, line: L, } impl BorderText<()> { /// Creates a [`BorderText`] instance. /// /// Lines are numbered from 0 to the `count_rows` included /// (`line >= 0 && line <= count_rows`). pub fn new<S: Into<String>>(text: S) -> Self { BorderText { text: text.into(), line: (), offset: Offset::Begin(0), color: None, } } } impl<Line> BorderText<Line> { /// Set a line on which we will set the text. pub fn horizontal<L>(self, line: L) -> BorderText<L> { BorderText { line, text: self.text, offset: self.offset, color: self.color, } } /// Set an offset from which the text will be started. pub fn offset(self, offset: Offset) -> Self { BorderText { offset, text: self.text, line: self.line, color: self.color, } } /// Set a color of the text. pub fn color(self, color: Color) -> Self { BorderText { color: Some(color.into()), text: self.text, line: self.line, offset: self.offset, } } } impl<R, D> TableOption<R, D, ColoredConfig> for BorderText<usize> where R: Records + ExactRecords, for<'a> &'a R: Records, for<'a> D: Estimate<&'a R, ColoredConfig>, D: Dimension, { fn change(self, records: &mut R, cfg: &mut ColoredConfig, dims: &mut D) { dims.estimate(records, cfg); let shape = (records.count_rows(), records.count_columns()); let line = self.line; set_horizontal_chars(cfg, dims, self.offset, line, &self.text, &self.color, shape); } } impl<R, D> TableOption<R, D, ColoredConfig> for BorderText<FirstRow> where R: Records + ExactRecords, for<'a> &'a R: Records, for<'a> D: Estimate<&'a R, ColoredConfig>, D: Dimension, { fn change(self, records: &mut R, cfg: &mut ColoredConfig, dims: &mut D) { dims.estimate(records, cfg); let shape = (records.count_rows(), records.count_columns()); let line = 0; set_horizontal_chars(cfg, dims, self.offset, line, &self.text, &self.color, shape); } } impl<R, D> TableOption<R, D, ColoredConfig> for BorderText<LastRow> where R: Records + ExactRecords, for<'a> &'a R: Records, for<'a> D: Estimate<&'a R, ColoredConfig>, D: Dimension, { fn change(self, records: &mut R, cfg: &mut ColoredConfig, dims: &mut D) { dims.estimate(records, cfg); let shape = (records.count_rows(), records.count_columns()); let line = records.count_rows(); set_horizontal_chars(cfg, dims, self.offset, line, &self.text, &self.color, shape); } } fn set_horizontal_chars<D: Dimension>( cfg: &mut SpannedConfig, dims: &D, offset: Offset, line: usize, text: &str, color: &Option<AnsiColor<'static>>, shape: (usize, usize), ) { let (_, count_columns) = shape; let pos = get_start_pos(cfg, dims, offset, count_columns); let pos = match pos { Some(pos) => pos, None => return, }; let mut chars = text.chars(); let mut i = cfg.has_vertical(0, count_columns) as usize; if i == 1 && pos == 0 { let c = match chars.next() { Some(c) => c, None => return, }; let mut b = cfg.get_border((line, 0), shape); b.left_top_corner = b.left_top_corner.map(|_| c); cfg.set_border((line, 0), b); if let Some(color) = color.as_ref() { let mut b = cfg.get_border_color((line, 0), shape).cloned(); b.left_top_corner = Some(color.clone()); cfg.set_border_color((line, 0), b); } } for col in 0..count_columns { let w = dims.get_width(col); if i + w > pos { for off in 0..w { if i + off < pos { continue; } let c = match chars.next() { Some(c) => c, None => return, }; cfg.set_horizontal_char((line, col), c, config::Offset::Begin(off)); if let Some(color) = color.as_ref() { cfg.set_horizontal_color( (line, col), color.clone(), config::Offset::Begin(off), ); } } } i += w; if cfg.has_vertical(col + 1, count_columns) { i += 1; if i > pos { let c = match chars.next() { Some(c) => c, None => return, }; let mut b = cfg.get_border((line, col), shape); b.right_top_corner = b.right_top_corner.map(|_| c); cfg.set_border((line, col), b); if let Some(color) = color.as_ref() { let mut b = cfg.get_border_color((line, col), shape).cloned(); b.right_top_corner = Some(color.clone()); cfg.set_border_color((line, col), b); } } } } } fn get_start_pos<D: Dimension>( cfg: &SpannedConfig, dims: &D, offset: Offset, count_columns: usize, ) -> Option<usize> { let totalw = total_width(cfg, dims, count_columns); match offset { Offset::Begin(i) => { if i > totalw { None } else { Some(i) } } Offset::End(i) => { if i > totalw { None } else { Some(totalw - i) } } } } fn total_width<D: Dimension>(cfg: &SpannedConfig, dims: &D, count_columns: usize) -> usize { let mut totalw = cfg.has_vertical(0, count_columns) as usize; for col in 0..count_columns { totalw += dims.get_width(col); totalw += cfg.has_vertical(col + 1, count_columns) as usize; } totalw }
import option::{option,none,some}; import geom::*; enum space { robot, wall, rock, lambda, closed_lift, open_lift, earth, empty, tramp(u8), target(u8), beard, razor, horock } impl rock for space { pure fn is_rock() -> bool { alt self { rock | horock { true } _ { false } } } } fn print(mine: mine) -> ~[str] { do mine.read |img| { let n = img.len(); do vec::from_fn(n) |i| { str::from_chars(img[n - 1 - i] .map(|s| char_of_space(space_show_(s)))) } } } fn parse(lines: &[str]) -> (mine_image, &[str]) { let mut maxlen = 0; let mut rows = ~[]; let mut metaline = 0; for lines.eachi |i, line| { let line = str::trim_right(copy line); // XXX \r metaline = i + 1; if line == "" { break; } maxlen = uint::max(maxlen, line.len()); let row = vec::to_mut(str::chars(line) .map(|c| space_hide_(space_of_char(c)))); vec::unshift(rows, row); } let img = do vec::map_consume(rows) |+line| { if line.len() == maxlen { line } else { line + vec::from_elem(maxlen - line.len(), space_hide_(empty)) } }; ret (img, vec::view(lines, metaline, lines.len())) } type mine = @{ mut repr: mine_repr }; type mine_image = ~[~[mut space_]]; type mine_change = ~[{where: point, what: space}]; type mine_change_ = ~[{where: point, what_: space_}]; enum mine_repr { root(mine_image), diff(mine_change_, mine), under_construction } impl geom for mine_image { pure fn get(p: point) -> space { if self.box().contains(p) { let {x, y} = p; space_show_(self[y][x]) } else { wall } } pure fn box() -> rect { {x: 0, y: 0, w: self[0].len() as length, h: self.len() as length} } } fn new_mine(+image : mine_image) -> mine { @{ mut repr: root(image) } } impl mine for mine { fn read<R>(f: fn (&mine_image) -> R) -> R { let rval: R; self.focus(); let mut self_repr = under_construction; self_repr <-> self.repr; alt check self_repr { root(img) { rval = f(img) } } self.repr <-> self_repr; ret rval; } fn edit(+ch: mine_change) -> mine { if ch.len() == 0 { ret self; } let ch_ = do vec::map_consume(ch) |+ww| { { where: ww.where, what_: space_hide_(ww.what) } }; @{ mut repr: diff(ch_, self) } } fn focus() { alt check self.repr { root(*) { ret } diff(*) { } } let mut diff_repr = under_construction; let mut root_repr = under_construction; let rdiff_repr: mine_repr; let other: mine; diff_repr <-> self.repr; alt check diff_repr { diff(diffs, d_other) { other = d_other; other.focus(); root_repr <-> other.repr; alt check root_repr { root(img) { let n = diffs.len(); // Yes, we have no rev_map. // Also, in principle this could reuse the old vector. let rdiffs = do vec::from_fn(n) |i| { let d = diffs[n - 1 - i]; {where: d.where, what_: img[d.where.y][d.where.x]} }; // Cannot iterate an impure action over the borrowed diffs. for uint::range(0, n) |i| { let {where, what_} = diffs[i]; img[where.y][where.x] = what_; } rdiff_repr = diff(rdiffs, self); } } } } self.repr <- root_repr; other.repr <- rdiff_repr; } } impl geom for mine { pure fn get(p: point) -> space { alt check self.repr { root(img) { img.get(p) } diff(diffs, other) { alt vec::rfind(diffs, |d|d.where == p) { some(d) { space_show_(d.what_) } none { other.get(p) } } } } } } pure fn space_of_char(c: char) -> space { alt c { 'R' { robot } '#' { wall } '*' { rock } '\\' { lambda } 'L' { closed_lift } 'O' { open_lift } '.' { earth } ' ' { empty } 'A' to 'I' { tramp((c as u8) - ('A' as u8) + 1) } '1' to '9' { target((c as u8) - ('1' as u8) + 1) } 'W' { beard } '!' { razor } '@' { horock } _ { fail } } } pure fn char_of_space(s: space) -> char { alt s { robot { 'R' } wall { '#' } rock { '*' } lambda { '\\' } closed_lift { 'L' } open_lift { 'O' } earth { '.' } empty { ' ' } tramp(x) { assert(x - 1 < 9); (x + ('A' as u8) - 1) as char } target(x) { assert(x - 1 < 9); (x + ('1' as u8) - 1) as char } beard { 'W' } razor { '!' } horock { '@' } } } enum space_ = u8; pure fn space_hide_(s : space) -> space_ { space_(alt (s) { robot { 0 } wall { 1 } rock { 2 } lambda { 3 } closed_lift { 4 } open_lift { 5 } earth { 6 } empty { 7 } beard { 8 } razor { 9 } horock { 10 } tramp(x) { assert(x<16); 64+x } target(x) { assert(x<16); 48+x } }) } pure fn space_show_(s : space_) -> space { alt check *s & 240 { 0 { alt check *s { 0 { robot } 1 { wall } 2 { rock } 3 { lambda } 4 { closed_lift } 5 { open_lift } 6 { earth } 7 { empty } 8 { beard } 9 { razor } 10 { horock } } } 64 { tramp(*s - 64) } 48 { target(*s - 48) } } }
fn main() { slice_1(); slice_test(); string_test(); } fn slice_1() { let mut s = String::from("hello world"); { let word = first_word(&s); println!("first word is until {}.", word); } s.clear(); { let s = String::from("hello"); let len = s.len(); let slice = &s[0..len]; let slice = &s[3..]; } { let arr = [1, 2, 3, 4, 5]; let slice1 = &arr[..4]; for i in slice1 { println!("slice1! {}", i); } let slice2 = &arr[2..]; for i in slice2 { println!("slice2! {}", i); } } } fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn slice_test() { let numbers: [i32; 3] = [1, 2, 3]; assert_eq!([1, 2, 3], &numbers[..]); for n in numbers.iter() { println!("number! {}", n); } } fn string_test() { let str1 = "hello"; let str2: &str = "world"; let str3: String = String::from("Rust is awesome!"); let str4: &str = &str3[2..8]; let str5: &str = &str2[2..5]; println!("str1=>{}", str1); println!("str2=>{}", str2); println!("str3=>{}", str3); println!("str4=>{}", str4); println!("str5=>{}", str5); }
// https://github.com/PacktPublishing/Hands-On-Data-Structures-and-Algorithms-with-Rust/blob/master/Chapter04/src/doubly_linked_list.rs use std::cell::{Ref, RefCell}; use std::rc::Rc; type Link = Option<Rc<RefCell<Node>>>; #[derive(Clone)] struct Node { value:String, next: Link, prev: Link } #[derive(Clone)] pub struct BetterTransactionLog { head: Link, tail: Link, pub length: u64 } impl IntoIterator for BetterTransactionLog { type Item = String; type IntoIter = ListIterator; fn into_iter(self) -> Self::IntoIter { ListIterator::new(self.head) } } pub struct ListIterator { current: Link, } impl ListIterator { fn new(start_at: Link) -> ListIterator { ListIterator { current: start_at } } } impl Iterator for ListIterator { type Item = String; fn next(&mut self) -> Option<String> { let current = &self.current; let mut result = None; self.current = match current { Some(ref current) => { let current = current.borrow(); result = Some(current.value.clone()); current.next.clone() }, None => None }; result } } impl DoubleEndedIterator for ListIterator { fn next_back(&mut self) -> Option<String> { let current = &self.current; let mut result = None; self.current = match current{ Some(ref current) => { let current = current.borrow(); result = Some(current.value.clone()); current.prev.clone() }, None => None }; result } } impl Node { fn new(value:String) -> Rc<RefCell<Node>> { Rc::new(RefCell::new(Node { value: value, next: None, prev: None })) } } impl BetterTransactionLog { pub fn new_empty() -> BetterTransactionLog { BetterTransactionLog { head: None, tail: None, length: 0, } } pub fn append(&mut self, value:String) { let new = Node::new(value); match self.tail.take() { Some(old) => { old.borrow_mut().next = Some(new.clone()); new.borrow_mut().prev = Some(old); }, None => self.head = Some(new.clone()), } self.length += 1; self.tail = Some(new); } pub fn pop(&mut self) -> Option<String> { self.head.take().map( |head| { if let Some(next) = head.borrow_mut().next.take() { self.head = Some(next); } else { self.tail.take(); } self.length -= 1; Rc::try_unwrap(head) .ok() .expect("Something is terribly wrong") .into_inner() .value } ) } pub fn back_iter(self) -> ListIterator { ListIterator::new(self.tail) } pub fn iter(&self) -> ListIterator { ListIterator::new(self.head.clone()) } } fn main() { println!("double linked"); let mut log = BetterTransactionLog::new_empty(); log.append("test1".to_string()); log.append("test2".to_string()); log.append("test3".to_string()); let mut iter = log.clone().into_iter(); println!("{}", iter.next().unwrap()); println!("{}", iter.next().unwrap()); println!("{}", iter.next_back().unwrap()); println!("{}", iter.next_back().unwrap()); println!("{}", iter.next().unwrap()); println!("new iter"); let iter = log.clone().into_iter(); for l in iter { println!("{}", l); } }
// Copyright 2018-2019 Mozilla // // 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::{io, num, str}; use thiserror::Error; #[derive(Debug, Error)] pub enum MigrateError { #[error("database not found: {0:?}")] DatabaseNotFound(String), #[error("{0}")] FromString(String), #[error("couldn't determine bit depth")] IndeterminateBitDepth, #[error("I/O error: {0:?}")] IoError(#[from] io::Error), #[error("invalid DatabaseFlags bits")] InvalidDatabaseBits, #[error("invalid data version")] InvalidDataVersion, #[error("invalid magic number")] InvalidMagicNum, #[error("invalid NodeFlags bits")] InvalidNodeBits, #[error("invalid PageFlags bits")] InvalidPageBits, #[error("invalid page number")] InvalidPageNum, #[error("lmdb backend error: {0}")] LmdbError(#[from] lmdb::Error), #[error("string conversion error")] StringConversionError, #[error("TryFromInt error: {0:?}")] TryFromIntError(#[from] num::TryFromIntError), #[error("unexpected Page variant")] UnexpectedPageVariant, #[error("unexpected PageHeader variant")] UnexpectedPageHeaderVariant, #[error("unsupported PageHeader variant")] UnsupportedPageHeaderVariant, #[error("UTF8 error: {0:?}")] Utf8Error(#[from] str::Utf8Error), } impl From<&str> for MigrateError { fn from(e: &str) -> MigrateError { MigrateError::FromString(e.to_string()) } } impl From<String> for MigrateError { fn from(e: String) -> MigrateError { MigrateError::FromString(e) } }
use std::thread; use std::sync::mpsc; // Channels use std::time::Duration; use std::sync::{Mutex, Arc}; use rand::Rng; fn main() { simle_thread(); //using_channels(); //shared_mutex(); } fn simle_thread() { // Give a thread a closure let handle = thread::spawn(|| { for i in 1..6 { println!("hi number {} from the spawned thread!", i); } }); // Here code can be executed on the main thread thread::sleep(Duration::from_millis(3)); println!("Hi from the main thread"); // Join waits for thread to complete handle.join().unwrap(); } fn using_channels() { // Create my sender and reciever (just 1 of each) let (tx, rx) = mpsc::channel(); let val = "She turned me into a"; let types = ["newt", "moster", "human"]; //let tx1 = mpsc::Sender::clone(&tx); thread::spawn(move || { let secret_number = rand::thread_rng().gen_range(0, 3); let message = format!("{} {}", val, &types[secret_number]); tx.send(message).unwrap(); // message dies here }); // thread::spawn(move || { // let secret_number = rand::thread_rng().gen_range(0, 3); // let message = format!("{} {}", val, &types[secret_number]); // tx1.send(message).unwrap(); // message dies here // }); for message in rx { println!("{}", message); if message.contains("newt") { println!("but I got better again"); } } } fn shared_mutex() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); }
pub fn square_of_sum(i: u32) -> u32 { let mut sum = 0; // sum: u32 for x in 1..(i+1) { sum += x; } sum * sum } pub fn sum_of_squares(i: u32) -> u32 { let mut sum = 0; // sum: u32 for x in 1..(i+1) { sum += x * x; } sum } pub fn difference(i: u32) -> u32 { square_of_sum(i) - sum_of_squares(i) }
use std::ops::{Index, IndexMut}; use minivec::{mini_vec, MiniVec}; use crate::heap::cell::*; use crate::vm::VirtualMachine; pub struct FixedStorage<T: Cell + Copy> { pub(crate) data: MiniVec<T>, } impl<T: Cell + Copy + Default> FixedStorage<T> { pub fn reserve(&mut self, vm: &mut VirtualMachine, n: usize) { /*if n > self.capacity() { let next = if n == 0 { 0 } else if n < 8 { 8 } else { clp2(n) }; let ptr = GcArray::<T>::new(vm.space(), next, T::default()); unsafe { std::ptr::copy_nonoverlapping(self.data.begin(), ptr.begin(), self.data.len()); } self.data = ptr; }*/ self.data.reserve(n); } pub fn resize(&mut self, vm: &mut VirtualMachine, n: usize, value: T) { /*let previous = self.capacity(); self.reserve(vm, n); if previous < self.capacity() { for i in previous..self.capacity() { self.data[i] = value; } }*/ self.data.resize(n, value); } pub fn size(&self) -> usize { self.capacity() } pub fn capacity(&self) -> usize { self.data.len() } pub fn new(vm: &mut VirtualMachine, init: T) -> Self { Self { data: MiniVec::new(), } } pub fn with_capacity(vm: &mut VirtualMachine, cap: usize, init: T) -> Self { if cap == 0 { return Self { data: MiniVec::new(), }; } Self { data: mini_vec![init;cap], } } pub fn with(vm: &mut VirtualMachine, cap: usize, value: T) -> Self { let mut this = Self::new(vm, T::default()); this.resize(vm, cap, value); this } } impl<T: Cell + Copy> Index<usize> for FixedStorage<T> { type Output = T; fn index(&self, index: usize) -> &Self::Output { &self.data[index] } } impl<T: Cell + Copy> IndexMut<usize> for FixedStorage<T> { fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.data[index] } } impl<T: Cell + Copy> Cell for FixedStorage<T> {} unsafe impl<T: Cell + Copy> Trace for FixedStorage<T> { fn trace(&self, tracer: &mut dyn Tracer) { /*for i in 0..self.data.len() { self.data[i].trace(tracer); }*/ self.data.iter().for_each(|x| x.trace(tracer)); } } #[cfg(feature = "debug-snapshots")] impl<T: Cell + Copy> serde::Serialize for FixedStorage<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let mut x = serializer.serialize_struct("FixedStorage", 1)?; x.serialize_field("data", &self.data)?; x.end() } }
use std::ffi::{OsStr, OsString}; use std::fs::File; use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; use indicatif::{ProgressBar, ProgressStyle}; use memmap::MmapOptions; use structopt::StructOpt; fn search(test: &[u8], file: &[u8]) { let progress = ProgressBar::new((file.len() - test.len()) as u64) .with_style(ProgressStyle::default_bar().template("{wide_bar} {bytes}/{total_bytes}")); for file_pos in 0..file.len() - test.len() { if test == &file[file_pos..file_pos + test.len()] { progress.println(format!( "Match from {} to {}", file_pos, file_pos + test.len() )); } // Only update progress bar every megabyte in case it's too expensive if file_pos % (1024 * 1024) == 0 { progress.inc(1024 * 1024) } } } fn os_str_to_vec(s: &OsStr) -> Result<Box<[u8]>, OsString> { if s.is_empty() { Err("Non-empty pattern required".into()) } else { Ok(s.as_bytes().to_owned().into_boxed_slice()) } } #[derive(StructOpt, Debug)] struct Opt { /// The length of the region to check. Defaults to the length of the file. #[structopt(short, long)] length: Option<usize>, /// The text to search for #[structopt(parse(try_from_os_str = os_str_to_vec))] pattern: Box<[u8]>, /// The file to search in #[structopt(parse(from_os_str))] file: PathBuf, } fn main() { let opt = Opt::from_args(); assert!(opt.pattern.len() > 0, "pattern should not be empty"); let file = File::open(opt.file).expect("could not open file"); let mut mmap_opts = MmapOptions::new(); if let Some(len) = opt.length { mmap_opts.len(len); } let mmap = unsafe { mmap_opts.map(&file).expect("could not mmap file") }; search(&opt.pattern, &mmap[..]); }
use ast; use ast::AstExpressionNode; use ast::Block; use ast::Expression; use ast::Expression::*; use ast::Function; use ast::FunctionCall; use ast::Program; use ast::Statement; use ast::VarType; use ast_helper::is_pointer; use type_checker_helper::type_contains; use std::collections::VecDeque; struct PointerArithmeticTransformer; fn multiply_by(left: AstExpressionNode, right: AstExpressionNode, typ: &VarType) -> AstExpressionNode { assert!(left.typ.is_some() && right.typ.is_some()); assert!(type_contains(typ, left.typ.as_ref().unwrap())); assert!(type_contains(typ, right.typ.as_ref().unwrap())); let expr = BinaryOp(ast::BinaryOp::Multiply, Box::new(left), Box::new(right)); let mut new_expr = AstExpressionNode::new(expr); new_expr.typ = Some(typ.clone()); new_expr } fn replace_pointer_arithmetic(mut left: AstExpressionNode, mut right: AstExpressionNode, pointer_type: &VarType) -> (AstExpressionNode, AstExpressionNode) { let mut type_size = AstExpressionNode::new( SizeOf((*pointer_type).clone())); type_size.typ = Some(VarType::Int); if is_pointer(left.typ.as_ref().unwrap()) { right = multiply_by(type_size, right, &VarType::Int); } else if is_pointer(right.typ.as_ref().unwrap()) { left = multiply_by(type_size, left, &VarType::Int); } else { panic!("how are neither types a pointer?"); } (left, right) } impl PointerArithmeticTransformer { pub fn new() -> PointerArithmeticTransformer { PointerArithmeticTransformer } fn transform_call(&self, mut fn_call: FunctionCall) -> FunctionCall { let mut new_args = Vec::new(); while !fn_call.args_exprs.is_empty() { let expr = fn_call.args_exprs.remove(0); new_args.push(self.transform_expr(expr)); } FunctionCall { name: fn_call.name, args_exprs: new_args } } fn transform_expr(&self, expr_node: AstExpressionNode) -> AstExpressionNode { let new_expr = match expr_node.expr { BinaryOp(op, l_node, r_node) => { assert!(l_node.typ.is_some() && r_node.typ.is_some()); assert!(expr_node.typ.is_some()); let binop_type = expr_node.typ.as_ref().unwrap(); let mut left = self.transform_expr(*l_node); let mut right = self.transform_expr(*r_node); if let VarType::Pointer(_, ref typ) = *binop_type { if op == ast::BinaryOp::Plus || op == ast::BinaryOp::Minus { let (nl, nr) = replace_pointer_arithmetic(left, right, typ); left = nl; right = nr; } } Expression::BinaryOp(op.clone(), Box::new(left), Box::new(right)) } Call(fn_call) => { Call(self.transform_call(fn_call)) } Reference(expr) => { Reference(Box::new(self.transform_expr(*expr))) } Dereference(expr) => { Dereference(Box::new(self.transform_expr(*expr))) } FieldAccess(expr, field_name) => { FieldAccess(Box::new(self.transform_expr(*expr)), field_name) } _ => expr_node.expr }; let mut node = AstExpressionNode::new(new_expr); node.typ = expr_node.typ.clone(); node } // Given a statement, return a list of statements to replace it with fn transform_stmt(&self, stmt: Statement) -> Statement { // FIXME: Do match *&mut stmt instead, to avoid having all the weird returns match stmt { Statement::Return(expr) => { Statement::Return(self.transform_expr(expr)) } Statement::If(expr, mut then_block, else_block_opt) => { self.transform_block(&mut then_block); let transformed_else_block = if let Some(mut else_block) = else_block_opt { self.transform_block(&mut else_block); Some(else_block) } else { None }; Statement::If(self.transform_expr(expr), then_block, transformed_else_block) } Statement::While(expr, mut block) => { self.transform_block(&mut block); Statement::While(self.transform_expr(expr), block) } Statement::Let(name, typ, value_expr) => { let new_val_expr = if let Some(expr) = value_expr { Some(self.transform_expr(expr)) } else { None }; Statement::Let(name, typ, new_val_expr) } Statement::Assign(left_expr, right_expr) => { Statement::Assign(self.transform_expr(left_expr), self.transform_expr(right_expr)) } Statement::Call(fn_call) => { Statement::Call(self.transform_call(fn_call)) } Statement::Print(expr) => { Statement::Print(self.transform_expr(expr)) } } } fn transform_block(&self, block: &mut ast::Block) { // Analyze each statement, and replace it with whatever the // transform function tells us to let mut new_statements = VecDeque::new(); while let Some(stmt) = block.statements.pop_front() { let replacement = self.transform_stmt(stmt); new_statements.push_back(replacement); } block.statements = new_statements; } fn transform_function(&self, function: &mut Function) { self.transform_block(&mut function.statements); } pub fn transform_program(&self, program: &mut Program) { for fun in program.functions.iter_mut() { self.transform_function(fun); } } } pub fn transform_pointer_arithmetic(program: &mut Program) { let t = PointerArithmeticTransformer::new(); t.transform_program(program); }
pub mod random_bot; pub mod killer_bot; pub mod test_bot; pub mod common; pub use crate::bot::random_bot::*; pub use crate::bot::killer_bot::*; pub use crate::bot::test_bot::*; pub use crate::bot::common::*;
extern crate clap; use clap::{App, Arg, SubCommand}; use ot::{Replica, DB}; use uuid::Uuid; fn main() { let matches = App::new("Rask") .version("0.1") .author("Dustin J. Mitchell <dustin@v.igoro.us>") .about("Replacement for TaskWarrior") .subcommand( SubCommand::with_name("add") .about("adds a task") .arg(Arg::with_name("title").help("task title").required(true)), ) .subcommand(SubCommand::with_name("list").about("lists tasks")) .get_matches(); let mut replica = Replica::new(DB::new().into()); match matches.subcommand() { ("add", Some(matches)) => { let uuid = Uuid::new_v4(); replica.create_task(uuid).unwrap(); replica .update_task(uuid, "title", Some(matches.value_of("title").unwrap())) .unwrap(); } ("list", _) => { for task in replica.all_tasks() { println!("{:?}", task); } } ("", None) => { unreachable!(); } _ => unreachable!(), }; }
use std::io; fn get_line() -> String { let mut input = String::new(); let stdin = io::stdin(); stdin.read_line(&mut input).unwrap(); input } fn main() { let mut total = 0; // Loop until the line doesn't include enough numbers for the calculation loop { let line = get_line(); let line = line.trim(); // Collect all of the numbers into a Vec let nums: Vec<&str> = line.split("x").collect(); // If the Vec isn't long enough, break the loop if nums.len() < 3 { break; } let length: i32 = nums[0].parse().unwrap(); let width: i32 = nums[1].parse().unwrap(); let height: i32 = nums[2].parse().unwrap(); let surface_area = (2 * length * width) + (2 * width * height) + (2 * height * length); total += surface_area; // Calculate slack let mut sides = vec![length, width, height]; sides.sort(); let slack = sides[0] * sides[1]; total += slack; } println!("Total surface area: {}", total); }
use super::{param_header::*, param_type::*, *}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::fmt; #[derive(Debug, Copy, Clone, PartialEq)] #[repr(C)] pub(crate) enum HmacAlgorithm { HmacResv1 = 0, HmacSha128 = 1, HmacResv2 = 2, HmacSha256 = 3, Unknown, } impl fmt::Display for HmacAlgorithm { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match *self { HmacAlgorithm::HmacResv1 => "HMAC Reserved (0x00)", HmacAlgorithm::HmacSha128 => "HMAC SHA-128", HmacAlgorithm::HmacResv2 => "HMAC Reserved (0x02)", HmacAlgorithm::HmacSha256 => "HMAC SHA-256", _ => "Unknown HMAC Algorithm", }; write!(f, "{}", s) } } impl From<u16> for HmacAlgorithm { fn from(v: u16) -> HmacAlgorithm { match v { 0 => HmacAlgorithm::HmacResv1, 1 => HmacAlgorithm::HmacSha128, 2 => HmacAlgorithm::HmacResv2, 3 => HmacAlgorithm::HmacSha256, _ => HmacAlgorithm::Unknown, } } } #[derive(Default, Debug, Clone, PartialEq)] pub(crate) struct ParamRequestedHmacAlgorithm { pub(crate) available_algorithms: Vec<HmacAlgorithm>, } impl fmt::Display for ParamRequestedHmacAlgorithm { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{} {}", self.header(), self.available_algorithms .iter() .map(|ct| ct.to_string()) .collect::<Vec<String>>() .join(" "), ) } } impl Param for ParamRequestedHmacAlgorithm { fn header(&self) -> ParamHeader { ParamHeader { typ: ParamType::ReqHmacAlgo, value_length: self.value_length() as u16, } } fn unmarshal(raw: &Bytes) -> Result<Self, Error> { let header = ParamHeader::unmarshal(raw)?; let reader = &mut raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); let mut available_algorithms = vec![]; let mut offset = 0; while offset + 1 < header.value_length() { let a: HmacAlgorithm = reader.get_u16().into(); if a == HmacAlgorithm::HmacSha128 || a == HmacAlgorithm::HmacSha256 { available_algorithms.push(a); } else { return Err(Error::ErrInvalidAlgorithmType); } offset += 2; } Ok(ParamRequestedHmacAlgorithm { available_algorithms, }) } fn marshal_to(&self, buf: &mut BytesMut) -> Result<usize, Error> { self.header().marshal_to(buf)?; for a in &self.available_algorithms { buf.put_u16(*a as u16); } Ok(buf.len()) } fn value_length(&self) -> usize { 2 * self.available_algorithms.len() } fn clone_to(&self) -> Box<dyn Param + Send + Sync> { Box::new(self.clone()) } fn as_any(&self) -> &(dyn Any + Send + Sync) { self } }